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