]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/AsmPrinter/DwarfUnit.cpp
Implement DW_TAG_subrange_type with DW_AT_count rather than DW_AT_upper_bound
[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 #include "DwarfUnit.h"
15 #include "DwarfAccelTable.h"
16 #include "DwarfDebug.h"
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DIBuilder.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
35 using namespace llvm;
37 #define DEBUG_TYPE "dwarfdebug"
39 static cl::opt<bool>
40 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
41                        cl::desc("Generate DWARF4 type units."),
42                        cl::init(false));
44 /// Unit - Unit constructor.
45 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node,
46                      AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
47     : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
48       DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr),
49       Skeleton(nullptr) {
50   assert(UnitTag == dwarf::DW_TAG_compile_unit ||
51          UnitTag == dwarf::DW_TAG_type_unit);
52   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
53 }
55 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
56                                    AsmPrinter *A, DwarfDebug *DW,
57                                    DwarfFile *DWU)
58     : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU) {
59   insertDIE(Node, &getUnitDie());
60 }
62 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
63                              DwarfDebug *DW, DwarfFile *DWU,
64                              MCDwarfDwoLineTable *SplitLineTable)
65     : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
66       CU(CU), SplitLineTable(SplitLineTable) {
67   if (SplitLineTable)
68     addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
69 }
71 /// ~Unit - Destructor for compile unit.
72 DwarfUnit::~DwarfUnit() {
73   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
74     DIEBlocks[j]->~DIEBlock();
75   for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
76     DIELocs[j]->~DIELoc();
77 }
79 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
80 /// information entry.
81 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
82   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
83   return Value;
84 }
86 /// getDefaultLowerBound - Return the default lower bound for an array. If the
87 /// DWARF version doesn't handle the language, return -1.
88 int64_t DwarfUnit::getDefaultLowerBound() const {
89   switch (getLanguage()) {
90   default:
91     break;
93   case dwarf::DW_LANG_C89:
94   case dwarf::DW_LANG_C99:
95   case dwarf::DW_LANG_C:
96   case dwarf::DW_LANG_C_plus_plus:
97   case dwarf::DW_LANG_ObjC:
98   case dwarf::DW_LANG_ObjC_plus_plus:
99     return 0;
101   case dwarf::DW_LANG_Fortran77:
102   case dwarf::DW_LANG_Fortran90:
103   case dwarf::DW_LANG_Fortran95:
104     return 1;
106   // The languages below have valid values only if the DWARF version >= 4.
107   case dwarf::DW_LANG_Java:
108   case dwarf::DW_LANG_Python:
109   case dwarf::DW_LANG_UPC:
110   case dwarf::DW_LANG_D:
111     if (dwarf::DWARF_VERSION >= 4)
112       return 0;
113     break;
115   case dwarf::DW_LANG_Ada83:
116   case dwarf::DW_LANG_Ada95:
117   case dwarf::DW_LANG_Cobol74:
118   case dwarf::DW_LANG_Cobol85:
119   case dwarf::DW_LANG_Modula2:
120   case dwarf::DW_LANG_Pascal83:
121   case dwarf::DW_LANG_PLI:
122     if (dwarf::DWARF_VERSION >= 4)
123       return 1;
124     break;
125   }
127   return -1;
130 /// Check whether the DIE for this MDNode can be shared across CUs.
131 static bool isShareableAcrossCUs(DIDescriptor D) {
132   // When the MDNode can be part of the type system, the DIE can be shared
133   // across CUs.
134   // Combining type units and cross-CU DIE sharing is lower value (since
135   // cross-CU DIE sharing is used in LTO and removes type redundancy at that
136   // level already) but may be implementable for some value in projects
137   // building multiple independent libraries with LTO and then linking those
138   // together.
139   return (D.isType() ||
140           (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
141          !GenerateDwarfTypeUnits;
144 /// getDIE - Returns the debug information entry map slot for the
145 /// specified debug variable. We delegate the request to DwarfDebug
146 /// when the DIE for this MDNode can be shared across CUs. The mappings
147 /// will be kept in DwarfDebug for shareable DIEs.
148 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
149   if (isShareableAcrossCUs(D))
150     return DD->getDIE(D);
151   return MDNodeToDieMap.lookup(D);
154 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
155 /// when the DIE for this MDNode can be shared across CUs. The mappings
156 /// will be kept in DwarfDebug for shareable DIEs.
157 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
158   if (isShareableAcrossCUs(Desc)) {
159     DD->insertDIE(Desc, D);
160     return;
161   }
162   MDNodeToDieMap.insert(std::make_pair(Desc, D));
165 /// addFlag - Add a flag that is true.
166 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
167   if (DD->getDwarfVersion() >= 4)
168     Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
169   else
170     Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
173 /// addUInt - Add an unsigned integer attribute data and value.
174 ///
175 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
176                         Optional<dwarf::Form> Form, uint64_t Integer) {
177   if (!Form)
178     Form = DIEInteger::BestForm(false, Integer);
179   DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
180                         DIEInteger(Integer);
181   Die.addValue(Attribute, *Form, Value);
184 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
185   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
188 /// addSInt - Add an signed integer attribute data and value.
189 ///
190 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
191                         Optional<dwarf::Form> Form, int64_t Integer) {
192   if (!Form)
193     Form = DIEInteger::BestForm(true, Integer);
194   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
195   Die.addValue(Attribute, *Form, Value);
198 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
199                         int64_t Integer) {
200   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
203 /// addString - Add a string attribute data and value. We always emit a
204 /// reference to the string pool instead of immediate strings so that DIEs have
205 /// more predictable sizes. In the case of split dwarf we emit an index
206 /// into another table which gets us the static offset into the string
207 /// table.
208 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
209                           StringRef String) {
211   if (!DD->useSplitDwarf())
212     return addLocalString(Die, Attribute, String);
214   unsigned idx = DU->getStringPool().getIndex(*Asm, String);
215   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
216   DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
217   Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
220 /// addLocalString - Add a string attribute data and value. This is guaranteed
221 /// to be in the local string pool instead of indirected.
222 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
223                                StringRef String) {
224   MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
225   DIEValue *Value;
226   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
227     Value = new (DIEValueAllocator) DIELabel(Symb);
228   else
229     Value = new (DIEValueAllocator) DIEDelta(Symb, DD->getDebugStrSym());
230   DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
231   Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
234 /// addExpr - Add a Dwarf expression attribute data and value.
235 ///
236 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
237   DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
238   Die.addValue((dwarf::Attribute)0, Form, Value);
241 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
242 ///
243 void DwarfUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
244                                 unsigned Index) {
245   DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
246   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
247                                                 : dwarf::DW_FORM_data4;
248   Die.addValue(Attribute, Form, Value);
251 /// addLabel - Add a Dwarf label attribute data and value.
252 ///
253 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
254                          const MCSymbol *Label) {
255   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
256   Die.addValue(Attribute, Form, Value);
259 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
260   addLabel(Die, (dwarf::Attribute)0, Form, Label);
263 /// addSectionLabel - Add a Dwarf section label attribute data and value.
264 ///
265 void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
266                                 const MCSymbol *Label) {
267   if (DD->getDwarfVersion() >= 4)
268     addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
269   else
270     addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
273 /// addSectionOffset - Add an offset into a section attribute data and value.
274 ///
275 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
276                                  uint64_t Integer) {
277   if (DD->getDwarfVersion() >= 4)
278     addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
279   else
280     addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
283 /// addLabelAddress - Add a dwarf label attribute data and value using
284 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
285 ///
286 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
287                                        const MCSymbol *Label) {
289   // Don't use the address pool in non-fission or in the skeleton unit itself.
290   // FIXME: Once GDB supports this, it's probably worthwhile using the address
291   // pool from the skeleton - maybe even in non-fission (possibly fewer
292   // relocations by sharing them in the pool, but we have other ideas about how
293   // to reduce the number of relocations as well/instead).
294   if (!DD->useSplitDwarf() || !Skeleton)
295     return addLocalLabelAddress(Die, Attribute, Label);
297   if (Label)
298     DD->addArangeLabel(SymbolCU(this, Label));
300   unsigned idx = DD->getAddressPool().getIndex(Label);
301   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
302   Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
305 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
306                                             dwarf::Attribute Attribute,
307                                             const MCSymbol *Label) {
308   if (Label)
309     DD->addArangeLabel(SymbolCU(this, Label));
311   Die.addValue(Attribute, dwarf::DW_FORM_addr,
312                Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
313                      : new (DIEValueAllocator) DIEInteger(0));
316 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
317   // If we print assembly, we can't separate .file entries according to
318   // compile units. Thus all files will belong to the default compile unit.
320   // FIXME: add a better feature test than hasRawTextSupport. Even better,
321   // extend .file to support this.
322   return Asm->OutStreamer.EmitDwarfFileDirective(
323       0, DirName, FileName,
324       Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
327 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
328   return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
329                         : getCU().getOrCreateSourceID(FileName, DirName);
332 /// addOpAddress - Add a dwarf op address data and value using the
333 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
334 ///
335 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
336   if (!DD->useSplitDwarf()) {
337     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
338     addLabel(Die, dwarf::DW_FORM_udata, Sym);
339   } else {
340     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
341     addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
342             DD->getAddressPool().getIndex(Sym));
343   }
346 /// addSectionDelta - Add a section label delta attribute data and value.
347 ///
348 void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
349                                 const MCSymbol *Hi, const MCSymbol *Lo) {
350   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
351   Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
352                                                      : dwarf::DW_FORM_data4,
353                Value);
356 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
357                               const MCSymbol *Hi, const MCSymbol *Lo) {
358   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
359   Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
362 /// addDIEEntry - Add a DIE attribute data and value.
363 ///
364 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
365   addDIEEntry(Die, Attribute, createDIEEntry(Entry));
368 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
369   // Flag the type unit reference as a declaration so that if it contains
370   // members (implicit special members, static data member definitions, member
371   // declarations for definitions in this CU, etc) consumers don't get confused
372   // and think this is a full definition.
373   addFlag(Die, dwarf::DW_AT_declaration);
375   Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
376                new (DIEValueAllocator) DIETypeSignature(Type));
379 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
380                             DIEEntry *Entry) {
381   const DIE *DieCU = Die.getUnitOrNull();
382   const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
383   if (!DieCU)
384     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
385     DieCU = &getUnitDie();
386   if (!EntryCU)
387     EntryCU = &getUnitDie();
388   Die.addValue(Attribute,
389                EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
390                Entry);
393 /// Create a DIE with the given Tag, add the DIE to its parent, and
394 /// call insertDIE if MD is not null.
395 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
396   assert(Tag != dwarf::DW_TAG_auto_variable &&
397          Tag != dwarf::DW_TAG_arg_variable);
398   Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
399   DIE &Die = *Parent.getChildren().back();
400   if (N)
401     insertDIE(N, &Die);
402   return Die;
405 /// addBlock - Add block data.
406 ///
407 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
408   Loc->ComputeSize(Asm);
409   DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
410   Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
413 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
414                          DIEBlock *Block) {
415   Block->ComputeSize(Asm);
416   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
417   Die.addValue(Attribute, Block->BestForm(), Block);
420 /// addSourceLine - Add location information to specified debug information
421 /// entry.
422 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
423                               StringRef Directory) {
424   if (Line == 0)
425     return;
427   unsigned FileID = getOrCreateSourceID(File, Directory);
428   assert(FileID && "Invalid file id");
429   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
430   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
433 /// addSourceLine - Add location information to specified debug information
434 /// entry.
435 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
436   assert(V.isVariable());
438   addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
439                 V.getContext().getDirectory());
442 /// addSourceLine - Add location information to specified debug information
443 /// entry.
444 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
445   assert(G.isGlobalVariable());
447   addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
450 /// addSourceLine - Add location information to specified debug information
451 /// entry.
452 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
453   assert(SP.isSubprogram());
455   addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
458 /// addSourceLine - Add location information to specified debug information
459 /// entry.
460 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
461   assert(Ty.isType());
463   addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
466 /// addSourceLine - Add location information to specified debug information
467 /// entry.
468 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
469   assert(Ty.isObjCProperty());
471   DIFile File = Ty.getFile();
472   addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
473                 File.getDirectory());
476 /// addSourceLine - Add location information to specified debug information
477 /// entry.
478 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
479   assert(NS.Verify());
481   addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
484 /// addVariableAddress - Add DW_AT_location attribute for a
485 /// DbgVariable based on provided MachineLocation.
486 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
487                                    MachineLocation Location) {
488   if (DV.variableHasComplexAddress())
489     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
490   else if (DV.isBlockByrefVariable())
491     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
492   else
493     addAddress(Die, dwarf::DW_AT_location, Location,
494                DV.getVariable().isIndirect());
497 /// addRegisterOp - Add register operand.
498 // FIXME: Ideally, this would share the implementation with
499 // AsmPrinter::EmitDwarfRegOpPiece.
500 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
501                                    unsigned SizeInBits, unsigned OffsetInBits) {
502   const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
503   int DWReg = RI->getDwarfRegNum(Reg, false);
504   bool isSubRegister = DWReg < 0;
506   unsigned Idx = 0;
508   // Go up the super-register chain until we hit a valid dwarf register number.
509   for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
510     DWReg = RI->getDwarfRegNum(*SR, false);
511     if (DWReg >= 0)
512       Idx = RI->getSubRegIndex(*SR, Reg);
513   }
515   if (DWReg < 0) {
516     DEBUG(dbgs() << "Invalid Dwarf register number.\n");
517     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
518     return;
519   }
521   // Emit register.
522   if (DWReg < 32)
523     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
524   else {
525     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
526     addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
527   }
529   // Emit mask.
530   bool isPiece = SizeInBits > 0;
531   if (isSubRegister || isPiece) {
532     const unsigned SizeOfByte = 8;
533     unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
534     unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
535     unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
536     unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
537     assert(RegSizeInBits >= SizeInBits && "register smaller than value");
539     if (RegOffsetInBits != PieceOffsetInBits) {
540       // Manually shift the value into place, since the DW_OP_piece
541       // describes the part of the variable, not the position of the
542       // subregister.
543       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
544       addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
545       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
546     }
548     if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
549       assert(PieceSizeInBits > 0 && "piece has zero size");
550       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
551       addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
552       addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
553      } else {
554       assert(PieceSizeInBits > 0 && "piece has zero size");
555       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
556       addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
557     }
558   }
561 /// addRegisterOffset - Add register offset.
562 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
563                                   int64_t Offset) {
564   const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
565   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
566   const TargetRegisterInfo *TRI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
567   if (Reg == TRI->getFrameRegister(*Asm->MF))
568     // If variable offset is based in frame register then use fbreg.
569     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
570   else if (DWReg < 32)
571     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
572   else {
573     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
574     addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
575   }
576   addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
579 /// addAddress - Add an address attribute to a die based on the location
580 /// provided.
581 void DwarfUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
582                            const MachineLocation &Location, bool Indirect) {
583   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
585   if (Location.isReg() && !Indirect)
586     addRegisterOpPiece(*Loc, Location.getReg());
587   else {
588     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
589     if (Indirect && !Location.isReg()) {
590       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
591     }
592   }
594   // Now attach the location information to the DIE.
595   addBlock(Die, Attribute, Loc);
598 /// addComplexAddress - Start with the address based on the location provided,
599 /// and generate the DWARF information necessary to find the actual variable
600 /// given the extra address information encoded in the DbgVariable, starting
601 /// from the starting location.  Add the DWARF information to the die.
602 ///
603 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
604                                   dwarf::Attribute Attribute,
605                                   const MachineLocation &Location) {
606   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
607   unsigned N = DV.getNumAddrElements();
608   unsigned i = 0;
609   if (Location.isReg()) {
610     if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
611       // If first address element is OpPlus then emit
612       // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
613       addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
614       i = 2;
615     } else if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpDeref) {
616         addRegisterOpPiece(*Loc, Location.getReg(),
617                            DV.getVariable().getPieceSize(),
618                            DV.getVariable().getPieceOffset());
619         i = 3;
620     } else
621       addRegisterOpPiece(*Loc, Location.getReg());
622   } else
623     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
625   for (; i < N; ++i) {
626     uint64_t Element = DV.getAddrElement(i);
627     if (Element == DIBuilder::OpPlus) {
628       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
629       addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
631     } else if (Element == DIBuilder::OpDeref) {
632       if (!Location.isReg())
633         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
635     } else if (Element == DIBuilder::OpPiece) {
636       const unsigned SizeOfByte = 8;
637       unsigned PieceOffsetInBits = DV.getAddrElement(++i)*SizeOfByte;
638       unsigned PieceSizeInBits = DV.getAddrElement(++i)*SizeOfByte;
639       // Emit DW_OP_bit_piece Size Offset.
640       assert(PieceSizeInBits > 0 && "piece has zero size");
641       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
642       addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
643       addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
645     } else
646       llvm_unreachable("unknown DIBuilder Opcode");
647   }
649   // Now attach the location information to the DIE.
650   addBlock(Die, Attribute, Loc);
653 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
654    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
655    gives the variable VarName either the struct, or a pointer to the struct, as
656    its type.  This is necessary for various behind-the-scenes things the
657    compiler needs to do with by-reference variables in Blocks.
659    However, as far as the original *programmer* is concerned, the variable
660    should still have type 'SomeType', as originally declared.
662    The function getBlockByrefType dives into the __Block_byref_x_VarName
663    struct to find the original type of the variable, which is then assigned to
664    the variable's Debug Information Entry as its real type.  So far, so good.
665    However now the debugger will expect the variable VarName to have the type
666    SomeType.  So we need the location attribute for the variable to be an
667    expression that explains to the debugger how to navigate through the
668    pointers and struct to find the actual variable of type SomeType.
670    The following function does just that.  We start by getting
671    the "normal" location for the variable. This will be the location
672    of either the struct __Block_byref_x_VarName or the pointer to the
673    struct __Block_byref_x_VarName.
675    The struct will look something like:
677    struct __Block_byref_x_VarName {
678      ... <various fields>
679      struct __Block_byref_x_VarName *forwarding;
680      ... <various other fields>
681      SomeType VarName;
682      ... <maybe more fields>
683    };
685    If we are given the struct directly (as our starting point) we
686    need to tell the debugger to:
688    1).  Add the offset of the forwarding field.
690    2).  Follow that pointer to get the real __Block_byref_x_VarName
691    struct to use (the real one may have been copied onto the heap).
693    3).  Add the offset for the field VarName, to find the actual variable.
695    If we started with a pointer to the struct, then we need to
696    dereference that pointer first, before the other steps.
697    Translating this into DWARF ops, we will need to append the following
698    to the current location description for the variable:
700    DW_OP_deref                    -- optional, if we start with a pointer
701    DW_OP_plus_uconst <forward_fld_offset>
702    DW_OP_deref
703    DW_OP_plus_uconst <varName_fld_offset>
705    That is what this function does.  */
707 /// addBlockByrefAddress - Start with the address based on the location
708 /// provided, and generate the DWARF information necessary to find the
709 /// actual Block variable (navigating the Block struct) based on the
710 /// starting location.  Add the DWARF information to the die.  For
711 /// more information, read large comment just above here.
712 ///
713 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
714                                      dwarf::Attribute Attribute,
715                                      const MachineLocation &Location) {
716   DIType Ty = DV.getType();
717   DIType TmpTy = Ty;
718   uint16_t Tag = Ty.getTag();
719   bool isPointer = false;
721   StringRef varName = DV.getName();
723   if (Tag == dwarf::DW_TAG_pointer_type) {
724     DIDerivedType DTy(Ty);
725     TmpTy = resolve(DTy.getTypeDerivedFrom());
726     isPointer = true;
727   }
729   DICompositeType blockStruct(TmpTy);
731   // Find the __forwarding field and the variable field in the __Block_byref
732   // struct.
733   DIArray Fields = blockStruct.getElements();
734   DIDerivedType varField;
735   DIDerivedType forwardingField;
737   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
738     DIDerivedType DT(Fields.getElement(i));
739     StringRef fieldName = DT.getName();
740     if (fieldName == "__forwarding")
741       forwardingField = DT;
742     else if (fieldName == varName)
743       varField = DT;
744   }
746   // Get the offsets for the forwarding field and the variable field.
747   unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
748   unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
750   // Decode the original location, and use that as the start of the byref
751   // variable's location.
752   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
754   if (Location.isReg())
755     addRegisterOpPiece(*Loc, Location.getReg());
756   else
757     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
759   // If we started with a pointer to the __Block_byref... struct, then
760   // the first thing we need to do is dereference the pointer (DW_OP_deref).
761   if (isPointer)
762     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
764   // Next add the offset for the '__forwarding' field:
765   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
766   // adding the offset if it's 0.
767   if (forwardingFieldOffset > 0) {
768     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
769     addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
770   }
772   // Now dereference the __forwarding field to get to the real __Block_byref
773   // struct:  DW_OP_deref.
774   addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
776   // Now that we've got the real __Block_byref... struct, add the offset
777   // for the variable's field to get to the location of the actual variable:
778   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
779   if (varFieldOffset > 0) {
780     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
781     addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
782   }
784   // Now attach the location information to the DIE.
785   addBlock(Die, Attribute, Loc);
788 /// Return true if type encoding is unsigned.
789 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
790   DIDerivedType DTy(Ty);
791   if (DTy.isDerivedType()) {
792     dwarf::Tag T = (dwarf::Tag)Ty.getTag();
793     // Encode pointer constants as unsigned bytes. This is used at least for
794     // null pointer constant emission.
795     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
796     // here, but accept them for now due to a bug in SROA producing bogus
797     // dbg.values.
798     if (T == dwarf::DW_TAG_pointer_type ||
799         T == dwarf::DW_TAG_ptr_to_member_type ||
800         T == dwarf::DW_TAG_reference_type ||
801         T == dwarf::DW_TAG_rvalue_reference_type)
802       return true;
803     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
804            T == dwarf::DW_TAG_volatile_type ||
805            T == dwarf::DW_TAG_restrict_type ||
806            T == dwarf::DW_TAG_enumeration_type);
807     if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
808       return isUnsignedDIType(DD, DD->resolve(Deriv));
809     // FIXME: Enums without a fixed underlying type have unknown signedness
810     // here, leading to incorrectly emitted constants.
811     assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
812     return false;
813   }
815   DIBasicType BTy(Ty);
816   assert(BTy.isBasicType());
817   unsigned Encoding = BTy.getEncoding();
818   assert((Encoding == dwarf::DW_ATE_unsigned ||
819           Encoding == dwarf::DW_ATE_unsigned_char ||
820           Encoding == dwarf::DW_ATE_signed ||
821           Encoding == dwarf::DW_ATE_signed_char ||
822           Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
823          "Unsupported encoding");
824   return (Encoding == dwarf::DW_ATE_unsigned ||
825           Encoding == dwarf::DW_ATE_unsigned_char ||
826           Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
829 /// If this type is derived from a base type then return base type size.
830 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
831   unsigned Tag = Ty.getTag();
833   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
834       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
835       Tag != dwarf::DW_TAG_restrict_type)
836     return Ty.getSizeInBits();
838   DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
840   // If this type is not derived from any type or the type is a declaration then
841   // take conservative approach.
842   if (!BaseType.isValid() || BaseType.isForwardDecl())
843     return Ty.getSizeInBits();
845   // If this is a derived type, go ahead and get the base type, unless it's a
846   // reference then it's just the size of the field. Pointer types have no need
847   // of this since they're a different type of qualification on the type.
848   if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
849       BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
850     return Ty.getSizeInBits();
852   if (BaseType.isDerivedType())
853     return getBaseTypeSize(DD, DIDerivedType(BaseType));
855   return BaseType.getSizeInBits();
858 /// addConstantFPValue - Add constant value entry in variable DIE.
859 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
860   assert(MO.isFPImm() && "Invalid machine operand!");
861   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
862   APFloat FPImm = MO.getFPImm()->getValueAPF();
864   // Get the raw data form of the floating point.
865   const APInt FltVal = FPImm.bitcastToAPInt();
866   const char *FltPtr = (const char *)FltVal.getRawData();
868   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
869   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
870   int Incr = (LittleEndian ? 1 : -1);
871   int Start = (LittleEndian ? 0 : NumBytes - 1);
872   int Stop = (LittleEndian ? NumBytes : -1);
874   // Output the constant to DWARF one byte at a time.
875   for (; Start != Stop; Start += Incr)
876     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
878   addBlock(Die, dwarf::DW_AT_const_value, Block);
881 /// addConstantFPValue - Add constant value entry in variable DIE.
882 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
883   // Pass this down to addConstantValue as an unsigned bag of bits.
884   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
887 /// addConstantValue - Add constant value entry in variable DIE.
888 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
889   addConstantValue(Die, CI->getValue(), Ty);
892 /// addConstantValue - Add constant value entry in variable DIE.
893 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
894                                  DIType Ty) {
895   assert(MO.isImm() && "Invalid machine operand!");
897   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
900 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
901   // FIXME: This is a bit conservative/simple - it emits negative values always
902   // sign extended to 64 bits rather than minimizing the number of bytes.
903   addUInt(Die, dwarf::DW_AT_const_value,
904           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
907 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
908   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
911 // addConstantValue - Add constant value entry in variable DIE.
912 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
913   unsigned CIBitWidth = Val.getBitWidth();
914   if (CIBitWidth <= 64) {
915     addConstantValue(Die, Unsigned,
916                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
917     return;
918   }
920   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
922   // Get the raw data form of the large APInt.
923   const uint64_t *Ptr64 = Val.getRawData();
925   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
926   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
928   // Output the constant to DWARF one byte at a time.
929   for (int i = 0; i < NumBytes; i++) {
930     uint8_t c;
931     if (LittleEndian)
932       c = Ptr64[i / 8] >> (8 * (i & 7));
933     else
934       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
935     addUInt(*Block, dwarf::DW_FORM_data1, c);
936   }
938   addBlock(Die, dwarf::DW_AT_const_value, Block);
941 /// addTemplateParams - Add template parameters into buffer.
942 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
943   // Add template parameters.
944   for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
945     DIDescriptor Element = TParams.getElement(i);
946     if (Element.isTemplateTypeParameter())
947       constructTemplateTypeParameterDIE(Buffer,
948                                         DITemplateTypeParameter(Element));
949     else if (Element.isTemplateValueParameter())
950       constructTemplateValueParameterDIE(Buffer,
951                                          DITemplateValueParameter(Element));
952   }
955 /// getOrCreateContextDIE - Get context owner's DIE.
956 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
957   if (!Context || Context.isFile())
958     return &getUnitDie();
959   if (Context.isType())
960     return getOrCreateTypeDIE(DIType(Context));
961   if (Context.isNameSpace())
962     return getOrCreateNameSpace(DINameSpace(Context));
963   if (Context.isSubprogram())
964     return getOrCreateSubprogramDIE(DISubprogram(Context));
965   return getDIE(Context);
968 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
969   DIScope Context = resolve(Ty.getContext());
970   DIE *ContextDIE = getOrCreateContextDIE(Context);
972   if (DIE *TyDIE = getDIE(Ty))
973     return TyDIE;
975   // Create new type.
976   DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
978   constructTypeDIE(TyDIE, Ty);
980   updateAcceleratorTables(Context, Ty, TyDIE);
981   return &TyDIE;
984 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
985 /// given DIType.
986 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
987   if (!TyNode)
988     return nullptr;
990   DIType Ty(TyNode);
991   assert(Ty.isType());
992   assert(Ty == resolve(Ty.getRef()) &&
993          "type was not uniqued, possible ODR violation.");
995   // DW_TAG_restrict_type is not supported in DWARF2
996   if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
997     return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
999   // Construct the context before querying for the existence of the DIE in case
1000   // such construction creates the DIE.
1001   DIScope Context = resolve(Ty.getContext());
1002   DIE *ContextDIE = getOrCreateContextDIE(Context);
1003   assert(ContextDIE);
1005   if (DIE *TyDIE = getDIE(Ty))
1006     return TyDIE;
1008   // Create new type.
1009   DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1011   updateAcceleratorTables(Context, Ty, TyDIE);
1013   if (Ty.isBasicType())
1014     constructTypeDIE(TyDIE, DIBasicType(Ty));
1015   else if (Ty.isCompositeType()) {
1016     DICompositeType CTy(Ty);
1017     if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1018       if (MDString *TypeId = CTy.getIdentifier()) {
1019         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1020         // Skip updating the accelerator tables since this is not the full type.
1021         return &TyDIE;
1022       }
1023     constructTypeDIE(TyDIE, CTy);
1024   } else {
1025     assert(Ty.isDerivedType() && "Unknown kind of DIType");
1026     constructTypeDIE(TyDIE, DIDerivedType(Ty));
1027   }
1029   return &TyDIE;
1032 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1033                                         const DIE &TyDIE) {
1034   if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1035     bool IsImplementation = 0;
1036     if (Ty.isCompositeType()) {
1037       DICompositeType CT(Ty);
1038       // A runtime language of 0 actually means C/C++ and that any
1039       // non-negative value is some version of Objective-C/C++.
1040       IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1041     }
1042     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1043     DD->addAccelType(Ty.getName(), TyDIE, Flags);
1045     if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1046          Context.isNameSpace()) &&
1047         getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1048       GlobalTypes[getParentContextString(Context) + Ty.getName().str()] =
1049           &TyDIE;
1050   }
1053 /// addType - Add a new type attribute to the specified entity.
1054 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
1055   assert(Ty && "Trying to add a type that doesn't exist?");
1057   // Check for pre-existence.
1058   DIEEntry *Entry = getDIEEntry(Ty);
1059   // If it exists then use the existing value.
1060   if (Entry) {
1061     addDIEEntry(Entity, Attribute, Entry);
1062     return;
1063   }
1065   // Construct type.
1066   DIE *Buffer = getOrCreateTypeDIE(Ty);
1068   // Set up proxy.
1069   Entry = createDIEEntry(*Buffer);
1070   insertDIEEntry(Ty, Entry);
1071   addDIEEntry(Entity, Attribute, Entry);
1074 /// addGlobalName - Add a new global name to the compile unit.
1075 void DwarfUnit::addGlobalName(StringRef Name, DIE &Die, DIScope Context) {
1076   if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1077     return;
1078   std::string FullName = getParentContextString(Context) + Name.str();
1079   GlobalNames[FullName] = &Die;
1082 /// getParentContextString - Walks the metadata parent chain in a language
1083 /// specific manner (using the compile unit language) and returns
1084 /// it as a string. This is done at the metadata level because DIEs may
1085 /// not currently have been added to the parent context and walking the
1086 /// DIEs looking for names is more expensive than walking the metadata.
1087 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1088   if (!Context)
1089     return "";
1091   // FIXME: Decide whether to implement this for non-C++ languages.
1092   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1093     return "";
1095   std::string CS;
1096   SmallVector<DIScope, 1> Parents;
1097   while (!Context.isCompileUnit()) {
1098     Parents.push_back(Context);
1099     if (Context.getContext())
1100       Context = resolve(Context.getContext());
1101     else
1102       // Structure, etc types will have a NULL context if they're at the top
1103       // level.
1104       break;
1105   }
1107   // Reverse iterate over our list to go from the outermost construct to the
1108   // innermost.
1109   for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1110                                                   E = Parents.rend();
1111        I != E; ++I) {
1112     DIScope Ctx = *I;
1113     StringRef Name = Ctx.getName();
1114     if (Name.empty() && Ctx.isNameSpace())
1115       Name = "(anonymous namespace)";
1116     if (!Name.empty()) {
1117       CS += Name;
1118       CS += "::";
1119     }
1120   }
1121   return CS;
1124 /// constructTypeDIE - Construct basic type die from DIBasicType.
1125 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1126   // Get core information.
1127   StringRef Name = BTy.getName();
1128   // Add name if not anonymous or intermediate type.
1129   if (!Name.empty())
1130     addString(Buffer, dwarf::DW_AT_name, Name);
1132   // An unspecified type only has a name attribute.
1133   if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1134     return;
1136   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1137           BTy.getEncoding());
1139   uint64_t Size = BTy.getSizeInBits() >> 3;
1140   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1143 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1144 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1145   // Get core information.
1146   StringRef Name = DTy.getName();
1147   uint64_t Size = DTy.getSizeInBits() >> 3;
1148   uint16_t Tag = Buffer.getTag();
1150   // Map to main type, void will not have a type.
1151   DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1152   if (FromTy)
1153     addType(Buffer, FromTy);
1155   // Add name if not anonymous or intermediate type.
1156   if (!Name.empty())
1157     addString(Buffer, dwarf::DW_AT_name, Name);
1159   // Add size if non-zero (derived types might be zero-sized.)
1160   if (Size && Tag != dwarf::DW_TAG_pointer_type)
1161     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1163   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1164     addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1165                 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
1166   // Add source line info if available and TyDesc is not a forward declaration.
1167   if (!DTy.isForwardDecl())
1168     addSourceLine(Buffer, DTy);
1171 /// constructSubprogramArguments - Construct function argument DIEs.
1172 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1173   for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1174     DIType Ty = resolve(Args.getElement(i));
1175     if (!Ty) {
1176       assert(i == N-1 && "Unspecified parameter must be the last argument");
1177       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1178     } else {
1179       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1180       addType(Arg, DIType(Ty));
1181       if (DIType(Ty).isArtificial())
1182         addFlag(Arg, dwarf::DW_AT_artificial);
1183     }
1184   }
1187 /// constructTypeDIE - Construct type DIE from DICompositeType.
1188 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1189   // Add name if not anonymous or intermediate type.
1190   StringRef Name = CTy.getName();
1192   uint64_t Size = CTy.getSizeInBits() >> 3;
1193   uint16_t Tag = Buffer.getTag();
1195   switch (Tag) {
1196   case dwarf::DW_TAG_array_type:
1197     constructArrayTypeDIE(Buffer, CTy);
1198     break;
1199   case dwarf::DW_TAG_enumeration_type:
1200     constructEnumTypeDIE(Buffer, CTy);
1201     break;
1202   case dwarf::DW_TAG_subroutine_type: {
1203     // Add return type. A void return won't have a type.
1204     DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1205     DIType RTy(resolve(Elements.getElement(0)));
1206     if (RTy)
1207       addType(Buffer, RTy);
1209     bool isPrototyped = true;
1210     if (Elements.getNumElements() == 2 &&
1211         !Elements.getElement(1))
1212       isPrototyped = false;
1214     constructSubprogramArguments(Buffer, Elements);
1216     // Add prototype flag if we're dealing with a C language and the
1217     // function has been prototyped.
1218     uint16_t Language = getLanguage();
1219     if (isPrototyped &&
1220         (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1221          Language == dwarf::DW_LANG_ObjC))
1222       addFlag(Buffer, dwarf::DW_AT_prototyped);
1224     if (CTy.isLValueReference())
1225       addFlag(Buffer, dwarf::DW_AT_reference);
1227     if (CTy.isRValueReference())
1228       addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1229   } break;
1230   case dwarf::DW_TAG_structure_type:
1231   case dwarf::DW_TAG_union_type:
1232   case dwarf::DW_TAG_class_type: {
1233     // Add elements to structure type.
1234     DIArray Elements = CTy.getElements();
1235     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1236       DIDescriptor Element = Elements.getElement(i);
1237       if (Element.isSubprogram())
1238         getOrCreateSubprogramDIE(DISubprogram(Element));
1239       else if (Element.isDerivedType()) {
1240         DIDerivedType DDTy(Element);
1241         if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1242           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1243           addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1244                   dwarf::DW_AT_friend);
1245         } else if (DDTy.isStaticMember()) {
1246           getOrCreateStaticMemberDIE(DDTy);
1247         } else {
1248           constructMemberDIE(Buffer, DDTy);
1249         }
1250       } else if (Element.isObjCProperty()) {
1251         DIObjCProperty Property(Element);
1252         DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1253         StringRef PropertyName = Property.getObjCPropertyName();
1254         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1255         if (Property.getType())
1256           addType(ElemDie, Property.getType());
1257         addSourceLine(ElemDie, Property);
1258         StringRef GetterName = Property.getObjCPropertyGetterName();
1259         if (!GetterName.empty())
1260           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1261         StringRef SetterName = Property.getObjCPropertySetterName();
1262         if (!SetterName.empty())
1263           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1264         unsigned PropertyAttributes = 0;
1265         if (Property.isReadOnlyObjCProperty())
1266           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1267         if (Property.isReadWriteObjCProperty())
1268           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1269         if (Property.isAssignObjCProperty())
1270           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1271         if (Property.isRetainObjCProperty())
1272           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1273         if (Property.isCopyObjCProperty())
1274           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1275         if (Property.isNonAtomicObjCProperty())
1276           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1277         if (PropertyAttributes)
1278           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1279                   PropertyAttributes);
1281         DIEEntry *Entry = getDIEEntry(Element);
1282         if (!Entry) {
1283           Entry = createDIEEntry(ElemDie);
1284           insertDIEEntry(Element, Entry);
1285         }
1286       } else
1287         continue;
1288     }
1290     if (CTy.isAppleBlockExtension())
1291       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1293     DICompositeType ContainingType(resolve(CTy.getContainingType()));
1294     if (ContainingType)
1295       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1296                   *getOrCreateTypeDIE(ContainingType));
1298     if (CTy.isObjcClassComplete())
1299       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1301     // Add template parameters to a class, structure or union types.
1302     // FIXME: The support isn't in the metadata for this yet.
1303     if (Tag == dwarf::DW_TAG_class_type ||
1304         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1305       addTemplateParams(Buffer, CTy.getTemplateParams());
1307     break;
1308   }
1309   default:
1310     break;
1311   }
1313   // Add name if not anonymous or intermediate type.
1314   if (!Name.empty())
1315     addString(Buffer, dwarf::DW_AT_name, Name);
1317   if (Tag == dwarf::DW_TAG_enumeration_type ||
1318       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1319       Tag == dwarf::DW_TAG_union_type) {
1320     // Add size if non-zero (derived types might be zero-sized.)
1321     // TODO: Do we care about size for enum forward declarations?
1322     if (Size)
1323       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1324     else if (!CTy.isForwardDecl())
1325       // Add zero size if it is not a forward declaration.
1326       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1328     // If we're a forward decl, say so.
1329     if (CTy.isForwardDecl())
1330       addFlag(Buffer, dwarf::DW_AT_declaration);
1332     // Add source line info if available.
1333     if (!CTy.isForwardDecl())
1334       addSourceLine(Buffer, CTy);
1336     // No harm in adding the runtime language to the declaration.
1337     unsigned RLang = CTy.getRunTimeLang();
1338     if (RLang)
1339       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1340               RLang);
1341   }
1344 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1345 /// DITemplateTypeParameter.
1346 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1347                                                   DITemplateTypeParameter TP) {
1348   DIE &ParamDIE =
1349       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1350   // Add the type if it exists, it could be void and therefore no type.
1351   if (TP.getType())
1352     addType(ParamDIE, resolve(TP.getType()));
1353   if (!TP.getName().empty())
1354     addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1357 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1358 /// DITemplateValueParameter.
1359 void
1360 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1361                                               DITemplateValueParameter VP) {
1362   DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1364   // Add the type if there is one, template template and template parameter
1365   // packs will not have a type.
1366   if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1367     addType(ParamDIE, resolve(VP.getType()));
1368   if (!VP.getName().empty())
1369     addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1370   if (Value *Val = VP.getValue()) {
1371     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1372       addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1373     else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1374       // For declaration non-type template parameters (such as global values and
1375       // functions)
1376       DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1377       addOpAddress(*Loc, Asm->getSymbol(GV));
1378       // Emit DW_OP_stack_value to use the address as the immediate value of the
1379       // parameter, rather than a pointer to it.
1380       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1381       addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1382     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1383       assert(isa<MDString>(Val));
1384       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1385                 cast<MDString>(Val)->getString());
1386     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1387       assert(isa<MDNode>(Val));
1388       DIArray A(cast<MDNode>(Val));
1389       addTemplateParams(ParamDIE, A);
1390     }
1391   }
1394 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1395 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1396   // Construct the context before querying for the existence of the DIE in case
1397   // such construction creates the DIE.
1398   DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1400   if (DIE *NDie = getDIE(NS))
1401     return NDie;
1402   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1404   StringRef Name = NS.getName();
1405   if (!Name.empty())
1406     addString(NDie, dwarf::DW_AT_name, NS.getName());
1407   else
1408     Name = "(anonymous namespace)";
1409   DD->addAccelNamespace(Name, NDie);
1410   addGlobalName(Name, NDie, NS.getContext());
1411   addSourceLine(NDie, NS);
1412   return &NDie;
1415 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1416 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1417   // Construct the context before querying for the existence of the DIE in case
1418   // such construction creates the DIE (as is the case for member function
1419   // declarations).
1420   DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1422   if (DIE *SPDie = getDIE(SP))
1423     return SPDie;
1425   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1426     // Add subprogram definitions to the CU die directly.
1427     ContextDIE = &getUnitDie();
1428     // Build the decl now to ensure it precedes the definition.
1429     getOrCreateSubprogramDIE(SPDecl);
1430   }
1432   // DW_TAG_inlined_subroutine may refer to this DIE.
1433   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1435   // Stop here and fill this in later, depending on whether or not this
1436   // subprogram turns out to have inlined instances or not.
1437   if (SP.isDefinition())
1438     return &SPDie;
1440   applySubprogramAttributes(SP, SPDie);
1441   return &SPDie;
1444 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1445   DISubprogram SPDecl = SP.getFunctionDeclaration();
1446   DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1447   applySubprogramAttributes(SP, SPDie);
1448   addGlobalName(SP.getName(), SPDie, Context);
1451 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1452   DIE *DeclDie = nullptr;
1453   StringRef DeclLinkageName;
1454   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1455     DeclDie = getDIE(SPDecl);
1456     assert(DeclDie && "This DIE should've already been constructed when the "
1457                       "definition DIE was created in "
1458                       "getOrCreateSubprogramDIE");
1459     DeclLinkageName = SPDecl.getLinkageName();
1460   }
1462   // Add function template parameters.
1463   addTemplateParams(SPDie, SP.getTemplateParams());
1465   // Add the linkage name if we have one and it isn't in the Decl.
1466   StringRef LinkageName = SP.getLinkageName();
1467   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1468           LinkageName == DeclLinkageName) &&
1469          "decl has a linkage name and it is different");
1470   if (!LinkageName.empty() && DeclLinkageName.empty())
1471     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1472               GlobalValue::getRealLinkageName(LinkageName));
1474   if (DeclDie) {
1475     // Refer to the function declaration where all the other attributes will be
1476     // found.
1477     addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1478     return;
1479   }
1481   // Constructors and operators for anonymous aggregates do not have names.
1482   if (!SP.getName().empty())
1483     addString(SPDie, dwarf::DW_AT_name, SP.getName());
1485   // Skip the rest of the attributes under -gmlt to save space.
1486   if(getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1487     return;
1489   addSourceLine(SPDie, SP);
1491   // Add the prototype if we have a prototype and we have a C like
1492   // language.
1493   uint16_t Language = getLanguage();
1494   if (SP.isPrototyped() &&
1495       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1496        Language == dwarf::DW_LANG_ObjC))
1497     addFlag(SPDie, dwarf::DW_AT_prototyped);
1499   DISubroutineType SPTy = SP.getType();
1500   assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1501          "the type of a subprogram should be a subroutine");
1503   DITypeArray Args = SPTy.getTypeArray();
1504   // Add a return type. If this is a type like a C/C++ void type we don't add a
1505   // return type.
1506   if (resolve(Args.getElement(0)))
1507     addType(SPDie, DIType(resolve(Args.getElement(0))));
1509   unsigned VK = SP.getVirtuality();
1510   if (VK) {
1511     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1512     DIELoc *Block = getDIELoc();
1513     addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1514     addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1515     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1516     ContainingTypeMap.insert(
1517         std::make_pair(&SPDie, resolve(SP.getContainingType())));
1518   }
1520   if (!SP.isDefinition()) {
1521     addFlag(SPDie, dwarf::DW_AT_declaration);
1523     // Add arguments. Do not add arguments for subprogram definition. They will
1524     // be handled while processing variables.
1525     constructSubprogramArguments(SPDie, Args);
1526   }
1528   if (SP.isArtificial())
1529     addFlag(SPDie, dwarf::DW_AT_artificial);
1531   if (!SP.isLocalToUnit())
1532     addFlag(SPDie, dwarf::DW_AT_external);
1534   if (SP.isOptimized())
1535     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1537   if (unsigned isa = Asm->getISAEncoding()) {
1538     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1539   }
1541   if (SP.isLValueReference())
1542     addFlag(SPDie, dwarf::DW_AT_reference);
1544   if (SP.isRValueReference())
1545     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1547   if (SP.isProtected())
1548     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1549             dwarf::DW_ACCESS_protected);
1550   else if (SP.isPrivate())
1551     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1552             dwarf::DW_ACCESS_private);
1553   else if (SP.isPublic())
1554     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1555             dwarf::DW_ACCESS_public);
1557   if (SP.isExplicit())
1558     addFlag(SPDie, dwarf::DW_AT_explicit);
1561 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1562                                         DIE &VariableDie) {
1563   StringRef Name = Var.getName();
1564   if (!Name.empty())
1565     addString(VariableDie, dwarf::DW_AT_name, Name);
1566   addSourceLine(VariableDie, Var.getVariable());
1567   addType(VariableDie, Var.getType());
1568   if (Var.isArtificial())
1569     addFlag(VariableDie, dwarf::DW_AT_artificial);
1572 // Return const expression if value is a GEP to access merged global
1573 // constant. e.g.
1574 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1575 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1576   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1577   if (!CE || CE->getNumOperands() != 3 ||
1578       CE->getOpcode() != Instruction::GetElementPtr)
1579     return nullptr;
1581   // First operand points to a global struct.
1582   Value *Ptr = CE->getOperand(0);
1583   if (!isa<GlobalValue>(Ptr) ||
1584       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1585     return nullptr;
1587   // Second operand is zero.
1588   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1589   if (!CI || !CI->isZero())
1590     return nullptr;
1592   // Third operand is offset.
1593   if (!isa<ConstantInt>(CE->getOperand(2)))
1594     return nullptr;
1596   return CE;
1599 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
1600 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(DIGlobalVariable GV) {
1601   // Check for pre-existence.
1602   if (DIE *Die = getDIE(GV))
1603     return Die;
1605   assert(GV.isGlobalVariable());
1607   DIScope GVContext = GV.getContext();
1608   DIType GTy = DD->resolve(GV.getType());
1610   // If this is a static data member definition, some attributes belong
1611   // to the declaration DIE.
1612   DIE *VariableDIE = nullptr;
1613   bool IsStaticMember = false;
1614   DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1615   if (SDMDecl.Verify()) {
1616     assert(SDMDecl.isStaticMember() && "Expected static member decl");
1617     // We need the declaration DIE that is in the static member's class.
1618     VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1619     IsStaticMember = true;
1620   }
1622   // If this is not a static data member definition, create the variable
1623   // DIE and add the initial set of attributes to it.
1624   if (!VariableDIE) {
1625     // Construct the context before querying for the existence of the DIE in
1626     // case such construction creates the DIE.
1627     DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1629     // Add to map.
1630     VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1632     // Add name and type.
1633     addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1634     addType(*VariableDIE, GTy);
1636     // Add scoping info.
1637     if (!GV.isLocalToUnit())
1638       addFlag(*VariableDIE, dwarf::DW_AT_external);
1640     // Add line number info.
1641     addSourceLine(*VariableDIE, GV);
1642   }
1644   // Add location.
1645   bool addToAccelTable = false;
1646   DIE *VariableSpecDIE = nullptr;
1647   bool isGlobalVariable = GV.getGlobal() != nullptr;
1648   if (isGlobalVariable) {
1649     addToAccelTable = true;
1650     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1651     const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1652     if (GV.getGlobal()->isThreadLocal()) {
1653       // FIXME: Make this work with -gsplit-dwarf.
1654       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1655       assert((PointerSize == 4 || PointerSize == 8) &&
1656              "Add support for other sizes if necessary");
1657       // Based on GCC's support for TLS:
1658       if (!DD->useSplitDwarf()) {
1659         // 1) Start with a constNu of the appropriate pointer size
1660         addUInt(*Loc, dwarf::DW_FORM_data1,
1661                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1662         // 2) containing the (relocated) offset of the TLS variable
1663         //    within the module's TLS block.
1664         addExpr(*Loc, dwarf::DW_FORM_udata,
1665                 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1666       } else {
1667         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1668         addUInt(*Loc, dwarf::DW_FORM_udata,
1669                 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1670       }
1671       // 3) followed by a custom OP to make the debugger do a TLS lookup.
1672       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1673     } else {
1674       DD->addArangeLabel(SymbolCU(this, Sym));
1675       addOpAddress(*Loc, Sym);
1676     }
1677     // A static member's declaration is already flagged as such.
1678     if (!SDMDecl.Verify() && !GV.isDefinition())
1679       addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1680     // Do not create specification DIE if context is either compile unit
1681     // or a subprogram.
1682     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1683         !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1684       // Create specification DIE.
1685       VariableSpecDIE = &createAndAddDIE(dwarf::DW_TAG_variable, UnitDie);
1686       addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, *VariableDIE);
1687       addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
1688       // A static member's declaration is already flagged as such.
1689       if (!SDMDecl.Verify())
1690         addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1691     } else {
1692       addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1693     }
1694     // Add the linkage name.
1695     StringRef LinkageName = GV.getLinkageName();
1696     if (!LinkageName.empty())
1697       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1698       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1699       // TAG_variable.
1700       addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
1701                                                   : *VariableDIE,
1702                 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1703                                            : dwarf::DW_AT_MIPS_linkage_name,
1704                 GlobalValue::getRealLinkageName(LinkageName));
1705   } else if (const ConstantInt *CI =
1706                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1707     // AT_const_value was added when the static member was created. To avoid
1708     // emitting AT_const_value multiple times, we only add AT_const_value when
1709     // it is not a static member.
1710     if (!IsStaticMember)
1711       addConstantValue(*VariableDIE, CI, GTy);
1712   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1713     addToAccelTable = true;
1714     // GV is a merged global.
1715     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1716     Value *Ptr = CE->getOperand(0);
1717     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1718     DD->addArangeLabel(SymbolCU(this, Sym));
1719     addOpAddress(*Loc, Sym);
1720     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1721     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1722     addUInt(*Loc, dwarf::DW_FORM_udata,
1723             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1724     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1725     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1726   }
1728   DIE *ResultDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1730   if (addToAccelTable) {
1731     DD->addAccelName(GV.getName(), *ResultDIE);
1733     // If the linkage name is different than the name, go ahead and output
1734     // that as well into the name table.
1735     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1736       DD->addAccelName(GV.getLinkageName(), *ResultDIE);
1737   }
1739   addGlobalName(GV.getName(), *ResultDIE, GV.getContext());
1740   return ResultDIE;
1743 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1744 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1745   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1746   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1748   // The LowerBound value defines the lower bounds which is typically zero for
1749   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1750   // Count == -1 then the array is unbounded and we do not emit
1751   // DW_AT_lower_bound and DW_AT_count attributes.
1752   int64_t LowerBound = SR.getLo();
1753   int64_t DefaultLowerBound = getDefaultLowerBound();
1754   int64_t Count = SR.getCount();
1756   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1757     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1759   if (Count != -1)
1760     // FIXME: An unbounded array should reference the expression that defines
1761     // the array.
1762     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1765 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1766 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1767   if (CTy.isVector())
1768     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1770   // Emit the element type.
1771   addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1773   // Get an anonymous type for index type.
1774   // FIXME: This type should be passed down from the front end
1775   // as different languages may have different sizes for indexes.
1776   DIE *IdxTy = getIndexTyDie();
1777   if (!IdxTy) {
1778     // Construct an integer type to use for indexes.
1779     IdxTy = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1780     addString(*IdxTy, dwarf::DW_AT_name, "sizetype");
1781     addUInt(*IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1782     addUInt(*IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1783             dwarf::DW_ATE_unsigned);
1784     setIndexTyDie(IdxTy);
1785   }
1787   // Add subranges to array type.
1788   DIArray Elements = CTy.getElements();
1789   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1790     DIDescriptor Element = Elements.getElement(i);
1791     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1792       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1793   }
1796 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1797 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1798   DIArray Elements = CTy.getElements();
1800   // Add enumerators to enumeration type.
1801   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1802     DIEnumerator Enum(Elements.getElement(i));
1803     if (Enum.isEnumerator()) {
1804       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1805       StringRef Name = Enum.getName();
1806       addString(Enumerator, dwarf::DW_AT_name, Name);
1807       int64_t Value = Enum.getEnumValue();
1808       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1809               Value);
1810     }
1811   }
1812   DIType DTy = resolve(CTy.getTypeDerivedFrom());
1813   if (DTy) {
1814     addType(Buffer, DTy);
1815     addFlag(Buffer, dwarf::DW_AT_enum_class);
1816   }
1819 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1820 /// vtables.
1821 void DwarfUnit::constructContainingTypeDIEs() {
1822   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1823                                                  CE = ContainingTypeMap.end();
1824        CI != CE; ++CI) {
1825     DIE &SPDie = *CI->first;
1826     DIDescriptor D(CI->second);
1827     if (!D)
1828       continue;
1829     DIE *NDie = getDIE(D);
1830     if (!NDie)
1831       continue;
1832     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1833   }
1836 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1837 std::unique_ptr<DIE> DwarfUnit::constructVariableDIE(DbgVariable &DV,
1838                                                      bool Abstract) {
1839   auto D = constructVariableDIEImpl(DV, Abstract);
1840   DV.setDIE(*D);
1841   return D;
1844 std::unique_ptr<DIE> DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1845                                                          bool Abstract) {
1846   // Define variable debug information entry.
1847   auto VariableDie = make_unique<DIE>(DV.getTag());
1849   if (Abstract) {
1850     applyVariableAttributes(DV, *VariableDie);
1851     return VariableDie;
1852   }
1854   // Add variable address.
1856   unsigned Offset = DV.getDotDebugLocOffset();
1857   if (Offset != ~0U) {
1858     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
1859     return VariableDie;
1860   }
1862   // Check if variable is described by a DBG_VALUE instruction.
1863   if (const MachineInstr *DVInsn = DV.getMInsn()) {
1864     assert(DVInsn->getNumOperands() == 3);
1865     if (DVInsn->getOperand(0).isReg()) {
1866       const MachineOperand RegOp = DVInsn->getOperand(0);
1867       // If the second operand is an immediate, this is an indirect value.
1868       if (DVInsn->getOperand(1).isImm()) {
1869         MachineLocation Location(RegOp.getReg(),
1870                                  DVInsn->getOperand(1).getImm());
1871         addVariableAddress(DV, *VariableDie, Location);
1872       } else if (RegOp.getReg())
1873         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
1874     } else if (DVInsn->getOperand(0).isImm())
1875       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
1876     else if (DVInsn->getOperand(0).isFPImm())
1877       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
1878     else if (DVInsn->getOperand(0).isCImm())
1879       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
1880                        DV.getType());
1882     return VariableDie;
1883   }
1885   // .. else use frame index.
1886   int FI = DV.getFrameIndex();
1887   if (FI != ~0) {
1888     unsigned FrameReg = 0;
1889     const TargetFrameLowering *TFI =
1890         Asm->TM.getSubtargetImpl()->getFrameLowering();
1891     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1892     MachineLocation Location(FrameReg, Offset);
1893     addVariableAddress(DV, *VariableDie, Location);
1894   }
1896   return VariableDie;
1899 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1900 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1901   DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1902   StringRef Name = DT.getName();
1903   if (!Name.empty())
1904     addString(MemberDie, dwarf::DW_AT_name, Name);
1906   addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1908   addSourceLine(MemberDie, DT);
1910   if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1912     // For C++, virtual base classes are not at fixed offset. Use following
1913     // expression to extract appropriate offset from vtable.
1914     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1916     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1917     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1918     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1919     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1920     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1921     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1922     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1923     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1925     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1926   } else {
1927     uint64_t Size = DT.getSizeInBits();
1928     uint64_t FieldSize = getBaseTypeSize(DD, DT);
1929     uint64_t OffsetInBytes;
1931     if (Size != FieldSize) {
1932       // Handle bitfield, assume bytes are 8 bits.
1933       addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1934       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1936       uint64_t Offset = DT.getOffsetInBits();
1937       uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1938       uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1939       uint64_t FieldOffset = (HiMark - FieldSize);
1940       Offset -= FieldOffset;
1942       // Maybe we need to work from the other end.
1943       if (Asm->getDataLayout().isLittleEndian())
1944         Offset = FieldSize - (Offset + Size);
1945       addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1947       // Here DW_AT_data_member_location points to the anonymous
1948       // field that includes this bit field.
1949       OffsetInBytes = FieldOffset >> 3;
1950     } else
1951       // This is not a bitfield.
1952       OffsetInBytes = DT.getOffsetInBits() >> 3;
1954     if (DD->getDwarfVersion() <= 2) {
1955       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1956       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1957       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1958       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1959     } else
1960       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1961               OffsetInBytes);
1962   }
1964   if (DT.isProtected())
1965     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1966             dwarf::DW_ACCESS_protected);
1967   else if (DT.isPrivate())
1968     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1969             dwarf::DW_ACCESS_private);
1970   // Otherwise C++ member and base classes are considered public.
1971   else if (DT.isPublic())
1972     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1973             dwarf::DW_ACCESS_public);
1974   if (DT.isVirtual())
1975     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1976             dwarf::DW_VIRTUALITY_virtual);
1978   // Objective-C properties.
1979   if (MDNode *PNode = DT.getObjCProperty())
1980     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1981       MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1982                          PropertyDie);
1984   if (DT.isArtificial())
1985     addFlag(MemberDie, dwarf::DW_AT_artificial);
1988 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1989 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1990   if (!DT.Verify())
1991     return nullptr;
1993   // Construct the context before querying for the existence of the DIE in case
1994   // such construction creates the DIE.
1995   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1996   assert(dwarf::isType(ContextDIE->getTag()) &&
1997          "Static member should belong to a type.");
1999   if (DIE *StaticMemberDIE = getDIE(DT))
2000     return StaticMemberDIE;
2002   DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
2004   DIType Ty = resolve(DT.getTypeDerivedFrom());
2006   addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
2007   addType(StaticMemberDIE, Ty);
2008   addSourceLine(StaticMemberDIE, DT);
2009   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2010   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2012   // FIXME: We could omit private if the parent is a class_type, and
2013   // public if the parent is something else.
2014   if (DT.isProtected())
2015     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2016             dwarf::DW_ACCESS_protected);
2017   else if (DT.isPrivate())
2018     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2019             dwarf::DW_ACCESS_private);
2020   else if (DT.isPublic())
2021     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2022             dwarf::DW_ACCESS_public);
2024   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2025     addConstantValue(StaticMemberDIE, CI, Ty);
2026   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2027     addConstantFPValue(StaticMemberDIE, CFP);
2029   return &StaticMemberDIE;
2032 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2033   Asm->OutStreamer.AddComment("DWARF version number");
2034   Asm->EmitInt16(DD->getDwarfVersion());
2035   Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2036   // We share one abbreviations table across all units so it's always at the
2037   // start of the section. Use a relocatable offset where needed to ensure
2038   // linking doesn't invalidate that offset.
2039   if (ASectionSym)
2040     Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2041   else
2042     // Use a constant value when no symbol is provided.
2043     Asm->EmitInt32(0);
2044   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2045   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2048 void DwarfCompileUnit::addRange(RangeSpan Range) {
2049   bool SameAsPrevCU = this == DD->getPrevCU();
2050   DD->setPrevCU(this);
2051   // If we have no current ranges just add the range and return, otherwise,
2052   // check the current section and CU against the previous section and CU we
2053   // emitted into and the subprogram was contained within. If these are the
2054   // same then extend our current range, otherwise add this as a new range.
2055   if (CURanges.empty() || !SameAsPrevCU ||
2056       (&CURanges.back().getEnd()->getSection() !=
2057        &Range.getEnd()->getSection())) {
2058     CURanges.push_back(Range);
2059     return;
2060   }
2062   CURanges.back().setEnd(Range.getEnd());
2065 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2066   // Define start line table label for each Compile Unit.
2067   MCSymbol *LineTableStartSym =
2068       Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2070   stmtListIndex = UnitDie.getValues().size();
2072   // DW_AT_stmt_list is a offset of line number information for this
2073   // compile unit in debug_line section. For split dwarf this is
2074   // left in the skeleton CU and so not included.
2075   // The line table entries are not always emitted in assembly, so it
2076   // is not okay to use line_table_start here.
2077   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2078     addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym);
2079   else
2080     addSectionDelta(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
2081                     DwarfLineSectionSym);
2084 void DwarfCompileUnit::applyStmtList(DIE &D) {
2085   D.addValue(dwarf::DW_AT_stmt_list,
2086              UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
2087              UnitDie.getValues()[stmtListIndex]);
2090 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2091   DwarfUnit::emitHeader(ASectionSym);
2092   Asm->OutStreamer.AddComment("Type Signature");
2093   Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2094   Asm->OutStreamer.AddComment("Type DIE Offset");
2095   // In a skeleton type unit there is no type DIE so emit a zero offset.
2096   Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2097                                 sizeof(Ty->getOffset()));
2100 void DwarfTypeUnit::initSection(const MCSection *Section) {
2101   assert(!this->Section);
2102   this->Section = Section;
2103   // Since each type unit is contained in its own COMDAT section, the begin
2104   // label and the section label are the same. Using the begin label emission in
2105   // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2106   // the only other alternative of lazily constructing start-of-section labels
2107   // and storing a mapping in DwarfDebug (or AsmPrinter).
2108   this->SectionSym = this->LabelBegin =
2109       Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2110   this->LabelEnd =
2111       Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());