1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for constructing a dwarf compile unit.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "DwarfUnit.h"
15 #include "AddressPool.h"
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "DwarfExpression.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/MC/MachineLocation.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
38 #include <cassert>
39 #include <cstdint>
40 #include <string>
41 #include <utility>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "dwarfdebug"
46 
47 static cl::opt<bool>
48 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
49                        cl::desc("Generate DWARF4 type units."),
50                        cl::init(false));
51 
52 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
53                                        DIELoc &DIE)
54     : DwarfExpression(AP.getDwarfDebug()->getDwarfVersion()), AP(AP), DU(DU),
55       DIE(DIE) {}
56 
57 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
58   DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
59 }
60 
61 void DIEDwarfExpression::EmitSigned(int64_t Value) {
62   DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
63 }
64 
65 void DIEDwarfExpression::EmitUnsigned(uint64_t Value) {
66   DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
67 }
68 
69 bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
70                                          unsigned MachineReg) {
71   return MachineReg == TRI.getFrameRegister(*AP.MF);
72 }
73 
74 DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
75                      AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
76     : CUNode(Node), UnitDie(*DIE::get(DIEValueAllocator, UnitTag)), Asm(A),
77       DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
78   assert(UnitTag == dwarf::DW_TAG_compile_unit ||
79          UnitTag == dwarf::DW_TAG_type_unit);
80 }
81 
82 DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
83                              DwarfDebug *DW, DwarfFile *DWU,
84                              MCDwarfDwoLineTable *SplitLineTable)
85     : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
86       SplitLineTable(SplitLineTable) {
87   if (SplitLineTable)
88     addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
89 }
90 
91 DwarfUnit::~DwarfUnit() {
92   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
93     DIEBlocks[j]->~DIEBlock();
94   for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
95     DIELocs[j]->~DIELoc();
96 }
97 
98 int64_t DwarfUnit::getDefaultLowerBound() const {
99   switch (getLanguage()) {
100   default:
101     break;
102 
103   case dwarf::DW_LANG_C89:
104   case dwarf::DW_LANG_C99:
105   case dwarf::DW_LANG_C:
106   case dwarf::DW_LANG_C_plus_plus:
107   case dwarf::DW_LANG_ObjC:
108   case dwarf::DW_LANG_ObjC_plus_plus:
109     return 0;
110 
111   case dwarf::DW_LANG_Fortran77:
112   case dwarf::DW_LANG_Fortran90:
113   case dwarf::DW_LANG_Fortran95:
114     return 1;
115 
116   // The languages below have valid values only if the DWARF version >= 4.
117   case dwarf::DW_LANG_Java:
118   case dwarf::DW_LANG_Python:
119   case dwarf::DW_LANG_UPC:
120   case dwarf::DW_LANG_D:
121     if (dwarf::DWARF_VERSION >= 4)
122       return 0;
123     break;
124 
125   case dwarf::DW_LANG_Ada83:
126   case dwarf::DW_LANG_Ada95:
127   case dwarf::DW_LANG_Cobol74:
128   case dwarf::DW_LANG_Cobol85:
129   case dwarf::DW_LANG_Modula2:
130   case dwarf::DW_LANG_Pascal83:
131   case dwarf::DW_LANG_PLI:
132     if (dwarf::DWARF_VERSION >= 4)
133       return 1;
134     break;
135 
136   // The languages below have valid values only if the DWARF version >= 5.
137   case dwarf::DW_LANG_OpenCL:
138   case dwarf::DW_LANG_Go:
139   case dwarf::DW_LANG_Haskell:
140   case dwarf::DW_LANG_C_plus_plus_03:
141   case dwarf::DW_LANG_C_plus_plus_11:
142   case dwarf::DW_LANG_OCaml:
143   case dwarf::DW_LANG_Rust:
144   case dwarf::DW_LANG_C11:
145   case dwarf::DW_LANG_Swift:
146   case dwarf::DW_LANG_Dylan:
147   case dwarf::DW_LANG_C_plus_plus_14:
148     if (dwarf::DWARF_VERSION >= 5)
149       return 0;
150     break;
151 
152   case dwarf::DW_LANG_Modula3:
153   case dwarf::DW_LANG_Julia:
154   case dwarf::DW_LANG_Fortran03:
155   case dwarf::DW_LANG_Fortran08:
156     if (dwarf::DWARF_VERSION >= 5)
157       return 1;
158     break;
159   }
160 
161   return -1;
162 }
163 
164 /// Check whether the DIE for this MDNode can be shared across CUs.
165 static bool isShareableAcrossCUs(const DINode *D) {
166   // When the MDNode can be part of the type system, the DIE can be shared
167   // across CUs.
168   // Combining type units and cross-CU DIE sharing is lower value (since
169   // cross-CU DIE sharing is used in LTO and removes type redundancy at that
170   // level already) but may be implementable for some value in projects
171   // building multiple independent libraries with LTO and then linking those
172   // together.
173   return (isa<DIType>(D) ||
174           (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
175          !GenerateDwarfTypeUnits;
176 }
177 
178 DIE *DwarfUnit::getDIE(const DINode *D) const {
179   if (isShareableAcrossCUs(D))
180     return DU->getDIE(D);
181   return MDNodeToDieMap.lookup(D);
182 }
183 
184 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
185   if (isShareableAcrossCUs(Desc)) {
186     DU->insertDIE(Desc, D);
187     return;
188   }
189   MDNodeToDieMap.insert(std::make_pair(Desc, D));
190 }
191 
192 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
193   if (DD->getDwarfVersion() >= 4)
194     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
195                  DIEInteger(1));
196   else
197     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
198                  DIEInteger(1));
199 }
200 
201 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
202                         Optional<dwarf::Form> Form, uint64_t Integer) {
203   if (!Form)
204     Form = DIEInteger::BestForm(false, Integer);
205   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
206 }
207 
208 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
209                         uint64_t Integer) {
210   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
211 }
212 
213 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
214                         Optional<dwarf::Form> Form, int64_t Integer) {
215   if (!Form)
216     Form = DIEInteger::BestForm(true, Integer);
217   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
218 }
219 
220 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
221                         int64_t Integer) {
222   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
223 }
224 
225 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
226                           StringRef String) {
227   Die.addValue(DIEValueAllocator, Attribute,
228                isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
229                DIEString(DU->getStringPool().getEntry(*Asm, String)));
230 }
231 
232 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
233                                                  dwarf::Attribute Attribute,
234                                                  dwarf::Form Form,
235                                                  const MCSymbol *Label) {
236   return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
237 }
238 
239 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
240   addLabel(Die, (dwarf::Attribute)0, Form, Label);
241 }
242 
243 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
244                                  uint64_t Integer) {
245   if (DD->getDwarfVersion() >= 4)
246     addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
247   else
248     addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
249 }
250 
251 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
252   return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
253                         : getCU().getOrCreateSourceID(FileName, DirName);
254 }
255 
256 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
257   if (!DD->useSplitDwarf()) {
258     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
259     addLabel(Die, dwarf::DW_FORM_udata, Sym);
260   } else {
261     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
262     addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
263             DD->getAddressPool().getIndex(Sym));
264   }
265 }
266 
267 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
268                               const MCSymbol *Hi, const MCSymbol *Lo) {
269   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
270                new (DIEValueAllocator) DIEDelta(Hi, Lo));
271 }
272 
273 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
274   addDIEEntry(Die, Attribute, DIEEntry(Entry));
275 }
276 
277 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
278   // Flag the type unit reference as a declaration so that if it contains
279   // members (implicit special members, static data member definitions, member
280   // declarations for definitions in this CU, etc) consumers don't get confused
281   // and think this is a full definition.
282   addFlag(Die, dwarf::DW_AT_declaration);
283 
284   Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
285                dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
286 }
287 
288 void DwarfUnit::addDIETypeSignature(DIE &Die, dwarf::Attribute Attribute,
289                                     StringRef Identifier) {
290   uint64_t Signature = DD->makeTypeSignature(Identifier);
291   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_ref_sig8,
292                DIEInteger(Signature));
293 }
294 
295 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
296                             DIEEntry Entry) {
297   const DIE *DieCU = Die.getUnitOrNull();
298   const DIE *EntryCU = Entry.getEntry().getUnitOrNull();
299   if (!DieCU)
300     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
301     DieCU = &getUnitDie();
302   if (!EntryCU)
303     EntryCU = &getUnitDie();
304   Die.addValue(DIEValueAllocator, Attribute,
305                EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
306                Entry);
307 }
308 
309 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
310   DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
311   if (N)
312     insertDIE(N, &Die);
313   return Die;
314 }
315 
316 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
317   Loc->ComputeSize(Asm);
318   DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
319   Die.addValue(DIEValueAllocator, Attribute,
320                Loc->BestForm(DD->getDwarfVersion()), Loc);
321 }
322 
323 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
324                          DIEBlock *Block) {
325   Block->ComputeSize(Asm);
326   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
327   Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
328 }
329 
330 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
331                               StringRef Directory) {
332   if (Line == 0)
333     return;
334 
335   unsigned FileID = getOrCreateSourceID(File, Directory);
336   assert(FileID && "Invalid file id");
337   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
338   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
339 }
340 
341 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
342   assert(V);
343 
344   addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
345                 V->getScope()->getDirectory());
346 }
347 
348 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
349   assert(G);
350 
351   addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
352 }
353 
354 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
355   assert(SP);
356 
357   addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
358 }
359 
360 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
361   assert(Ty);
362 
363   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
364 }
365 
366 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
367   assert(Ty);
368 
369   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
370 }
371 
372 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
373   addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
374 }
375 
376 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
377                                    unsigned SizeInBits, unsigned OffsetInBits) {
378   DIEDwarfExpression Expr(*Asm, *this, TheDie);
379   Expr.AddMachineRegPiece(*Asm->MF->getSubtarget().getRegisterInfo(), Reg,
380                           SizeInBits, OffsetInBits);
381   return true;
382 }
383 
384 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
385                                   int64_t Offset) {
386   DIEDwarfExpression Expr(*Asm, *this, TheDie);
387   return Expr.AddMachineRegIndirect(*Asm->MF->getSubtarget().getRegisterInfo(),
388                                     Reg, Offset);
389 }
390 
391 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
392    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
393    gives the variable VarName either the struct, or a pointer to the struct, as
394    its type.  This is necessary for various behind-the-scenes things the
395    compiler needs to do with by-reference variables in Blocks.
396 
397    However, as far as the original *programmer* is concerned, the variable
398    should still have type 'SomeType', as originally declared.
399 
400    The function getBlockByrefType dives into the __Block_byref_x_VarName
401    struct to find the original type of the variable, which is then assigned to
402    the variable's Debug Information Entry as its real type.  So far, so good.
403    However now the debugger will expect the variable VarName to have the type
404    SomeType.  So we need the location attribute for the variable to be an
405    expression that explains to the debugger how to navigate through the
406    pointers and struct to find the actual variable of type SomeType.
407 
408    The following function does just that.  We start by getting
409    the "normal" location for the variable. This will be the location
410    of either the struct __Block_byref_x_VarName or the pointer to the
411    struct __Block_byref_x_VarName.
412 
413    The struct will look something like:
414 
415    struct __Block_byref_x_VarName {
416      ... <various fields>
417      struct __Block_byref_x_VarName *forwarding;
418      ... <various other fields>
419      SomeType VarName;
420      ... <maybe more fields>
421    };
422 
423    If we are given the struct directly (as our starting point) we
424    need to tell the debugger to:
425 
426    1).  Add the offset of the forwarding field.
427 
428    2).  Follow that pointer to get the real __Block_byref_x_VarName
429    struct to use (the real one may have been copied onto the heap).
430 
431    3).  Add the offset for the field VarName, to find the actual variable.
432 
433    If we started with a pointer to the struct, then we need to
434    dereference that pointer first, before the other steps.
435    Translating this into DWARF ops, we will need to append the following
436    to the current location description for the variable:
437 
438    DW_OP_deref                    -- optional, if we start with a pointer
439    DW_OP_plus_uconst <forward_fld_offset>
440    DW_OP_deref
441    DW_OP_plus_uconst <varName_fld_offset>
442 
443    That is what this function does.  */
444 
445 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
446                                      dwarf::Attribute Attribute,
447                                      const MachineLocation &Location) {
448   const DIType *Ty = DV.getType();
449   const DIType *TmpTy = Ty;
450   uint16_t Tag = Ty->getTag();
451   bool isPointer = false;
452 
453   StringRef varName = DV.getName();
454 
455   if (Tag == dwarf::DW_TAG_pointer_type) {
456     auto *DTy = cast<DIDerivedType>(Ty);
457     TmpTy = resolve(DTy->getBaseType());
458     isPointer = true;
459   }
460 
461   // Find the __forwarding field and the variable field in the __Block_byref
462   // struct.
463   DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements();
464   const DIDerivedType *varField = nullptr;
465   const DIDerivedType *forwardingField = nullptr;
466 
467   for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
468     auto *DT = cast<DIDerivedType>(Fields[i]);
469     StringRef fieldName = DT->getName();
470     if (fieldName == "__forwarding")
471       forwardingField = DT;
472     else if (fieldName == varName)
473       varField = DT;
474   }
475 
476   // Get the offsets for the forwarding field and the variable field.
477   unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
478   unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
479 
480   // Decode the original location, and use that as the start of the byref
481   // variable's location.
482   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
483 
484   bool validReg;
485   if (Location.isReg())
486     validReg = addRegisterOpPiece(*Loc, Location.getReg());
487   else
488     validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
489 
490   if (!validReg)
491     return;
492 
493   // If we started with a pointer to the __Block_byref... struct, then
494   // the first thing we need to do is dereference the pointer (DW_OP_deref).
495   if (isPointer)
496     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
497 
498   // Next add the offset for the '__forwarding' field:
499   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
500   // adding the offset if it's 0.
501   if (forwardingFieldOffset > 0) {
502     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
503     addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
504   }
505 
506   // Now dereference the __forwarding field to get to the real __Block_byref
507   // struct:  DW_OP_deref.
508   addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
509 
510   // Now that we've got the real __Block_byref... struct, add the offset
511   // for the variable's field to get to the location of the actual variable:
512   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
513   if (varFieldOffset > 0) {
514     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
515     addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
516   }
517 
518   // Now attach the location information to the DIE.
519   addBlock(Die, Attribute, Loc);
520 }
521 
522 /// Return true if type encoding is unsigned.
523 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
524   if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
525     // FIXME: Enums without a fixed underlying type have unknown signedness
526     // here, leading to incorrectly emitted constants.
527     if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
528       return false;
529 
530     // (Pieces of) aggregate types that get hacked apart by SROA may be
531     // represented by a constant. Encode them as unsigned bytes.
532     return true;
533   }
534 
535   if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
536     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
537     // Encode pointer constants as unsigned bytes. This is used at least for
538     // null pointer constant emission.
539     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
540     // here, but accept them for now due to a bug in SROA producing bogus
541     // dbg.values.
542     if (T == dwarf::DW_TAG_pointer_type ||
543         T == dwarf::DW_TAG_ptr_to_member_type ||
544         T == dwarf::DW_TAG_reference_type ||
545         T == dwarf::DW_TAG_rvalue_reference_type)
546       return true;
547     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
548            T == dwarf::DW_TAG_volatile_type ||
549            T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
550     DITypeRef Deriv = DTy->getBaseType();
551     assert(Deriv && "Expected valid base type");
552     return isUnsignedDIType(DD, DD->resolve(Deriv));
553   }
554 
555   auto *BTy = cast<DIBasicType>(Ty);
556   unsigned Encoding = BTy->getEncoding();
557   assert((Encoding == dwarf::DW_ATE_unsigned ||
558           Encoding == dwarf::DW_ATE_unsigned_char ||
559           Encoding == dwarf::DW_ATE_signed ||
560           Encoding == dwarf::DW_ATE_signed_char ||
561           Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
562           Encoding == dwarf::DW_ATE_boolean ||
563           (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
564            Ty->getName() == "decltype(nullptr)")) &&
565          "Unsupported encoding");
566   return Encoding == dwarf::DW_ATE_unsigned ||
567          Encoding == dwarf::DW_ATE_unsigned_char ||
568          Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
569          Ty->getTag() == dwarf::DW_TAG_unspecified_type;
570 }
571 
572 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
573   assert(MO.isFPImm() && "Invalid machine operand!");
574   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
575   APFloat FPImm = MO.getFPImm()->getValueAPF();
576 
577   // Get the raw data form of the floating point.
578   const APInt FltVal = FPImm.bitcastToAPInt();
579   const char *FltPtr = (const char *)FltVal.getRawData();
580 
581   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
582   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
583   int Incr = (LittleEndian ? 1 : -1);
584   int Start = (LittleEndian ? 0 : NumBytes - 1);
585   int Stop = (LittleEndian ? NumBytes : -1);
586 
587   // Output the constant to DWARF one byte at a time.
588   for (; Start != Stop; Start += Incr)
589     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
590 
591   addBlock(Die, dwarf::DW_AT_const_value, Block);
592 }
593 
594 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
595   // Pass this down to addConstantValue as an unsigned bag of bits.
596   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
597 }
598 
599 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
600                                  const DIType *Ty) {
601   addConstantValue(Die, CI->getValue(), Ty);
602 }
603 
604 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
605                                  const DIType *Ty) {
606   assert(MO.isImm() && "Invalid machine operand!");
607 
608   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
609 }
610 
611 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
612   // FIXME: This is a bit conservative/simple - it emits negative values always
613   // sign extended to 64 bits rather than minimizing the number of bytes.
614   addUInt(Die, dwarf::DW_AT_const_value,
615           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
616 }
617 
618 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
619   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
620 }
621 
622 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
623   unsigned CIBitWidth = Val.getBitWidth();
624   if (CIBitWidth <= 64) {
625     addConstantValue(Die, Unsigned,
626                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
627     return;
628   }
629 
630   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
631 
632   // Get the raw data form of the large APInt.
633   const uint64_t *Ptr64 = Val.getRawData();
634 
635   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
636   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
637 
638   // Output the constant to DWARF one byte at a time.
639   for (int i = 0; i < NumBytes; i++) {
640     uint8_t c;
641     if (LittleEndian)
642       c = Ptr64[i / 8] >> (8 * (i & 7));
643     else
644       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
645     addUInt(*Block, dwarf::DW_FORM_data1, c);
646   }
647 
648   addBlock(Die, dwarf::DW_AT_const_value, Block);
649 }
650 
651 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
652   if (!LinkageName.empty())
653     addString(Die,
654               DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
655                                          : dwarf::DW_AT_MIPS_linkage_name,
656               GlobalValue::getRealLinkageName(LinkageName));
657 }
658 
659 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
660   // Add template parameters.
661   for (const auto *Element : TParams) {
662     if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
663       constructTemplateTypeParameterDIE(Buffer, TTP);
664     else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
665       constructTemplateValueParameterDIE(Buffer, TVP);
666   }
667 }
668 
669 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
670   if (!Context || isa<DIFile>(Context))
671     return &getUnitDie();
672   if (auto *T = dyn_cast<DIType>(Context))
673     return getOrCreateTypeDIE(T);
674   if (auto *NS = dyn_cast<DINamespace>(Context))
675     return getOrCreateNameSpace(NS);
676   if (auto *SP = dyn_cast<DISubprogram>(Context))
677     return getOrCreateSubprogramDIE(SP);
678   if (auto *M = dyn_cast<DIModule>(Context))
679     return getOrCreateModule(M);
680   return getDIE(Context);
681 }
682 
683 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
684   auto *Context = resolve(Ty->getScope());
685   DIE *ContextDIE = getOrCreateContextDIE(Context);
686 
687   if (DIE *TyDIE = getDIE(Ty))
688     return TyDIE;
689 
690   // Create new type.
691   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
692 
693   constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
694 
695   if (!Ty->isExternalTypeRef())
696     updateAcceleratorTables(Context, Ty, TyDIE);
697   return &TyDIE;
698 }
699 
700 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
701   if (!TyNode)
702     return nullptr;
703 
704   auto *Ty = cast<DIType>(TyNode);
705 
706   // DW_TAG_restrict_type is not supported in DWARF2
707   if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
708     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
709 
710   // DW_TAG_atomic_type is not supported in DWARF < 5
711   if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
712     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
713 
714   // Construct the context before querying for the existence of the DIE in case
715   // such construction creates the DIE.
716   auto *Context = resolve(Ty->getScope());
717   DIE *ContextDIE = getOrCreateContextDIE(Context);
718   assert(ContextDIE);
719 
720   if (DIE *TyDIE = getDIE(Ty))
721     return TyDIE;
722 
723   // Create new type.
724   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
725 
726   updateAcceleratorTables(Context, Ty, TyDIE);
727 
728   if (auto *BT = dyn_cast<DIBasicType>(Ty))
729     constructTypeDIE(TyDIE, BT);
730   else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
731     constructTypeDIE(TyDIE, STy);
732   else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
733     if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
734       if (MDString *TypeId = CTy->getRawIdentifier()) {
735         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
736         // Skip updating the accelerator tables since this is not the full type.
737         return &TyDIE;
738       }
739     constructTypeDIE(TyDIE, CTy);
740   } else {
741     constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
742   }
743 
744   return &TyDIE;
745 }
746 
747 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
748                                         const DIType *Ty, const DIE &TyDIE) {
749   if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
750     bool IsImplementation = false;
751     if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
752       // A runtime language of 0 actually means C/C++ and that any
753       // non-negative value is some version of Objective-C/C++.
754       IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
755     }
756     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
757     DD->addAccelType(Ty->getName(), TyDIE, Flags);
758 
759     if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
760         isa<DINamespace>(Context))
761       addGlobalType(Ty, TyDIE, Context);
762   }
763 }
764 
765 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
766                         dwarf::Attribute Attribute) {
767   assert(Ty && "Trying to add a type that doesn't exist?");
768   addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
769 }
770 
771 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
772   if (!Context)
773     return "";
774 
775   // FIXME: Decide whether to implement this for non-C++ languages.
776   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
777     return "";
778 
779   std::string CS;
780   SmallVector<const DIScope *, 1> Parents;
781   while (!isa<DICompileUnit>(Context)) {
782     Parents.push_back(Context);
783     if (Context->getScope())
784       Context = resolve(Context->getScope());
785     else
786       // Structure, etc types will have a NULL context if they're at the top
787       // level.
788       break;
789   }
790 
791   // Reverse iterate over our list to go from the outermost construct to the
792   // innermost.
793   for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
794     StringRef Name = Ctx->getName();
795     if (Name.empty() && isa<DINamespace>(Ctx))
796       Name = "(anonymous namespace)";
797     if (!Name.empty()) {
798       CS += Name;
799       CS += "::";
800     }
801   }
802   return CS;
803 }
804 
805 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
806   // Get core information.
807   StringRef Name = BTy->getName();
808   // Add name if not anonymous or intermediate type.
809   if (!Name.empty())
810     addString(Buffer, dwarf::DW_AT_name, Name);
811 
812   // An unspecified type only has a name attribute.
813   if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
814     return;
815 
816   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
817           BTy->getEncoding());
818 
819   uint64_t Size = BTy->getSizeInBits() >> 3;
820   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
821 }
822 
823 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
824   // Get core information.
825   StringRef Name = DTy->getName();
826   uint64_t Size = DTy->getSizeInBits() >> 3;
827   uint16_t Tag = Buffer.getTag();
828 
829   // Map to main type, void will not have a type.
830   const DIType *FromTy = resolve(DTy->getBaseType());
831   if (FromTy)
832     addType(Buffer, FromTy);
833 
834   // Add name if not anonymous or intermediate type.
835   if (!Name.empty())
836     addString(Buffer, dwarf::DW_AT_name, Name);
837 
838   // Add size if non-zero (derived types might be zero-sized.)
839   if (Size && Tag != dwarf::DW_TAG_pointer_type
840            && Tag != dwarf::DW_TAG_ptr_to_member_type
841            && Tag != dwarf::DW_TAG_reference_type
842            && Tag != dwarf::DW_TAG_rvalue_reference_type)
843     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
844 
845   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
846     addDIEEntry(
847         Buffer, dwarf::DW_AT_containing_type,
848         *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
849   // Add source line info if available and TyDesc is not a forward declaration.
850   if (!DTy->isForwardDecl())
851     addSourceLine(Buffer, DTy);
852 }
853 
854 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
855   for (unsigned i = 1, N = Args.size(); i < N; ++i) {
856     const DIType *Ty = resolve(Args[i]);
857     if (!Ty) {
858       assert(i == N-1 && "Unspecified parameter must be the last argument");
859       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
860     } else {
861       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
862       addType(Arg, Ty);
863       if (Ty->isArtificial())
864         addFlag(Arg, dwarf::DW_AT_artificial);
865     }
866   }
867 }
868 
869 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
870   // Add return type.  A void return won't have a type.
871   auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
872   if (Elements.size())
873     if (auto RTy = resolve(Elements[0]))
874       addType(Buffer, RTy);
875 
876   bool isPrototyped = true;
877   if (Elements.size() == 2 && !Elements[1])
878     isPrototyped = false;
879 
880   constructSubprogramArguments(Buffer, Elements);
881 
882   // Add prototype flag if we're dealing with a C language and the function has
883   // been prototyped.
884   uint16_t Language = getLanguage();
885   if (isPrototyped &&
886       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
887        Language == dwarf::DW_LANG_ObjC))
888     addFlag(Buffer, dwarf::DW_AT_prototyped);
889 
890   // Add a DW_AT_calling_convention if this has an explicit convention.
891   if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
892     addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
893             CTy->getCC());
894 
895   if (CTy->isLValueReference())
896     addFlag(Buffer, dwarf::DW_AT_reference);
897 
898   if (CTy->isRValueReference())
899     addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
900 }
901 
902 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
903   if (CTy->isExternalTypeRef()) {
904     StringRef Identifier = CTy->getIdentifier();
905     assert(!Identifier.empty() && "external type ref without identifier");
906     addFlag(Buffer, dwarf::DW_AT_declaration);
907     return addDIETypeSignature(Buffer, dwarf::DW_AT_signature, Identifier);
908   }
909 
910   // Add name if not anonymous or intermediate type.
911   StringRef Name = CTy->getName();
912 
913   uint64_t Size = CTy->getSizeInBits() >> 3;
914   uint16_t Tag = Buffer.getTag();
915 
916   switch (Tag) {
917   case dwarf::DW_TAG_array_type:
918     constructArrayTypeDIE(Buffer, CTy);
919     break;
920   case dwarf::DW_TAG_enumeration_type:
921     constructEnumTypeDIE(Buffer, CTy);
922     break;
923   case dwarf::DW_TAG_structure_type:
924   case dwarf::DW_TAG_union_type:
925   case dwarf::DW_TAG_class_type: {
926     // Add elements to structure type.
927     DINodeArray Elements = CTy->getElements();
928     for (const auto *Element : Elements) {
929       if (!Element)
930         continue;
931       if (auto *SP = dyn_cast<DISubprogram>(Element))
932         getOrCreateSubprogramDIE(SP);
933       else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
934         if (DDTy->getTag() == dwarf::DW_TAG_friend) {
935           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
936           addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
937         } else if (DDTy->isStaticMember()) {
938           getOrCreateStaticMemberDIE(DDTy);
939         } else {
940           constructMemberDIE(Buffer, DDTy);
941         }
942       } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
943         DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
944         StringRef PropertyName = Property->getName();
945         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
946         if (Property->getType())
947           addType(ElemDie, resolve(Property->getType()));
948         addSourceLine(ElemDie, Property);
949         StringRef GetterName = Property->getGetterName();
950         if (!GetterName.empty())
951           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
952         StringRef SetterName = Property->getSetterName();
953         if (!SetterName.empty())
954           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
955         if (unsigned PropertyAttributes = Property->getAttributes())
956           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
957                   PropertyAttributes);
958       }
959     }
960 
961     if (CTy->isAppleBlockExtension())
962       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
963 
964     // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
965     // inside C++ composite types to point to the base class with the vtable.
966     if (auto *ContainingType =
967             dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
968       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
969                   *getOrCreateTypeDIE(ContainingType));
970 
971     if (CTy->isObjcClassComplete())
972       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
973 
974     // Add template parameters to a class, structure or union types.
975     // FIXME: The support isn't in the metadata for this yet.
976     if (Tag == dwarf::DW_TAG_class_type ||
977         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
978       addTemplateParams(Buffer, CTy->getTemplateParams());
979 
980     break;
981   }
982   default:
983     break;
984   }
985 
986   // Add name if not anonymous or intermediate type.
987   if (!Name.empty())
988     addString(Buffer, dwarf::DW_AT_name, Name);
989 
990   if (Tag == dwarf::DW_TAG_enumeration_type ||
991       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
992       Tag == dwarf::DW_TAG_union_type) {
993     // Add size if non-zero (derived types might be zero-sized.)
994     // TODO: Do we care about size for enum forward declarations?
995     if (Size)
996       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
997     else if (!CTy->isForwardDecl())
998       // Add zero size if it is not a forward declaration.
999       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1000 
1001     // If we're a forward decl, say so.
1002     if (CTy->isForwardDecl())
1003       addFlag(Buffer, dwarf::DW_AT_declaration);
1004 
1005     // Add source line info if available.
1006     if (!CTy->isForwardDecl())
1007       addSourceLine(Buffer, CTy);
1008 
1009     // No harm in adding the runtime language to the declaration.
1010     unsigned RLang = CTy->getRuntimeLang();
1011     if (RLang)
1012       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1013               RLang);
1014 
1015     // Add align info if available.
1016     if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1017       addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1018               AlignInBytes);
1019   }
1020 }
1021 
1022 void DwarfUnit::constructTemplateTypeParameterDIE(
1023     DIE &Buffer, const DITemplateTypeParameter *TP) {
1024   DIE &ParamDIE =
1025       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1026   // Add the type if it exists, it could be void and therefore no type.
1027   if (TP->getType())
1028     addType(ParamDIE, resolve(TP->getType()));
1029   if (!TP->getName().empty())
1030     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1031 }
1032 
1033 void DwarfUnit::constructTemplateValueParameterDIE(
1034     DIE &Buffer, const DITemplateValueParameter *VP) {
1035   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1036 
1037   // Add the type if there is one, template template and template parameter
1038   // packs will not have a type.
1039   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1040     addType(ParamDIE, resolve(VP->getType()));
1041   if (!VP->getName().empty())
1042     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1043   if (Metadata *Val = VP->getValue()) {
1044     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1045       addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1046     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1047       // We cannot describe the location of dllimport'd entities: the
1048       // computation of their address requires loads from the IAT.
1049       if (!GV->hasDLLImportStorageClass()) {
1050         // For declaration non-type template parameters (such as global values
1051         // and functions)
1052         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1053         addOpAddress(*Loc, Asm->getSymbol(GV));
1054         // Emit DW_OP_stack_value to use the address as the immediate value of
1055         // the parameter, rather than a pointer to it.
1056         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1057         addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1058       }
1059     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1060       assert(isa<MDString>(Val));
1061       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1062                 cast<MDString>(Val)->getString());
1063     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1064       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1065     }
1066   }
1067 }
1068 
1069 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1070   // Construct the context before querying for the existence of the DIE in case
1071   // such construction creates the DIE.
1072   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1073 
1074   if (DIE *NDie = getDIE(NS))
1075     return NDie;
1076   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1077 
1078   StringRef Name = NS->getName();
1079   if (!Name.empty())
1080     addString(NDie, dwarf::DW_AT_name, NS->getName());
1081   else
1082     Name = "(anonymous namespace)";
1083   DD->addAccelNamespace(Name, NDie);
1084   addGlobalName(Name, NDie, NS->getScope());
1085   addSourceLine(NDie, NS);
1086   if (NS->getExportSymbols())
1087     addFlag(NDie, dwarf::DW_AT_export_symbols);
1088   return &NDie;
1089 }
1090 
1091 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1092   // Construct the context before querying for the existence of the DIE in case
1093   // such construction creates the DIE.
1094   DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1095 
1096   if (DIE *MDie = getDIE(M))
1097     return MDie;
1098   DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1099 
1100   if (!M->getName().empty()) {
1101     addString(MDie, dwarf::DW_AT_name, M->getName());
1102     addGlobalName(M->getName(), MDie, M->getScope());
1103   }
1104   if (!M->getConfigurationMacros().empty())
1105     addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1106               M->getConfigurationMacros());
1107   if (!M->getIncludePath().empty())
1108     addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1109   if (!M->getISysRoot().empty())
1110     addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1111 
1112   return &MDie;
1113 }
1114 
1115 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1116   // Construct the context before querying for the existence of the DIE in case
1117   // such construction creates the DIE (as is the case for member function
1118   // declarations).
1119   DIE *ContextDIE =
1120       Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1121 
1122   if (DIE *SPDie = getDIE(SP))
1123     return SPDie;
1124 
1125   if (auto *SPDecl = SP->getDeclaration()) {
1126     if (!Minimal) {
1127       // Add subprogram definitions to the CU die directly.
1128       ContextDIE = &getUnitDie();
1129       // Build the decl now to ensure it precedes the definition.
1130       getOrCreateSubprogramDIE(SPDecl);
1131     }
1132   }
1133 
1134   // DW_TAG_inlined_subroutine may refer to this DIE.
1135   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1136 
1137   // Stop here and fill this in later, depending on whether or not this
1138   // subprogram turns out to have inlined instances or not.
1139   if (SP->isDefinition())
1140     return &SPDie;
1141 
1142   applySubprogramAttributes(SP, SPDie);
1143   return &SPDie;
1144 }
1145 
1146 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1147                                                     DIE &SPDie) {
1148   DIE *DeclDie = nullptr;
1149   StringRef DeclLinkageName;
1150   if (auto *SPDecl = SP->getDeclaration()) {
1151     DeclDie = getDIE(SPDecl);
1152     assert(DeclDie && "This DIE should've already been constructed when the "
1153                       "definition DIE was created in "
1154                       "getOrCreateSubprogramDIE");
1155     DeclLinkageName = SPDecl->getLinkageName();
1156     unsigned DeclID =
1157         getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1158     unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1159     if (DeclID != DefID)
1160       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1161 
1162     if (SP->getLine() != SPDecl->getLine())
1163       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1164   }
1165 
1166   // Add function template parameters.
1167   addTemplateParams(SPDie, SP->getTemplateParams());
1168 
1169   // Add the linkage name if we have one and it isn't in the Decl.
1170   StringRef LinkageName = SP->getLinkageName();
1171   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1172           LinkageName == DeclLinkageName) &&
1173          "decl has a linkage name and it is different");
1174   if (DeclLinkageName.empty() &&
1175       // Always emit it for abstract subprograms.
1176       (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1177     addLinkageName(SPDie, LinkageName);
1178 
1179   if (!DeclDie)
1180     return false;
1181 
1182   // Refer to the function declaration where all the other attributes will be
1183   // found.
1184   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1185   return true;
1186 }
1187 
1188 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1189                                           bool Minimal) {
1190   if (!Minimal)
1191     if (applySubprogramDefinitionAttributes(SP, SPDie))
1192       return;
1193 
1194   // Constructors and operators for anonymous aggregates do not have names.
1195   if (!SP->getName().empty())
1196     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1197 
1198   // Skip the rest of the attributes under -gmlt to save space.
1199   if (Minimal)
1200     return;
1201 
1202   addSourceLine(SPDie, SP);
1203 
1204   // Add the prototype if we have a prototype and we have a C like
1205   // language.
1206   uint16_t Language = getLanguage();
1207   if (SP->isPrototyped() &&
1208       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1209        Language == dwarf::DW_LANG_ObjC))
1210     addFlag(SPDie, dwarf::DW_AT_prototyped);
1211 
1212   unsigned CC = 0;
1213   DITypeRefArray Args;
1214   if (const DISubroutineType *SPTy = SP->getType()) {
1215     Args = SPTy->getTypeArray();
1216     CC = SPTy->getCC();
1217   }
1218 
1219   // Add a DW_AT_calling_convention if this has an explicit convention.
1220   if (CC && CC != dwarf::DW_CC_normal)
1221     addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1222 
1223   // Add a return type. If this is a type like a C/C++ void type we don't add a
1224   // return type.
1225   if (Args.size())
1226     if (auto Ty = resolve(Args[0]))
1227       addType(SPDie, Ty);
1228 
1229   unsigned VK = SP->getVirtuality();
1230   if (VK) {
1231     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1232     if (SP->getVirtualIndex() != -1u) {
1233       DIELoc *Block = getDIELoc();
1234       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1235       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1236       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1237     }
1238     ContainingTypeMap.insert(
1239         std::make_pair(&SPDie, resolve(SP->getContainingType())));
1240   }
1241 
1242   if (!SP->isDefinition()) {
1243     addFlag(SPDie, dwarf::DW_AT_declaration);
1244 
1245     // Add arguments. Do not add arguments for subprogram definition. They will
1246     // be handled while processing variables.
1247     constructSubprogramArguments(SPDie, Args);
1248   }
1249 
1250   if (SP->isArtificial())
1251     addFlag(SPDie, dwarf::DW_AT_artificial);
1252 
1253   if (!SP->isLocalToUnit())
1254     addFlag(SPDie, dwarf::DW_AT_external);
1255 
1256   if (DD->useAppleExtensionAttributes()) {
1257     if (SP->isOptimized())
1258       addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1259 
1260     if (unsigned isa = Asm->getISAEncoding())
1261       addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1262   }
1263 
1264   if (SP->isLValueReference())
1265     addFlag(SPDie, dwarf::DW_AT_reference);
1266 
1267   if (SP->isRValueReference())
1268     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1269 
1270   if (SP->isNoReturn())
1271     addFlag(SPDie, dwarf::DW_AT_noreturn);
1272 
1273   if (SP->isProtected())
1274     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1275             dwarf::DW_ACCESS_protected);
1276   else if (SP->isPrivate())
1277     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1278             dwarf::DW_ACCESS_private);
1279   else if (SP->isPublic())
1280     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1281             dwarf::DW_ACCESS_public);
1282 
1283   if (SP->isExplicit())
1284     addFlag(SPDie, dwarf::DW_AT_explicit);
1285 }
1286 
1287 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1288                                      DIE *IndexTy) {
1289   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1290   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1291 
1292   // The LowerBound value defines the lower bounds which is typically zero for
1293   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1294   // Count == -1 then the array is unbounded and we do not emit
1295   // DW_AT_lower_bound and DW_AT_count attributes.
1296   int64_t LowerBound = SR->getLowerBound();
1297   int64_t DefaultLowerBound = getDefaultLowerBound();
1298   int64_t Count = SR->getCount();
1299 
1300   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1301     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1302 
1303   if (Count != -1)
1304     // FIXME: An unbounded array should reference the expression that defines
1305     // the array.
1306     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1307 }
1308 
1309 DIE *DwarfUnit::getIndexTyDie() {
1310   if (IndexTyDie)
1311     return IndexTyDie;
1312   // Construct an integer type to use for indexes.
1313   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1314   addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1315   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1316   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1317           dwarf::DW_ATE_unsigned);
1318   return IndexTyDie;
1319 }
1320 
1321 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1322   if (CTy->isVector())
1323     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1324 
1325   // Emit the element type.
1326   addType(Buffer, resolve(CTy->getBaseType()));
1327 
1328   // Get an anonymous type for index type.
1329   // FIXME: This type should be passed down from the front end
1330   // as different languages may have different sizes for indexes.
1331   DIE *IdxTy = getIndexTyDie();
1332 
1333   // Add subranges to array type.
1334   DINodeArray Elements = CTy->getElements();
1335   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1336     // FIXME: Should this really be such a loose cast?
1337     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1338       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1339         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1340   }
1341 }
1342 
1343 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1344   DINodeArray Elements = CTy->getElements();
1345 
1346   // Add enumerators to enumeration type.
1347   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1348     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1349     if (Enum) {
1350       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1351       StringRef Name = Enum->getName();
1352       addString(Enumerator, dwarf::DW_AT_name, Name);
1353       int64_t Value = Enum->getValue();
1354       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1355               Value);
1356     }
1357   }
1358   const DIType *DTy = resolve(CTy->getBaseType());
1359   if (DTy) {
1360     addType(Buffer, DTy);
1361     addFlag(Buffer, dwarf::DW_AT_enum_class);
1362   }
1363 }
1364 
1365 void DwarfUnit::constructContainingTypeDIEs() {
1366   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1367        CI != CE; ++CI) {
1368     DIE &SPDie = *CI->first;
1369     const DINode *D = CI->second;
1370     if (!D)
1371       continue;
1372     DIE *NDie = getDIE(D);
1373     if (!NDie)
1374       continue;
1375     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1376   }
1377 }
1378 
1379 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1380   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1381   StringRef Name = DT->getName();
1382   if (!Name.empty())
1383     addString(MemberDie, dwarf::DW_AT_name, Name);
1384 
1385   addType(MemberDie, resolve(DT->getBaseType()));
1386 
1387   addSourceLine(MemberDie, DT);
1388 
1389   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1390 
1391     // For C++, virtual base classes are not at fixed offset. Use following
1392     // expression to extract appropriate offset from vtable.
1393     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1394 
1395     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1396     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1397     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1398     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1399     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1400     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1401     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1402     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1403 
1404     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1405   } else {
1406     uint64_t Size = DT->getSizeInBits();
1407     uint64_t FieldSize = DD->getBaseTypeSize(DT);
1408     uint32_t AlignInBytes = DT->getAlignInBytes();
1409     uint64_t OffsetInBytes;
1410 
1411     bool IsBitfield = FieldSize && Size != FieldSize;
1412     if (IsBitfield) {
1413       // Handle bitfield, assume bytes are 8 bits.
1414       if (DD->useDWARF2Bitfields())
1415         addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1416       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1417 
1418       uint64_t Offset = DT->getOffsetInBits();
1419       // We can't use DT->getAlignInBits() here: AlignInBits for member type
1420       // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1421       // which can't be done with bitfields. Thus we use FieldSize here.
1422       uint32_t AlignInBits = FieldSize;
1423       uint32_t AlignMask = ~(AlignInBits - 1);
1424       // The bits from the start of the storage unit to the start of the field.
1425       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1426       // The byte offset of the field's aligned storage unit inside the struct.
1427       OffsetInBytes = (Offset - StartBitOffset) / 8;
1428 
1429       if (DD->useDWARF2Bitfields()) {
1430         uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1431         uint64_t FieldOffset = (HiMark - FieldSize);
1432         Offset -= FieldOffset;
1433 
1434         // Maybe we need to work from the other end.
1435         if (Asm->getDataLayout().isLittleEndian())
1436           Offset = FieldSize - (Offset + Size);
1437 
1438         addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1439         OffsetInBytes = FieldOffset >> 3;
1440       } else {
1441         addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1442       }
1443     } else {
1444       // This is not a bitfield.
1445       OffsetInBytes = DT->getOffsetInBits() / 8;
1446       if (AlignInBytes)
1447         addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1448                 AlignInBytes);
1449     }
1450 
1451     if (DD->getDwarfVersion() <= 2) {
1452       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1453       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1454       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1455       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1456     } else if (!IsBitfield || DD->useDWARF2Bitfields())
1457       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1458               OffsetInBytes);
1459   }
1460 
1461   if (DT->isProtected())
1462     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1463             dwarf::DW_ACCESS_protected);
1464   else if (DT->isPrivate())
1465     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1466             dwarf::DW_ACCESS_private);
1467   // Otherwise C++ member and base classes are considered public.
1468   else if (DT->isPublic())
1469     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1470             dwarf::DW_ACCESS_public);
1471   if (DT->isVirtual())
1472     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1473             dwarf::DW_VIRTUALITY_virtual);
1474 
1475   // Objective-C properties.
1476   if (DINode *PNode = DT->getObjCProperty())
1477     if (DIE *PDie = getDIE(PNode))
1478       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1479                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1480 
1481   if (DT->isArtificial())
1482     addFlag(MemberDie, dwarf::DW_AT_artificial);
1483 }
1484 
1485 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1486   if (!DT)
1487     return nullptr;
1488 
1489   // Construct the context before querying for the existence of the DIE in case
1490   // such construction creates the DIE.
1491   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1492   assert(dwarf::isType(ContextDIE->getTag()) &&
1493          "Static member should belong to a type.");
1494 
1495   if (DIE *StaticMemberDIE = getDIE(DT))
1496     return StaticMemberDIE;
1497 
1498   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1499 
1500   const DIType *Ty = resolve(DT->getBaseType());
1501 
1502   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1503   addType(StaticMemberDIE, Ty);
1504   addSourceLine(StaticMemberDIE, DT);
1505   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1506   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1507 
1508   // FIXME: We could omit private if the parent is a class_type, and
1509   // public if the parent is something else.
1510   if (DT->isProtected())
1511     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1512             dwarf::DW_ACCESS_protected);
1513   else if (DT->isPrivate())
1514     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1515             dwarf::DW_ACCESS_private);
1516   else if (DT->isPublic())
1517     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1518             dwarf::DW_ACCESS_public);
1519 
1520   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1521     addConstantValue(StaticMemberDIE, CI, Ty);
1522   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1523     addConstantFPValue(StaticMemberDIE, CFP);
1524 
1525   if (uint32_t AlignInBytes = DT->getAlignInBytes())
1526     addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1527             AlignInBytes);
1528 
1529   return &StaticMemberDIE;
1530 }
1531 
1532 void DwarfUnit::emitHeader(bool UseOffsets) {
1533   // Emit size of content not including length itself
1534   Asm->OutStreamer->AddComment("Length of Unit");
1535   Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1536 
1537   Asm->OutStreamer->AddComment("DWARF version number");
1538   Asm->EmitInt16(DD->getDwarfVersion());
1539   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1540 
1541   // We share one abbreviations table across all units so it's always at the
1542   // start of the section. Use a relocatable offset where needed to ensure
1543   // linking doesn't invalidate that offset.
1544   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1545   if (UseOffsets)
1546     Asm->EmitInt32(0);
1547   else
1548     Asm->emitDwarfSymbolReference(
1549         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1550 
1551   Asm->OutStreamer->AddComment("Address Size (in bytes)");
1552   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1553 }
1554 
1555 void DwarfUnit::initSection(MCSection *Section) {
1556   assert(!this->Section);
1557   this->Section = Section;
1558 }
1559 
1560 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1561   DwarfUnit::emitHeader(UseOffsets);
1562   Asm->OutStreamer->AddComment("Type Signature");
1563   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1564   Asm->OutStreamer->AddComment("Type DIE Offset");
1565   // In a skeleton type unit there is no type DIE so emit a zero offset.
1566   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1567                                  sizeof(Ty->getOffset()));
1568 }
1569 
1570 bool DwarfTypeUnit::isDwoUnit() const {
1571   // Since there are no skeleton type units, all type units are dwo type units
1572   // when split DWARF is being used.
1573   return DD->useSplitDwarf();
1574 }
1575