Remove AsmPrinter::needsRelocationsForDwarfStringPool() since it's
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfUnit.cpp
1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for constructing a dwarf compile unit.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "dwarfdebug"
15
16 #include "DwarfUnit.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfDebug.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/DIBuilder.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Target/Mangler.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Support/CommandLine.h"
34
35 using namespace llvm;
36
37 static cl::opt<bool>
38 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
39                        cl::desc("Generate DWARF4 type units."),
40                        cl::init(false));
41
42 /// Unit - Unit constructor.
43 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
44                      DwarfDebug *DW, DwarfFile *DWU)
45     : UniqueID(UID), Node(Node), UnitDie(D), DebugInfoOffset(0), Asm(A), DD(DW),
46       DU(DWU), IndexTyDie(0), Section(0) {
47   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
48 }
49
50 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
51                                    AsmPrinter *A, DwarfDebug *DW,
52                                    DwarfFile *DWU)
53     : DwarfUnit(UID, D, Node, A, DW, DWU) {
54   insertDIE(Node, D);
55 }
56
57 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, uint16_t Language,
58                              AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
59     : DwarfUnit(UID, D, DICompileUnit(), A, DW, DWU), Language(Language) {}
60
61 /// ~Unit - Destructor for compile unit.
62 DwarfUnit::~DwarfUnit() {
63   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
64     DIEBlocks[j]->~DIEBlock();
65 }
66
67 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
68 /// information entry.
69 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
70   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
71   return Value;
72 }
73
74 /// getDefaultLowerBound - Return the default lower bound for an array. If the
75 /// DWARF version doesn't handle the language, return -1.
76 int64_t DwarfUnit::getDefaultLowerBound() const {
77   switch (getLanguage()) {
78   default:
79     break;
80
81   case dwarf::DW_LANG_C89:
82   case dwarf::DW_LANG_C99:
83   case dwarf::DW_LANG_C:
84   case dwarf::DW_LANG_C_plus_plus:
85   case dwarf::DW_LANG_ObjC:
86   case dwarf::DW_LANG_ObjC_plus_plus:
87     return 0;
88
89   case dwarf::DW_LANG_Fortran77:
90   case dwarf::DW_LANG_Fortran90:
91   case dwarf::DW_LANG_Fortran95:
92     return 1;
93
94   // The languages below have valid values only if the DWARF version >= 4.
95   case dwarf::DW_LANG_Java:
96   case dwarf::DW_LANG_Python:
97   case dwarf::DW_LANG_UPC:
98   case dwarf::DW_LANG_D:
99     if (dwarf::DWARF_VERSION >= 4)
100       return 0;
101     break;
102
103   case dwarf::DW_LANG_Ada83:
104   case dwarf::DW_LANG_Ada95:
105   case dwarf::DW_LANG_Cobol74:
106   case dwarf::DW_LANG_Cobol85:
107   case dwarf::DW_LANG_Modula2:
108   case dwarf::DW_LANG_Pascal83:
109   case dwarf::DW_LANG_PLI:
110     if (dwarf::DWARF_VERSION >= 4)
111       return 1;
112     break;
113   }
114
115   return -1;
116 }
117
118 /// Check whether the DIE for this MDNode can be shared across CUs.
119 static bool isShareableAcrossCUs(DIDescriptor D) {
120   // When the MDNode can be part of the type system, the DIE can be shared
121   // across CUs.
122   // Combining type units and cross-CU DIE sharing is lower value (since
123   // cross-CU DIE sharing is used in LTO and removes type redundancy at that
124   // level already) but may be implementable for some value in projects
125   // building multiple independent libraries with LTO and then linking those
126   // together.
127   return (D.isType() ||
128           (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
129          !GenerateDwarfTypeUnits;
130 }
131
132 /// getDIE - Returns the debug information entry map slot for the
133 /// specified debug variable. We delegate the request to DwarfDebug
134 /// when the DIE for this MDNode can be shared across CUs. The mappings
135 /// will be kept in DwarfDebug for shareable DIEs.
136 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
137   if (isShareableAcrossCUs(D))
138     return DD->getDIE(D);
139   return MDNodeToDieMap.lookup(D);
140 }
141
142 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
143 /// when the DIE for this MDNode can be shared across CUs. The mappings
144 /// will be kept in DwarfDebug for shareable DIEs.
145 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
146   if (isShareableAcrossCUs(Desc)) {
147     DD->insertDIE(Desc, D);
148     return;
149   }
150   MDNodeToDieMap.insert(std::make_pair(Desc, D));
151 }
152
153 /// addFlag - Add a flag that is true.
154 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
155   if (DD->getDwarfVersion() >= 4)
156     Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
157   else
158     Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
159 }
160
161 /// addUInt - Add an unsigned integer attribute data and value.
162 ///
163 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
164                         Optional<dwarf::Form> Form, uint64_t Integer) {
165   if (!Form)
166     Form = DIEInteger::BestForm(false, Integer);
167   DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
168                         DIEInteger(Integer);
169   Die->addValue(Attribute, *Form, Value);
170 }
171
172 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
173   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
174 }
175
176 /// addSInt - Add an signed integer attribute data and value.
177 ///
178 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
179                         Optional<dwarf::Form> Form, int64_t Integer) {
180   if (!Form)
181     Form = DIEInteger::BestForm(true, Integer);
182   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
183   Die->addValue(Attribute, *Form, Value);
184 }
185
186 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
187                         int64_t Integer) {
188   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
189 }
190
191 /// addString - Add a string attribute data and value. We always emit a
192 /// reference to the string pool instead of immediate strings so that DIEs have
193 /// more predictable sizes. In the case of split dwarf we emit an index
194 /// into another table which gets us the static offset into the string
195 /// table.
196 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
197                           StringRef String) {
198   DIEValue *Value;
199   dwarf::Form Form;
200   if (!DD->useSplitDwarf()) {
201     MCSymbol *Symb = DU->getStringPoolEntry(String);
202     if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
203       Value = new (DIEValueAllocator) DIELabel(Symb);
204     else {
205       MCSymbol *StringPool = DU->getStringPoolSym();
206       Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
207     }
208     Form = dwarf::DW_FORM_strp;
209   } else {
210     unsigned idx = DU->getStringPoolIndex(String);
211     Value = new (DIEValueAllocator) DIEInteger(idx);
212     Form = dwarf::DW_FORM_GNU_str_index;
213   }
214   DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
215   Die->addValue(Attribute, Form, Str);
216 }
217
218 /// addLocalString - Add a string attribute data and value. This is guaranteed
219 /// to be in the local string pool instead of indirected.
220 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
221                                StringRef String) {
222   MCSymbol *Symb = DU->getStringPoolEntry(String);
223   DIEValue *Value;
224   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
225     Value = new (DIEValueAllocator) DIELabel(Symb);
226   else {
227     MCSymbol *StringPool = DU->getStringPoolSym();
228     Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
229   }
230   Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
231 }
232
233 /// addExpr - Add a Dwarf expression attribute data and value.
234 ///
235 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
236   DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
237   Die->addValue((dwarf::Attribute)0, Form, Value);
238 }
239
240 /// addLabel - Add a Dwarf label attribute data and value.
241 ///
242 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
243                          const MCSymbol *Label) {
244   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
245   Die->addValue(Attribute, Form, Value);
246 }
247
248 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
249                          const MCSymbol *Label) {
250   addLabel(Die, (dwarf::Attribute)0, Form, Label);
251 }
252
253 /// addSectionLabel - Add a Dwarf section label attribute data and value.
254 ///
255 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
256                                 const MCSymbol *Label) {
257   if (DD->getDwarfVersion() >= 4)
258     addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
259   else
260     addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
261 }
262
263 /// addSectionOffset - Add an offset into a section attribute data and value.
264 ///
265 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
266                                  uint64_t Integer) {
267   if (DD->getDwarfVersion() >= 4)
268     addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
269   else
270     addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
271 }
272
273 /// addLabelAddress - Add a dwarf label attribute data and value using
274 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
275 ///
276 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
277                                        MCSymbol *Label) {
278   if (Label)
279     DD->addArangeLabel(SymbolCU(this, Label));
280
281   if (!DD->useSplitDwarf()) {
282     if (Label != NULL) {
283       DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
284       Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
285     } else {
286       DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
287       Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
288     }
289   } else {
290     unsigned idx = DU->getAddrPoolIndex(Label);
291     DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
292     Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
293   }
294 }
295
296 /// addOpAddress - Add a dwarf op address data and value using the
297 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
298 ///
299 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
300   if (!DD->useSplitDwarf()) {
301     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
302     addLabel(Die, dwarf::DW_FORM_udata, Sym);
303   } else {
304     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
305     addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
306   }
307 }
308
309 /// addSectionDelta - Add a section label delta attribute data and value.
310 ///
311 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
312                                 const MCSymbol *Hi, const MCSymbol *Lo) {
313   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
314   if (DD->getDwarfVersion() >= 4)
315     Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
316   else
317     Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
318 }
319
320 /// addDIEEntry - Add a DIE attribute data and value.
321 ///
322 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
323   addDIEEntry(Die, Attribute, createDIEEntry(Entry));
324 }
325
326 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
327   Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
328                 new (DIEValueAllocator) DIETypeSignature(Type));
329 }
330
331 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
332                             DIEEntry *Entry) {
333   const DIE *DieCU = Die->getUnitOrNull();
334   const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
335   if (!DieCU)
336     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
337     DieCU = getUnitDie();
338   if (!EntryCU)
339     EntryCU = getUnitDie();
340   Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
341                                             : dwarf::DW_FORM_ref_addr,
342                 Entry);
343 }
344
345 /// Create a DIE with the given Tag, add the DIE to its parent, and
346 /// call insertDIE if MD is not null.
347 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
348   DIE *Die = new DIE(Tag);
349   Parent.addChild(Die);
350   if (N)
351     insertDIE(N, Die);
352   return Die;
353 }
354
355 /// addBlock - Add block data.
356 ///
357 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
358                          DIEBlock *Block) {
359   Block->ComputeSize(Asm);
360   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
361   Die->addValue(Attribute, Block->BestForm(), Block);
362 }
363
364 /// addSourceLine - Add location information to specified debug information
365 /// entry.
366 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
367   // Verify variable.
368   if (!V.isVariable())
369     return;
370
371   unsigned Line = V.getLineNumber();
372   if (Line == 0)
373     return;
374   unsigned FileID =
375       DD->getOrCreateSourceID(V.getContext().getFilename(),
376                               V.getContext().getDirectory(), getUniqueID());
377   assert(FileID && "Invalid file id");
378   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
379   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
380 }
381
382 /// addSourceLine - Add location information to specified debug information
383 /// entry.
384 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
385   // Verify global variable.
386   if (!G.isGlobalVariable())
387     return;
388
389   unsigned Line = G.getLineNumber();
390   if (Line == 0)
391     return;
392   unsigned FileID =
393       DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
394   assert(FileID && "Invalid file id");
395   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
396   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
397 }
398
399 /// addSourceLine - Add location information to specified debug information
400 /// entry.
401 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
402   // Verify subprogram.
403   if (!SP.isSubprogram())
404     return;
405
406   // If the line number is 0, don't add it.
407   unsigned Line = SP.getLineNumber();
408   if (Line == 0)
409     return;
410
411   unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
412                                             getUniqueID());
413   assert(FileID && "Invalid file id");
414   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
415   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
416 }
417
418 /// addSourceLine - Add location information to specified debug information
419 /// entry.
420 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
421   // Verify type.
422   if (!Ty.isType())
423     return;
424
425   unsigned Line = Ty.getLineNumber();
426   if (Line == 0)
427     return;
428   unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
429                                             getUniqueID());
430   assert(FileID && "Invalid file id");
431   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
432   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
433 }
434
435 /// addSourceLine - Add location information to specified debug information
436 /// entry.
437 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
438   // Verify type.
439   if (!Ty.isObjCProperty())
440     return;
441
442   unsigned Line = Ty.getLineNumber();
443   if (Line == 0)
444     return;
445   DIFile File = Ty.getFile();
446   unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
447                                             File.getDirectory(), getUniqueID());
448   assert(FileID && "Invalid file id");
449   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
450   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
451 }
452
453 /// addSourceLine - Add location information to specified debug information
454 /// entry.
455 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
456   // Verify namespace.
457   if (!NS.Verify())
458     return;
459
460   unsigned Line = NS.getLineNumber();
461   if (Line == 0)
462     return;
463   StringRef FN = NS.getFilename();
464
465   unsigned FileID =
466       DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
467   assert(FileID && "Invalid file id");
468   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
469   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
470 }
471
472 /// addVariableAddress - Add DW_AT_location attribute for a
473 /// DbgVariable based on provided MachineLocation.
474 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
475                                    MachineLocation Location) {
476   if (DV.variableHasComplexAddress())
477     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
478   else if (DV.isBlockByrefVariable())
479     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
480   else
481     addAddress(Die, dwarf::DW_AT_location, Location,
482                DV.getVariable().isIndirect());
483 }
484
485 /// addRegisterOp - Add register operand.
486 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
487   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
488   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
489   if (DWReg < 32)
490     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
491   else {
492     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
493     addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
494   }
495 }
496
497 /// addRegisterOffset - Add register offset.
498 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
499                                   int64_t Offset) {
500   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
501   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
502   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
503   if (Reg == TRI->getFrameRegister(*Asm->MF))
504     // If variable offset is based in frame register then use fbreg.
505     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
506   else if (DWReg < 32)
507     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
508   else {
509     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
510     addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
511   }
512   addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
513 }
514
515 /// addAddress - Add an address attribute to a die based on the location
516 /// provided.
517 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
518                            const MachineLocation &Location, bool Indirect) {
519   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
520
521   if (Location.isReg() && !Indirect)
522     addRegisterOp(Block, Location.getReg());
523   else {
524     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
525     if (Indirect && !Location.isReg()) {
526       addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
527     }
528   }
529
530   // Now attach the location information to the DIE.
531   addBlock(Die, Attribute, Block);
532 }
533
534 /// addComplexAddress - Start with the address based on the location provided,
535 /// and generate the DWARF information necessary to find the actual variable
536 /// given the extra address information encoded in the DbgVariable, starting
537 /// from the starting location.  Add the DWARF information to the die.
538 ///
539 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
540                                   dwarf::Attribute Attribute,
541                                   const MachineLocation &Location) {
542   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
543   unsigned N = DV.getNumAddrElements();
544   unsigned i = 0;
545   if (Location.isReg()) {
546     if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
547       // If first address element is OpPlus then emit
548       // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
549       addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
550       i = 2;
551     } else
552       addRegisterOp(Block, Location.getReg());
553   } else
554     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
555
556   for (; i < N; ++i) {
557     uint64_t Element = DV.getAddrElement(i);
558     if (Element == DIBuilder::OpPlus) {
559       addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
560       addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
561     } else if (Element == DIBuilder::OpDeref) {
562       if (!Location.isReg())
563         addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
564     } else
565       llvm_unreachable("unknown DIBuilder Opcode");
566   }
567
568   // Now attach the location information to the DIE.
569   addBlock(Die, Attribute, Block);
570 }
571
572 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
573    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
574    gives the variable VarName either the struct, or a pointer to the struct, as
575    its type.  This is necessary for various behind-the-scenes things the
576    compiler needs to do with by-reference variables in Blocks.
577
578    However, as far as the original *programmer* is concerned, the variable
579    should still have type 'SomeType', as originally declared.
580
581    The function getBlockByrefType dives into the __Block_byref_x_VarName
582    struct to find the original type of the variable, which is then assigned to
583    the variable's Debug Information Entry as its real type.  So far, so good.
584    However now the debugger will expect the variable VarName to have the type
585    SomeType.  So we need the location attribute for the variable to be an
586    expression that explains to the debugger how to navigate through the
587    pointers and struct to find the actual variable of type SomeType.
588
589    The following function does just that.  We start by getting
590    the "normal" location for the variable. This will be the location
591    of either the struct __Block_byref_x_VarName or the pointer to the
592    struct __Block_byref_x_VarName.
593
594    The struct will look something like:
595
596    struct __Block_byref_x_VarName {
597      ... <various fields>
598      struct __Block_byref_x_VarName *forwarding;
599      ... <various other fields>
600      SomeType VarName;
601      ... <maybe more fields>
602    };
603
604    If we are given the struct directly (as our starting point) we
605    need to tell the debugger to:
606
607    1).  Add the offset of the forwarding field.
608
609    2).  Follow that pointer to get the real __Block_byref_x_VarName
610    struct to use (the real one may have been copied onto the heap).
611
612    3).  Add the offset for the field VarName, to find the actual variable.
613
614    If we started with a pointer to the struct, then we need to
615    dereference that pointer first, before the other steps.
616    Translating this into DWARF ops, we will need to append the following
617    to the current location description for the variable:
618
619    DW_OP_deref                    -- optional, if we start with a pointer
620    DW_OP_plus_uconst <forward_fld_offset>
621    DW_OP_deref
622    DW_OP_plus_uconst <varName_fld_offset>
623
624    That is what this function does.  */
625
626 /// addBlockByrefAddress - Start with the address based on the location
627 /// provided, and generate the DWARF information necessary to find the
628 /// actual Block variable (navigating the Block struct) based on the
629 /// starting location.  Add the DWARF information to the die.  For
630 /// more information, read large comment just above here.
631 ///
632 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
633                                      dwarf::Attribute Attribute,
634                                      const MachineLocation &Location) {
635   DIType Ty = DV.getType();
636   DIType TmpTy = Ty;
637   uint16_t Tag = Ty.getTag();
638   bool isPointer = false;
639
640   StringRef varName = DV.getName();
641
642   if (Tag == dwarf::DW_TAG_pointer_type) {
643     DIDerivedType DTy(Ty);
644     TmpTy = resolve(DTy.getTypeDerivedFrom());
645     isPointer = true;
646   }
647
648   DICompositeType blockStruct(TmpTy);
649
650   // Find the __forwarding field and the variable field in the __Block_byref
651   // struct.
652   DIArray Fields = blockStruct.getTypeArray();
653   DIDerivedType varField;
654   DIDerivedType forwardingField;
655
656   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
657     DIDerivedType DT(Fields.getElement(i));
658     StringRef fieldName = DT.getName();
659     if (fieldName == "__forwarding")
660       forwardingField = DT;
661     else if (fieldName == varName)
662       varField = DT;
663   }
664
665   // Get the offsets for the forwarding field and the variable field.
666   unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
667   unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
668
669   // Decode the original location, and use that as the start of the byref
670   // variable's location.
671   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
672
673   if (Location.isReg())
674     addRegisterOp(Block, Location.getReg());
675   else
676     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
677
678   // If we started with a pointer to the __Block_byref... struct, then
679   // the first thing we need to do is dereference the pointer (DW_OP_deref).
680   if (isPointer)
681     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
682
683   // Next add the offset for the '__forwarding' field:
684   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
685   // adding the offset if it's 0.
686   if (forwardingFieldOffset > 0) {
687     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
688     addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
689   }
690
691   // Now dereference the __forwarding field to get to the real __Block_byref
692   // struct:  DW_OP_deref.
693   addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
694
695   // Now that we've got the real __Block_byref... struct, add the offset
696   // for the variable's field to get to the location of the actual variable:
697   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
698   if (varFieldOffset > 0) {
699     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
700     addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
701   }
702
703   // Now attach the location information to the DIE.
704   addBlock(Die, Attribute, Block);
705 }
706
707 /// isTypeSigned - Return true if the type is signed.
708 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
709   if (Ty.isDerivedType())
710     return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
711                         SizeInBits);
712   if (Ty.isBasicType())
713     if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
714         DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
715       *SizeInBits = Ty.getSizeInBits();
716       return true;
717     }
718   return false;
719 }
720
721 /// Return true if type encoding is unsigned.
722 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
723   DIDerivedType DTy(Ty);
724   if (DTy.isDerivedType())
725     return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
726
727   DIBasicType BTy(Ty);
728   if (BTy.isBasicType()) {
729     unsigned Encoding = BTy.getEncoding();
730     if (Encoding == dwarf::DW_ATE_unsigned ||
731         Encoding == dwarf::DW_ATE_unsigned_char ||
732         Encoding == dwarf::DW_ATE_boolean)
733       return true;
734   }
735   return false;
736 }
737
738 /// If this type is derived from a base type then return base type size.
739 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
740   unsigned Tag = Ty.getTag();
741
742   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
743       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
744       Tag != dwarf::DW_TAG_restrict_type)
745     return Ty.getSizeInBits();
746
747   DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
748
749   // If this type is not derived from any type then take conservative approach.
750   if (!BaseType.isValid())
751     return Ty.getSizeInBits();
752
753   // If this is a derived type, go ahead and get the base type, unless it's a
754   // reference then it's just the size of the field. Pointer types have no need
755   // of this since they're a different type of qualification on the type.
756   if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
757       BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
758     return Ty.getSizeInBits();
759
760   if (BaseType.isDerivedType())
761     return getBaseTypeSize(DD, DIDerivedType(BaseType));
762
763   return BaseType.getSizeInBits();
764 }
765
766 /// addConstantValue - Add constant value entry in variable DIE.
767 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
768                                  DIType Ty) {
769   // FIXME: This is a bit conservative/simple - it emits negative values at
770   // their maximum bit width which is a bit unfortunate (& doesn't prefer
771   // udata/sdata over dataN as suggested by the DWARF spec)
772   assert(MO.isImm() && "Invalid machine operand!");
773   int SizeInBits = -1;
774   bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
775   dwarf::Form Form;
776
777   // If we're a signed constant definitely use sdata.
778   if (SignedConstant) {
779     addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
780     return;
781   }
782
783   // Else use data for now unless it's larger than we can deal with.
784   switch (SizeInBits) {
785   case 8:
786     Form = dwarf::DW_FORM_data1;
787     break;
788   case 16:
789     Form = dwarf::DW_FORM_data2;
790     break;
791   case 32:
792     Form = dwarf::DW_FORM_data4;
793     break;
794   case 64:
795     Form = dwarf::DW_FORM_data8;
796     break;
797   default:
798     Form = dwarf::DW_FORM_udata;
799     addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
800     return;
801   }
802   addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
803 }
804
805 /// addConstantFPValue - Add constant value entry in variable DIE.
806 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
807   assert(MO.isFPImm() && "Invalid machine operand!");
808   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
809   APFloat FPImm = MO.getFPImm()->getValueAPF();
810
811   // Get the raw data form of the floating point.
812   const APInt FltVal = FPImm.bitcastToAPInt();
813   const char *FltPtr = (const char *)FltVal.getRawData();
814
815   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
816   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
817   int Incr = (LittleEndian ? 1 : -1);
818   int Start = (LittleEndian ? 0 : NumBytes - 1);
819   int Stop = (LittleEndian ? NumBytes : -1);
820
821   // Output the constant to DWARF one byte at a time.
822   for (; Start != Stop; Start += Incr)
823     addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
824
825   addBlock(Die, dwarf::DW_AT_const_value, Block);
826 }
827
828 /// addConstantFPValue - Add constant value entry in variable DIE.
829 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
830   // Pass this down to addConstantValue as an unsigned bag of bits.
831   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
832 }
833
834 /// addConstantValue - Add constant value entry in variable DIE.
835 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
836                                  bool Unsigned) {
837   addConstantValue(Die, CI->getValue(), Unsigned);
838 }
839
840 // addConstantValue - Add constant value entry in variable DIE.
841 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
842   unsigned CIBitWidth = Val.getBitWidth();
843   if (CIBitWidth <= 64) {
844     // If we're a signed constant definitely use sdata.
845     if (!Unsigned) {
846       addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
847               Val.getSExtValue());
848       return;
849     }
850
851     // Else use data for now unless it's larger than we can deal with.
852     dwarf::Form Form;
853     switch (CIBitWidth) {
854     case 8:
855       Form = dwarf::DW_FORM_data1;
856       break;
857     case 16:
858       Form = dwarf::DW_FORM_data2;
859       break;
860     case 32:
861       Form = dwarf::DW_FORM_data4;
862       break;
863     case 64:
864       Form = dwarf::DW_FORM_data8;
865       break;
866     default:
867       addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
868               Val.getZExtValue());
869       return;
870     }
871     addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
872     return;
873   }
874
875   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
876
877   // Get the raw data form of the large APInt.
878   const uint64_t *Ptr64 = Val.getRawData();
879
880   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
881   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
882
883   // Output the constant to DWARF one byte at a time.
884   for (int i = 0; i < NumBytes; i++) {
885     uint8_t c;
886     if (LittleEndian)
887       c = Ptr64[i / 8] >> (8 * (i & 7));
888     else
889       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
890     addUInt(Block, dwarf::DW_FORM_data1, c);
891   }
892
893   addBlock(Die, dwarf::DW_AT_const_value, Block);
894 }
895
896 /// addTemplateParams - Add template parameters into buffer.
897 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
898   // Add template parameters.
899   for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
900     DIDescriptor Element = TParams.getElement(i);
901     if (Element.isTemplateTypeParameter())
902       constructTemplateTypeParameterDIE(Buffer,
903                                         DITemplateTypeParameter(Element));
904     else if (Element.isTemplateValueParameter())
905       constructTemplateValueParameterDIE(Buffer,
906                                          DITemplateValueParameter(Element));
907   }
908 }
909
910 /// getOrCreateContextDIE - Get context owner's DIE.
911 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
912   if (!Context || Context.isFile())
913     return getUnitDie();
914   if (Context.isType())
915     return getOrCreateTypeDIE(DIType(Context));
916   if (Context.isNameSpace())
917     return getOrCreateNameSpace(DINameSpace(Context));
918   if (Context.isSubprogram())
919     return getOrCreateSubprogramDIE(DISubprogram(Context));
920   return getDIE(Context);
921 }
922
923 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
924   DIScope Context = resolve(Ty.getContext());
925   DIE *ContextDIE = getOrCreateContextDIE(Context);
926
927   DIE *TyDIE = getDIE(Ty);
928   if (TyDIE)
929     return TyDIE;
930
931   // Create new type.
932   TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
933
934   constructTypeDIE(*TyDIE, Ty);
935
936   updateAcceleratorTables(Context, Ty, TyDIE);
937   return TyDIE;
938 }
939
940 /// Return true if the type is appropriately scoped to be contained inside
941 /// its own type unit.
942 static bool isDwarfTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
943   DIScope Parent = DD->resolve(Ty.getContext());
944   while (Parent) {
945     // Don't generate a hash for anything scoped inside a function.
946     if (Parent.isSubprogram())
947       return false;
948     Parent = DD->resolve(Parent.getContext());
949   }
950   return true;
951 }
952
953 /// Return true if the type should be split out into a type unit.
954 static bool shouldCreateDwarfTypeUnit(DICompositeType CTy,
955                                       const DwarfDebug *DD) {
956   if (!GenerateDwarfTypeUnits)
957     return false;
958
959   uint16_t Tag = CTy.getTag();
960
961   switch (Tag) {
962   case dwarf::DW_TAG_structure_type:
963   case dwarf::DW_TAG_union_type:
964   case dwarf::DW_TAG_enumeration_type:
965   case dwarf::DW_TAG_class_type:
966     // If this is a class, structure, union, or enumeration type
967     // that is a definition (not a declaration), and not scoped
968     // inside a function then separate this out as a type unit.
969     return !CTy.isForwardDecl() && isDwarfTypeUnitScoped(CTy, DD);
970   default:
971     return false;
972   }
973 }
974
975 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
976 /// given DIType.
977 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
978   if (!TyNode)
979     return NULL;
980
981   DIType Ty(TyNode);
982   assert(Ty.isType());
983
984   // Construct the context before querying for the existence of the DIE in case
985   // such construction creates the DIE.
986   DIScope Context = resolve(Ty.getContext());
987   DIE *ContextDIE = getOrCreateContextDIE(Context);
988   assert(ContextDIE);
989
990   DIE *TyDIE = getDIE(Ty);
991   if (TyDIE)
992     return TyDIE;
993
994   // Create new type.
995   TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
996
997   if (Ty.isBasicType())
998     constructTypeDIE(*TyDIE, DIBasicType(Ty));
999   else if (Ty.isCompositeType()) {
1000     DICompositeType CTy(Ty);
1001     if (shouldCreateDwarfTypeUnit(CTy, DD)) {
1002       DD->addDwarfTypeUnitType(getLanguage(), TyDIE, CTy);
1003       // Skip updating the accellerator tables since this is not the full type
1004       return TyDIE;
1005     }
1006     constructTypeDIE(*TyDIE, CTy);
1007   } else {
1008     assert(Ty.isDerivedType() && "Unknown kind of DIType");
1009     constructTypeDIE(*TyDIE, DIDerivedType(Ty));
1010   }
1011
1012   updateAcceleratorTables(Context, Ty, TyDIE);
1013
1014   return TyDIE;
1015 }
1016
1017 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1018                                         const DIE *TyDIE) {
1019   if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1020     bool IsImplementation = 0;
1021     if (Ty.isCompositeType()) {
1022       DICompositeType CT(Ty);
1023       // A runtime language of 0 actually means C/C++ and that any
1024       // non-negative value is some version of Objective-C/C++.
1025       IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1026     }
1027     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1028     addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1029
1030     if (!Context || Context.isCompileUnit() || Context.isFile() ||
1031         Context.isNameSpace())
1032       GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1033   }
1034 }
1035
1036 /// addType - Add a new type attribute to the specified entity.
1037 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1038   assert(Ty && "Trying to add a type that doesn't exist?");
1039
1040   // Check for pre-existence.
1041   DIEEntry *Entry = getDIEEntry(Ty);
1042   // If it exists then use the existing value.
1043   if (Entry) {
1044     addDIEEntry(Entity, Attribute, Entry);
1045     return;
1046   }
1047
1048   // Construct type.
1049   DIE *Buffer = getOrCreateTypeDIE(Ty);
1050
1051   // Set up proxy.
1052   Entry = createDIEEntry(Buffer);
1053   insertDIEEntry(Ty, Entry);
1054   addDIEEntry(Entity, Attribute, Entry);
1055 }
1056
1057 // Accelerator table mutators - add each name along with its companion
1058 // DIE to the proper table while ensuring that the name that we're going
1059 // to reference is in the string table. We do this since the names we
1060 // add may not only be identical to the names in the DIE.
1061 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1062   DU->getStringPoolEntry(Name);
1063   std::vector<const DIE *> &DIEs = AccelNames[Name];
1064   DIEs.push_back(Die);
1065 }
1066
1067 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1068   DU->getStringPoolEntry(Name);
1069   std::vector<const DIE *> &DIEs = AccelObjC[Name];
1070   DIEs.push_back(Die);
1071 }
1072
1073 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1074   DU->getStringPoolEntry(Name);
1075   std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1076   DIEs.push_back(Die);
1077 }
1078
1079 void DwarfUnit::addAccelType(StringRef Name,
1080                              std::pair<const DIE *, unsigned> Die) {
1081   DU->getStringPoolEntry(Name);
1082   std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1083   DIEs.push_back(Die);
1084 }
1085
1086 /// addGlobalName - Add a new global name to the compile unit.
1087 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1088   std::string FullName = getParentContextString(Context) + Name.str();
1089   GlobalNames[FullName] = Die;
1090 }
1091
1092 /// getParentContextString - Walks the metadata parent chain in a language
1093 /// specific manner (using the compile unit language) and returns
1094 /// it as a string. This is done at the metadata level because DIEs may
1095 /// not currently have been added to the parent context and walking the
1096 /// DIEs looking for names is more expensive than walking the metadata.
1097 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1098   if (!Context)
1099     return "";
1100
1101   // FIXME: Decide whether to implement this for non-C++ languages.
1102   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1103     return "";
1104
1105   std::string CS;
1106   SmallVector<DIScope, 1> Parents;
1107   while (!Context.isCompileUnit()) {
1108     Parents.push_back(Context);
1109     if (Context.getContext())
1110       Context = resolve(Context.getContext());
1111     else
1112       // Structure, etc types will have a NULL context if they're at the top
1113       // level.
1114       break;
1115   }
1116
1117   // Reverse iterate over our list to go from the outermost construct to the
1118   // innermost.
1119   for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1120                                                   E = Parents.rend();
1121        I != E; ++I) {
1122     DIScope Ctx = *I;
1123     StringRef Name = Ctx.getName();
1124     if (!Name.empty()) {
1125       CS += Name;
1126       CS += "::";
1127     }
1128   }
1129   return CS;
1130 }
1131
1132 /// constructTypeDIE - Construct basic type die from DIBasicType.
1133 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1134   // Get core information.
1135   StringRef Name = BTy.getName();
1136   // Add name if not anonymous or intermediate type.
1137   if (!Name.empty())
1138     addString(&Buffer, dwarf::DW_AT_name, Name);
1139
1140   // An unspecified type only has a name attribute.
1141   if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1142     return;
1143
1144   addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1145           BTy.getEncoding());
1146
1147   uint64_t Size = BTy.getSizeInBits() >> 3;
1148   addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1149 }
1150
1151 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1152 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1153   // Get core information.
1154   StringRef Name = DTy.getName();
1155   uint64_t Size = DTy.getSizeInBits() >> 3;
1156   uint16_t Tag = Buffer.getTag();
1157
1158   // Map to main type, void will not have a type.
1159   DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1160   if (FromTy)
1161     addType(&Buffer, FromTy);
1162
1163   // Add name if not anonymous or intermediate type.
1164   if (!Name.empty())
1165     addString(&Buffer, dwarf::DW_AT_name, Name);
1166
1167   // Add size if non-zero (derived types might be zero-sized.)
1168   if (Size && Tag != dwarf::DW_TAG_pointer_type)
1169     addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1170
1171   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1172     addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1173                 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1174   // Add source line info if available and TyDesc is not a forward declaration.
1175   if (!DTy.isForwardDecl())
1176     addSourceLine(&Buffer, DTy);
1177 }
1178
1179 /// constructTypeDIE - Construct type DIE from DICompositeType.
1180 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1181   // Add name if not anonymous or intermediate type.
1182   StringRef Name = CTy.getName();
1183
1184   uint64_t Size = CTy.getSizeInBits() >> 3;
1185   uint16_t Tag = Buffer.getTag();
1186
1187   switch (Tag) {
1188   case dwarf::DW_TAG_array_type:
1189     constructArrayTypeDIE(Buffer, CTy);
1190     break;
1191   case dwarf::DW_TAG_enumeration_type:
1192     constructEnumTypeDIE(Buffer, CTy);
1193     break;
1194   case dwarf::DW_TAG_subroutine_type: {
1195     // Add return type. A void return won't have a type.
1196     DIArray Elements = CTy.getTypeArray();
1197     DIType RTy(Elements.getElement(0));
1198     if (RTy)
1199       addType(&Buffer, RTy);
1200
1201     bool isPrototyped = true;
1202     // Add arguments.
1203     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1204       DIDescriptor Ty = Elements.getElement(i);
1205       if (Ty.isUnspecifiedParameter()) {
1206         createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1207         isPrototyped = false;
1208       } else {
1209         DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1210         addType(Arg, DIType(Ty));
1211         if (DIType(Ty).isArtificial())
1212           addFlag(Arg, dwarf::DW_AT_artificial);
1213       }
1214     }
1215     // Add prototype flag if we're dealing with a C language and the
1216     // function has been prototyped.
1217     uint16_t Language = getLanguage();
1218     if (isPrototyped &&
1219         (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1220          Language == dwarf::DW_LANG_ObjC))
1221       addFlag(&Buffer, dwarf::DW_AT_prototyped);
1222
1223     if (CTy.isLValueReference())
1224       addFlag(&Buffer, dwarf::DW_AT_reference);
1225
1226     if (CTy.isRValueReference())
1227       addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1228   } break;
1229   case dwarf::DW_TAG_structure_type:
1230   case dwarf::DW_TAG_union_type:
1231   case dwarf::DW_TAG_class_type: {
1232     // Add elements to structure type.
1233     DIArray Elements = CTy.getTypeArray();
1234     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1235       DIDescriptor Element = Elements.getElement(i);
1236       DIE *ElemDie = NULL;
1237       if (Element.isSubprogram()) {
1238         DISubprogram SP(Element);
1239         ElemDie = getOrCreateSubprogramDIE(SP);
1240         if (SP.isProtected())
1241           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1242                   dwarf::DW_ACCESS_protected);
1243         else if (SP.isPrivate())
1244           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1245                   dwarf::DW_ACCESS_private);
1246         else
1247           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1248                   dwarf::DW_ACCESS_public);
1249         if (SP.isExplicit())
1250           addFlag(ElemDie, dwarf::DW_AT_explicit);
1251       } else if (Element.isDerivedType()) {
1252         DIDerivedType DDTy(Element);
1253         if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1254           ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1255           addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1256                   dwarf::DW_AT_friend);
1257         } else if (DDTy.isStaticMember()) {
1258           getOrCreateStaticMemberDIE(DDTy);
1259         } else {
1260           constructMemberDIE(Buffer, DDTy);
1261         }
1262       } else if (Element.isObjCProperty()) {
1263         DIObjCProperty Property(Element);
1264         ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1265         StringRef PropertyName = Property.getObjCPropertyName();
1266         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1267         addType(ElemDie, Property.getType());
1268         addSourceLine(ElemDie, Property);
1269         StringRef GetterName = Property.getObjCPropertyGetterName();
1270         if (!GetterName.empty())
1271           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1272         StringRef SetterName = Property.getObjCPropertySetterName();
1273         if (!SetterName.empty())
1274           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1275         unsigned PropertyAttributes = 0;
1276         if (Property.isReadOnlyObjCProperty())
1277           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1278         if (Property.isReadWriteObjCProperty())
1279           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1280         if (Property.isAssignObjCProperty())
1281           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1282         if (Property.isRetainObjCProperty())
1283           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1284         if (Property.isCopyObjCProperty())
1285           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1286         if (Property.isNonAtomicObjCProperty())
1287           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1288         if (PropertyAttributes)
1289           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1290                   PropertyAttributes);
1291
1292         DIEEntry *Entry = getDIEEntry(Element);
1293         if (!Entry) {
1294           Entry = createDIEEntry(ElemDie);
1295           insertDIEEntry(Element, Entry);
1296         }
1297       } else
1298         continue;
1299     }
1300
1301     if (CTy.isAppleBlockExtension())
1302       addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1303
1304     DICompositeType ContainingType(resolve(CTy.getContainingType()));
1305     if (ContainingType)
1306       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1307                   getOrCreateTypeDIE(ContainingType));
1308
1309     if (CTy.isObjcClassComplete())
1310       addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1311
1312     // Add template parameters to a class, structure or union types.
1313     // FIXME: The support isn't in the metadata for this yet.
1314     if (Tag == dwarf::DW_TAG_class_type ||
1315         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1316       addTemplateParams(Buffer, CTy.getTemplateParams());
1317
1318     break;
1319   }
1320   default:
1321     break;
1322   }
1323
1324   // Add name if not anonymous or intermediate type.
1325   if (!Name.empty())
1326     addString(&Buffer, dwarf::DW_AT_name, Name);
1327
1328   if (Tag == dwarf::DW_TAG_enumeration_type ||
1329       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1330       Tag == dwarf::DW_TAG_union_type) {
1331     // Add size if non-zero (derived types might be zero-sized.)
1332     // TODO: Do we care about size for enum forward declarations?
1333     if (Size)
1334       addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1335     else if (!CTy.isForwardDecl())
1336       // Add zero size if it is not a forward declaration.
1337       addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1338
1339     // If we're a forward decl, say so.
1340     if (CTy.isForwardDecl())
1341       addFlag(&Buffer, dwarf::DW_AT_declaration);
1342
1343     // Add source line info if available.
1344     if (!CTy.isForwardDecl())
1345       addSourceLine(&Buffer, CTy);
1346
1347     // No harm in adding the runtime language to the declaration.
1348     unsigned RLang = CTy.getRunTimeLang();
1349     if (RLang)
1350       addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1351               RLang);
1352   }
1353 }
1354
1355 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1356 /// DITemplateTypeParameter.
1357 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1358                                                   DITemplateTypeParameter TP) {
1359   DIE *ParamDIE =
1360       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1361   // Add the type if it exists, it could be void and therefore no type.
1362   if (TP.getType())
1363     addType(ParamDIE, resolve(TP.getType()));
1364   if (!TP.getName().empty())
1365     addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1366 }
1367
1368 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1369 /// DITemplateValueParameter.
1370 void
1371 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1372                                               DITemplateValueParameter VP) {
1373   DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1374
1375   // Add the type if there is one, template template and template parameter
1376   // packs will not have a type.
1377   if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1378     addType(ParamDIE, resolve(VP.getType()));
1379   if (!VP.getName().empty())
1380     addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1381   if (Value *Val = VP.getValue()) {
1382     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1383       addConstantValue(ParamDIE, CI,
1384                        isUnsignedDIType(DD, resolve(VP.getType())));
1385     else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1386       // For declaration non-type template parameters (such as global values and
1387       // functions)
1388       DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1389       addOpAddress(Block, Asm->getSymbol(GV));
1390       // Emit DW_OP_stack_value to use the address as the immediate value of the
1391       // parameter, rather than a pointer to it.
1392       addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1393       addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1394     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1395       assert(isa<MDString>(Val));
1396       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1397                 cast<MDString>(Val)->getString());
1398     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1399       assert(isa<MDNode>(Val));
1400       DIArray A(cast<MDNode>(Val));
1401       addTemplateParams(*ParamDIE, A);
1402     }
1403   }
1404 }
1405
1406 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1407 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1408   // Construct the context before querying for the existence of the DIE in case
1409   // such construction creates the DIE.
1410   DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1411
1412   DIE *NDie = getDIE(NS);
1413   if (NDie)
1414     return NDie;
1415   NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1416
1417   if (!NS.getName().empty()) {
1418     addString(NDie, dwarf::DW_AT_name, NS.getName());
1419     addAccelNamespace(NS.getName(), NDie);
1420     addGlobalName(NS.getName(), NDie, NS.getContext());
1421   } else
1422     addAccelNamespace("(anonymous namespace)", NDie);
1423   addSourceLine(NDie, NS);
1424   return NDie;
1425 }
1426
1427 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1428 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1429   // Construct the context before querying for the existence of the DIE in case
1430   // such construction creates the DIE (as is the case for member function
1431   // declarations).
1432   DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1433
1434   DIE *SPDie = getDIE(SP);
1435   if (SPDie)
1436     return SPDie;
1437
1438   DISubprogram SPDecl = SP.getFunctionDeclaration();
1439   if (SPDecl.isSubprogram())
1440     // Add subprogram definitions to the CU die directly.
1441     ContextDIE = UnitDie.get();
1442
1443   // DW_TAG_inlined_subroutine may refer to this DIE.
1444   SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1445
1446   DIE *DeclDie = NULL;
1447   if (SPDecl.isSubprogram())
1448     DeclDie = getOrCreateSubprogramDIE(SPDecl);
1449
1450   // Add function template parameters.
1451   addTemplateParams(*SPDie, SP.getTemplateParams());
1452
1453   // If this DIE is going to refer declaration info using AT_specification
1454   // then there is no need to add other attributes.
1455   if (DeclDie) {
1456     // Refer function declaration directly.
1457     addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1458
1459     return SPDie;
1460   }
1461
1462   // Add the linkage name if we have one.
1463   StringRef LinkageName = SP.getLinkageName();
1464   if (!LinkageName.empty())
1465     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1466               GlobalValue::getRealLinkageName(LinkageName));
1467
1468   // Constructors and operators for anonymous aggregates do not have names.
1469   if (!SP.getName().empty())
1470     addString(SPDie, dwarf::DW_AT_name, SP.getName());
1471
1472   addSourceLine(SPDie, SP);
1473
1474   // Add the prototype if we have a prototype and we have a C like
1475   // language.
1476   uint16_t Language = getLanguage();
1477   if (SP.isPrototyped() &&
1478       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1479        Language == dwarf::DW_LANG_ObjC))
1480     addFlag(SPDie, dwarf::DW_AT_prototyped);
1481
1482   DICompositeType SPTy = SP.getType();
1483   assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1484          "the type of a subprogram should be a subroutine");
1485
1486   DIArray Args = SPTy.getTypeArray();
1487   // Add a return type. If this is a type like a C/C++ void type we don't add a
1488   // return type.
1489   if (Args.getElement(0))
1490     addType(SPDie, DIType(Args.getElement(0)));
1491
1492   unsigned VK = SP.getVirtuality();
1493   if (VK) {
1494     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1495     DIEBlock *Block = getDIEBlock();
1496     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1497     addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1498     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1499     ContainingTypeMap.insert(
1500         std::make_pair(SPDie, resolve(SP.getContainingType())));
1501   }
1502
1503   if (!SP.isDefinition()) {
1504     addFlag(SPDie, dwarf::DW_AT_declaration);
1505
1506     // Add arguments. Do not add arguments for subprogram definition. They will
1507     // be handled while processing variables.
1508     for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1509       DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1510       DIType ATy(Args.getElement(i));
1511       addType(Arg, ATy);
1512       if (ATy.isArtificial())
1513         addFlag(Arg, dwarf::DW_AT_artificial);
1514     }
1515   }
1516
1517   if (SP.isArtificial())
1518     addFlag(SPDie, dwarf::DW_AT_artificial);
1519
1520   if (!SP.isLocalToUnit())
1521     addFlag(SPDie, dwarf::DW_AT_external);
1522
1523   if (SP.isOptimized())
1524     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1525
1526   if (unsigned isa = Asm->getISAEncoding()) {
1527     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1528   }
1529
1530   if (SP.isLValueReference())
1531     addFlag(SPDie, dwarf::DW_AT_reference);
1532
1533   if (SP.isRValueReference())
1534     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1535
1536   return SPDie;
1537 }
1538
1539 // Return const expression if value is a GEP to access merged global
1540 // constant. e.g.
1541 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1542 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1543   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1544   if (!CE || CE->getNumOperands() != 3 ||
1545       CE->getOpcode() != Instruction::GetElementPtr)
1546     return NULL;
1547
1548   // First operand points to a global struct.
1549   Value *Ptr = CE->getOperand(0);
1550   if (!isa<GlobalValue>(Ptr) ||
1551       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1552     return NULL;
1553
1554   // Second operand is zero.
1555   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1556   if (!CI || !CI->isZero())
1557     return NULL;
1558
1559   // Third operand is offset.
1560   if (!isa<ConstantInt>(CE->getOperand(2)))
1561     return NULL;
1562
1563   return CE;
1564 }
1565
1566 /// createGlobalVariableDIE - create global variable DIE.
1567 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1568   // Check for pre-existence.
1569   if (getDIE(GV))
1570     return;
1571
1572   if (!GV.isGlobalVariable())
1573     return;
1574
1575   DIScope GVContext = GV.getContext();
1576   DIType GTy = GV.getType();
1577
1578   // If this is a static data member definition, some attributes belong
1579   // to the declaration DIE.
1580   DIE *VariableDIE = NULL;
1581   bool IsStaticMember = false;
1582   DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1583   if (SDMDecl.Verify()) {
1584     assert(SDMDecl.isStaticMember() && "Expected static member decl");
1585     // We need the declaration DIE that is in the static member's class.
1586     VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1587     IsStaticMember = true;
1588   }
1589
1590   // If this is not a static data member definition, create the variable
1591   // DIE and add the initial set of attributes to it.
1592   if (!VariableDIE) {
1593     // Construct the context before querying for the existence of the DIE in
1594     // case such construction creates the DIE.
1595     DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1596
1597     // Add to map.
1598     VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1599
1600     // Add name and type.
1601     addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1602     addType(VariableDIE, GTy);
1603
1604     // Add scoping info.
1605     if (!GV.isLocalToUnit())
1606       addFlag(VariableDIE, dwarf::DW_AT_external);
1607
1608     // Add line number info.
1609     addSourceLine(VariableDIE, GV);
1610   }
1611
1612   // Add location.
1613   bool addToAccelTable = false;
1614   DIE *VariableSpecDIE = NULL;
1615   bool isGlobalVariable = GV.getGlobal() != NULL;
1616   if (isGlobalVariable) {
1617     addToAccelTable = true;
1618     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1619     const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1620     if (GV.getGlobal()->isThreadLocal()) {
1621       // FIXME: Make this work with -gsplit-dwarf.
1622       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1623       assert((PointerSize == 4 || PointerSize == 8) &&
1624              "Add support for other sizes if necessary");
1625       const MCExpr *Expr =
1626           Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1627       // Based on GCC's support for TLS:
1628       if (!DD->useSplitDwarf()) {
1629         // 1) Start with a constNu of the appropriate pointer size
1630         addUInt(Block, dwarf::DW_FORM_data1,
1631                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1632         // 2) containing the (relocated) offset of the TLS variable
1633         //    within the module's TLS block.
1634         addExpr(Block, dwarf::DW_FORM_udata, Expr);
1635       } else {
1636         addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1637         addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1638       }
1639       // 3) followed by a custom OP to make the debugger do a TLS lookup.
1640       addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1641     } else {
1642       DD->addArangeLabel(SymbolCU(this, Sym));
1643       addOpAddress(Block, Sym);
1644     }
1645     // Do not create specification DIE if context is either compile unit
1646     // or a subprogram.
1647     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1648         !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1649       // Create specification DIE.
1650       VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1651       addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1652       addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1653       // A static member's declaration is already flagged as such.
1654       if (!SDMDecl.Verify())
1655         addFlag(VariableDIE, dwarf::DW_AT_declaration);
1656     } else {
1657       addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1658     }
1659     // Add the linkage name.
1660     StringRef LinkageName = GV.getLinkageName();
1661     if (!LinkageName.empty())
1662       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1663       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1664       // TAG_variable.
1665       addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1666                                                   : VariableDIE,
1667                 dwarf::DW_AT_MIPS_linkage_name,
1668                 GlobalValue::getRealLinkageName(LinkageName));
1669   } else if (const ConstantInt *CI =
1670                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1671     // AT_const_value was added when the static member was created. To avoid
1672     // emitting AT_const_value multiple times, we only add AT_const_value when
1673     // it is not a static member.
1674     if (!IsStaticMember)
1675       addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1676   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1677     addToAccelTable = true;
1678     // GV is a merged global.
1679     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1680     Value *Ptr = CE->getOperand(0);
1681     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1682     DD->addArangeLabel(SymbolCU(this, Sym));
1683     addOpAddress(Block, Sym);
1684     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1685     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1686     addUInt(Block, dwarf::DW_FORM_udata,
1687             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1688     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1689     addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1690   }
1691
1692   if (addToAccelTable) {
1693     DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1694     addAccelName(GV.getName(), AddrDIE);
1695
1696     // If the linkage name is different than the name, go ahead and output
1697     // that as well into the name table.
1698     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1699       addAccelName(GV.getLinkageName(), AddrDIE);
1700   }
1701
1702   if (!GV.isLocalToUnit())
1703     addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1704                   GV.getContext());
1705 }
1706
1707 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1708 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1709   DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1710   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1711
1712   // The LowerBound value defines the lower bounds which is typically zero for
1713   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1714   // Count == -1 then the array is unbounded and we do not emit
1715   // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1716   // Count == 0, then the array has zero elements in which case we do not emit
1717   // an upper bound.
1718   int64_t LowerBound = SR.getLo();
1719   int64_t DefaultLowerBound = getDefaultLowerBound();
1720   int64_t Count = SR.getCount();
1721
1722   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1723     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1724
1725   if (Count != -1 && Count != 0)
1726     // FIXME: An unbounded array should reference the expression that defines
1727     // the array.
1728     addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1729             LowerBound + Count - 1);
1730 }
1731
1732 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1733 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1734   if (CTy.isVector())
1735     addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1736
1737   // Emit the element type.
1738   addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1739
1740   // Get an anonymous type for index type.
1741   // FIXME: This type should be passed down from the front end
1742   // as different languages may have different sizes for indexes.
1743   DIE *IdxTy = getIndexTyDie();
1744   if (!IdxTy) {
1745     // Construct an anonymous type for index type.
1746     IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1747     addString(IdxTy, dwarf::DW_AT_name, "int");
1748     addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1749     addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1750             dwarf::DW_ATE_signed);
1751     setIndexTyDie(IdxTy);
1752   }
1753
1754   // Add subranges to array type.
1755   DIArray Elements = CTy.getTypeArray();
1756   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1757     DIDescriptor Element = Elements.getElement(i);
1758     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1759       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1760   }
1761 }
1762
1763 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1764 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1765   DIArray Elements = CTy.getTypeArray();
1766
1767   // Add enumerators to enumeration type.
1768   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1769     DIEnumerator Enum(Elements.getElement(i));
1770     if (Enum.isEnumerator()) {
1771       DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1772       StringRef Name = Enum.getName();
1773       addString(Enumerator, dwarf::DW_AT_name, Name);
1774       int64_t Value = Enum.getEnumValue();
1775       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1776               Value);
1777
1778       // Add the enumerator to the __apple_names accelerator table.
1779       addAccelName(Name, Enumerator);
1780     }
1781   }
1782   DIType DTy = resolve(CTy.getTypeDerivedFrom());
1783   if (DTy) {
1784     addType(&Buffer, DTy);
1785     addFlag(&Buffer, dwarf::DW_AT_enum_class);
1786   }
1787 }
1788
1789 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1790 /// vtables.
1791 void DwarfUnit::constructContainingTypeDIEs() {
1792   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1793                                                  CE = ContainingTypeMap.end();
1794        CI != CE; ++CI) {
1795     DIE *SPDie = CI->first;
1796     DIDescriptor D(CI->second);
1797     if (!D)
1798       continue;
1799     DIE *NDie = getDIE(D);
1800     if (!NDie)
1801       continue;
1802     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1803   }
1804 }
1805
1806 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1807 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1808   StringRef Name = DV.getName();
1809
1810   // Define variable debug information entry.
1811   DIE *VariableDie = new DIE(DV.getTag());
1812   DbgVariable *AbsVar = DV.getAbstractVariable();
1813   DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1814   if (AbsDIE)
1815     addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1816   else {
1817     if (!Name.empty())
1818       addString(VariableDie, dwarf::DW_AT_name, Name);
1819     addSourceLine(VariableDie, DV.getVariable());
1820     addType(VariableDie, DV.getType());
1821   }
1822
1823   if (DV.isArtificial())
1824     addFlag(VariableDie, dwarf::DW_AT_artificial);
1825
1826   if (isScopeAbstract) {
1827     DV.setDIE(VariableDie);
1828     return VariableDie;
1829   }
1830
1831   // Add variable address.
1832
1833   unsigned Offset = DV.getDotDebugLocOffset();
1834   if (Offset != ~0U) {
1835     addSectionLabel(VariableDie, dwarf::DW_AT_location,
1836                     Asm->GetTempSymbol("debug_loc", Offset));
1837     DV.setDIE(VariableDie);
1838     return VariableDie;
1839   }
1840
1841   // Check if variable is described by a DBG_VALUE instruction.
1842   if (const MachineInstr *DVInsn = DV.getMInsn()) {
1843     assert(DVInsn->getNumOperands() == 3);
1844     if (DVInsn->getOperand(0).isReg()) {
1845       const MachineOperand RegOp = DVInsn->getOperand(0);
1846       // If the second operand is an immediate, this is an indirect value.
1847       if (DVInsn->getOperand(1).isImm()) {
1848         MachineLocation Location(RegOp.getReg(),
1849                                  DVInsn->getOperand(1).getImm());
1850         addVariableAddress(DV, VariableDie, Location);
1851       } else if (RegOp.getReg())
1852         addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1853     } else if (DVInsn->getOperand(0).isImm())
1854       addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1855     else if (DVInsn->getOperand(0).isFPImm())
1856       addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1857     else if (DVInsn->getOperand(0).isCImm())
1858       addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1859                        isUnsignedDIType(DD, DV.getType()));
1860
1861     DV.setDIE(VariableDie);
1862     return VariableDie;
1863   } else {
1864     // .. else use frame index.
1865     int FI = DV.getFrameIndex();
1866     if (FI != ~0) {
1867       unsigned FrameReg = 0;
1868       const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1869       int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1870       MachineLocation Location(FrameReg, Offset);
1871       addVariableAddress(DV, VariableDie, Location);
1872     }
1873   }
1874
1875   DV.setDIE(VariableDie);
1876   return VariableDie;
1877 }
1878
1879 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1880 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1881   DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1882   StringRef Name = DT.getName();
1883   if (!Name.empty())
1884     addString(MemberDie, dwarf::DW_AT_name, Name);
1885
1886   addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1887
1888   addSourceLine(MemberDie, DT);
1889
1890   DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1891   addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1892
1893   if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1894
1895     // For C++, virtual base classes are not at fixed offset. Use following
1896     // expression to extract appropriate offset from vtable.
1897     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1898
1899     DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1900     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1901     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1902     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1903     addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1904     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1905     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1906     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1907
1908     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1909   } else {
1910     uint64_t Size = DT.getSizeInBits();
1911     uint64_t FieldSize = getBaseTypeSize(DD, DT);
1912     uint64_t OffsetInBytes;
1913
1914     if (Size != FieldSize) {
1915       // Handle bitfield.
1916       addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1917               getBaseTypeSize(DD, DT) >> 3);
1918       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1919
1920       uint64_t Offset = DT.getOffsetInBits();
1921       uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1922       uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1923       uint64_t FieldOffset = (HiMark - FieldSize);
1924       Offset -= FieldOffset;
1925
1926       // Maybe we need to work from the other end.
1927       if (Asm->getDataLayout().isLittleEndian())
1928         Offset = FieldSize - (Offset + Size);
1929       addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1930
1931       // Here WD_AT_data_member_location points to the anonymous
1932       // field that includes this bit field.
1933       OffsetInBytes = FieldOffset >> 3;
1934     } else
1935       // This is not a bitfield.
1936       OffsetInBytes = DT.getOffsetInBits() >> 3;
1937     addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes);
1938   }
1939
1940   if (DT.isProtected())
1941     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1942             dwarf::DW_ACCESS_protected);
1943   else if (DT.isPrivate())
1944     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1945             dwarf::DW_ACCESS_private);
1946   // Otherwise C++ member and base classes are considered public.
1947   else
1948     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1949             dwarf::DW_ACCESS_public);
1950   if (DT.isVirtual())
1951     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1952             dwarf::DW_VIRTUALITY_virtual);
1953
1954   // Objective-C properties.
1955   if (MDNode *PNode = DT.getObjCProperty())
1956     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1957       MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1958                           PropertyDie);
1959
1960   if (DT.isArtificial())
1961     addFlag(MemberDie, dwarf::DW_AT_artificial);
1962 }
1963
1964 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1965 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1966   if (!DT.Verify())
1967     return NULL;
1968
1969   // Construct the context before querying for the existence of the DIE in case
1970   // such construction creates the DIE.
1971   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1972   assert(dwarf::isType(ContextDIE->getTag()) &&
1973          "Static member should belong to a type.");
1974
1975   DIE *StaticMemberDIE = getDIE(DT);
1976   if (StaticMemberDIE)
1977     return StaticMemberDIE;
1978
1979   StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1980
1981   DIType Ty = resolve(DT.getTypeDerivedFrom());
1982
1983   addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1984   addType(StaticMemberDIE, Ty);
1985   addSourceLine(StaticMemberDIE, DT);
1986   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1987   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1988
1989   // FIXME: We could omit private if the parent is a class_type, and
1990   // public if the parent is something else.
1991   if (DT.isProtected())
1992     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1993             dwarf::DW_ACCESS_protected);
1994   else if (DT.isPrivate())
1995     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1996             dwarf::DW_ACCESS_private);
1997   else
1998     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1999             dwarf::DW_ACCESS_public);
2000
2001   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2002     addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
2003   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2004     addConstantFPValue(StaticMemberDIE, CFP);
2005
2006   return StaticMemberDIE;
2007 }
2008
2009 void DwarfUnit::emitHeader(const MCSection *ASection,
2010                            const MCSymbol *ASectionSym) const {
2011   Asm->OutStreamer.AddComment("DWARF version number");
2012   Asm->EmitInt16(DD->getDwarfVersion());
2013   Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2014   // We share one abbreviations table across all units so it's always at the
2015   // start of the section. Use a relocatable offset where needed to ensure
2016   // linking doesn't invalidate that offset.
2017   Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2018   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2019   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2020 }
2021
2022 DwarfCompileUnit::~DwarfCompileUnit() {}
2023 DwarfTypeUnit::~DwarfTypeUnit() {}
2024
2025 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2026                                const MCSymbol *ASectionSym) const {
2027   DwarfUnit::emitHeader(ASection, ASectionSym);
2028   Asm->OutStreamer.AddComment("Type Signature");
2029   Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2030   Asm->OutStreamer.AddComment("Type DIE Offset");
2031   Asm->OutStreamer.EmitIntValue(Ty->getOffset(), sizeof(Ty->getOffset()));
2032 }
2033
2034 void DwarfTypeUnit::initSection(const MCSection *Section) {
2035   assert(!this->Section);
2036   this->Section = Section;
2037   // Since each type unit is contained in its own COMDAT section, the begin
2038   // label and the section label are the same. Using the begin label emission in
2039   // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2040   // the only other alternative of lazily constructing start-of-section labels
2041   // and storing a mapping in DwarfDebug (or AsmPrinter).
2042   this->SectionSym = this->LabelBegin =
2043       Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2044   this->LabelEnd =
2045       Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2046   this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());
2047 }