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);
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   // Construct the context before querying for the existence of the DIE in case
711   // such construction creates the DIE.
712   auto *Context = resolve(Ty->getScope());
713   DIE *ContextDIE = getOrCreateContextDIE(Context);
714   assert(ContextDIE);
715 
716   if (DIE *TyDIE = getDIE(Ty))
717     return TyDIE;
718 
719   // Create new type.
720   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
721 
722   updateAcceleratorTables(Context, Ty, TyDIE);
723 
724   if (auto *BT = dyn_cast<DIBasicType>(Ty))
725     constructTypeDIE(TyDIE, BT);
726   else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
727     constructTypeDIE(TyDIE, STy);
728   else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
729     if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
730       if (MDString *TypeId = CTy->getRawIdentifier()) {
731         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
732         // Skip updating the accelerator tables since this is not the full type.
733         return &TyDIE;
734       }
735     constructTypeDIE(TyDIE, CTy);
736   } else {
737     constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
738   }
739 
740   return &TyDIE;
741 }
742 
743 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
744                                         const DIType *Ty, const DIE &TyDIE) {
745   if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
746     bool IsImplementation = false;
747     if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
748       // A runtime language of 0 actually means C/C++ and that any
749       // non-negative value is some version of Objective-C/C++.
750       IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
751     }
752     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
753     DD->addAccelType(Ty->getName(), TyDIE, Flags);
754 
755     if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
756         isa<DINamespace>(Context))
757       addGlobalType(Ty, TyDIE, Context);
758   }
759 }
760 
761 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
762                         dwarf::Attribute Attribute) {
763   assert(Ty && "Trying to add a type that doesn't exist?");
764   addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
765 }
766 
767 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
768   if (!Context)
769     return "";
770 
771   // FIXME: Decide whether to implement this for non-C++ languages.
772   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
773     return "";
774 
775   std::string CS;
776   SmallVector<const DIScope *, 1> Parents;
777   while (!isa<DICompileUnit>(Context)) {
778     Parents.push_back(Context);
779     if (Context->getScope())
780       Context = resolve(Context->getScope());
781     else
782       // Structure, etc types will have a NULL context if they're at the top
783       // level.
784       break;
785   }
786 
787   // Reverse iterate over our list to go from the outermost construct to the
788   // innermost.
789   for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
790     StringRef Name = Ctx->getName();
791     if (Name.empty() && isa<DINamespace>(Ctx))
792       Name = "(anonymous namespace)";
793     if (!Name.empty()) {
794       CS += Name;
795       CS += "::";
796     }
797   }
798   return CS;
799 }
800 
801 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
802   // Get core information.
803   StringRef Name = BTy->getName();
804   // Add name if not anonymous or intermediate type.
805   if (!Name.empty())
806     addString(Buffer, dwarf::DW_AT_name, Name);
807 
808   // An unspecified type only has a name attribute.
809   if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
810     return;
811 
812   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
813           BTy->getEncoding());
814 
815   uint64_t Size = BTy->getSizeInBits() >> 3;
816   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
817 }
818 
819 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
820   // Get core information.
821   StringRef Name = DTy->getName();
822   uint64_t Size = DTy->getSizeInBits() >> 3;
823   uint16_t Tag = Buffer.getTag();
824 
825   // Map to main type, void will not have a type.
826   const DIType *FromTy = resolve(DTy->getBaseType());
827   if (FromTy)
828     addType(Buffer, FromTy);
829 
830   // Add name if not anonymous or intermediate type.
831   if (!Name.empty())
832     addString(Buffer, dwarf::DW_AT_name, Name);
833 
834   // Add size if non-zero (derived types might be zero-sized.)
835   if (Size && Tag != dwarf::DW_TAG_pointer_type
836            && Tag != dwarf::DW_TAG_ptr_to_member_type
837            && Tag != dwarf::DW_TAG_reference_type
838            && Tag != dwarf::DW_TAG_rvalue_reference_type)
839     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
840 
841   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
842     addDIEEntry(
843         Buffer, dwarf::DW_AT_containing_type,
844         *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
845   // Add source line info if available and TyDesc is not a forward declaration.
846   if (!DTy->isForwardDecl())
847     addSourceLine(Buffer, DTy);
848 }
849 
850 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
851   for (unsigned i = 1, N = Args.size(); i < N; ++i) {
852     const DIType *Ty = resolve(Args[i]);
853     if (!Ty) {
854       assert(i == N-1 && "Unspecified parameter must be the last argument");
855       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
856     } else {
857       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
858       addType(Arg, Ty);
859       if (Ty->isArtificial())
860         addFlag(Arg, dwarf::DW_AT_artificial);
861     }
862   }
863 }
864 
865 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
866   // Add return type.  A void return won't have a type.
867   auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
868   if (Elements.size())
869     if (auto RTy = resolve(Elements[0]))
870       addType(Buffer, RTy);
871 
872   bool isPrototyped = true;
873   if (Elements.size() == 2 && !Elements[1])
874     isPrototyped = false;
875 
876   constructSubprogramArguments(Buffer, Elements);
877 
878   // Add prototype flag if we're dealing with a C language and the function has
879   // been prototyped.
880   uint16_t Language = getLanguage();
881   if (isPrototyped &&
882       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
883        Language == dwarf::DW_LANG_ObjC))
884     addFlag(Buffer, dwarf::DW_AT_prototyped);
885 
886   // Add a DW_AT_calling_convention if this has an explicit convention.
887   if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
888     addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
889             CTy->getCC());
890 
891   if (CTy->isLValueReference())
892     addFlag(Buffer, dwarf::DW_AT_reference);
893 
894   if (CTy->isRValueReference())
895     addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
896 }
897 
898 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
899   if (CTy->isExternalTypeRef()) {
900     StringRef Identifier = CTy->getIdentifier();
901     assert(!Identifier.empty() && "external type ref without identifier");
902     addFlag(Buffer, dwarf::DW_AT_declaration);
903     return addDIETypeSignature(Buffer, dwarf::DW_AT_signature, Identifier);
904   }
905 
906   // Add name if not anonymous or intermediate type.
907   StringRef Name = CTy->getName();
908 
909   uint64_t Size = CTy->getSizeInBits() >> 3;
910   uint16_t Tag = Buffer.getTag();
911 
912   switch (Tag) {
913   case dwarf::DW_TAG_array_type:
914     constructArrayTypeDIE(Buffer, CTy);
915     break;
916   case dwarf::DW_TAG_enumeration_type:
917     constructEnumTypeDIE(Buffer, CTy);
918     break;
919   case dwarf::DW_TAG_structure_type:
920   case dwarf::DW_TAG_union_type:
921   case dwarf::DW_TAG_class_type: {
922     // Add elements to structure type.
923     DINodeArray Elements = CTy->getElements();
924     for (const auto *Element : Elements) {
925       if (!Element)
926         continue;
927       if (auto *SP = dyn_cast<DISubprogram>(Element))
928         getOrCreateSubprogramDIE(SP);
929       else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
930         if (DDTy->getTag() == dwarf::DW_TAG_friend) {
931           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
932           addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
933         } else if (DDTy->isStaticMember()) {
934           getOrCreateStaticMemberDIE(DDTy);
935         } else {
936           constructMemberDIE(Buffer, DDTy);
937         }
938       } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
939         DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
940         StringRef PropertyName = Property->getName();
941         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
942         if (Property->getType())
943           addType(ElemDie, resolve(Property->getType()));
944         addSourceLine(ElemDie, Property);
945         StringRef GetterName = Property->getGetterName();
946         if (!GetterName.empty())
947           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
948         StringRef SetterName = Property->getSetterName();
949         if (!SetterName.empty())
950           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
951         if (unsigned PropertyAttributes = Property->getAttributes())
952           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
953                   PropertyAttributes);
954       }
955     }
956 
957     if (CTy->isAppleBlockExtension())
958       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
959 
960     // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
961     // inside C++ composite types to point to the base class with the vtable.
962     if (auto *ContainingType =
963             dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
964       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
965                   *getOrCreateTypeDIE(ContainingType));
966 
967     if (CTy->isObjcClassComplete())
968       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
969 
970     // Add template parameters to a class, structure or union types.
971     // FIXME: The support isn't in the metadata for this yet.
972     if (Tag == dwarf::DW_TAG_class_type ||
973         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
974       addTemplateParams(Buffer, CTy->getTemplateParams());
975 
976     break;
977   }
978   default:
979     break;
980   }
981 
982   // Add name if not anonymous or intermediate type.
983   if (!Name.empty())
984     addString(Buffer, dwarf::DW_AT_name, Name);
985 
986   if (Tag == dwarf::DW_TAG_enumeration_type ||
987       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
988       Tag == dwarf::DW_TAG_union_type) {
989     // Add size if non-zero (derived types might be zero-sized.)
990     // TODO: Do we care about size for enum forward declarations?
991     if (Size)
992       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
993     else if (!CTy->isForwardDecl())
994       // Add zero size if it is not a forward declaration.
995       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
996 
997     // If we're a forward decl, say so.
998     if (CTy->isForwardDecl())
999       addFlag(Buffer, dwarf::DW_AT_declaration);
1000 
1001     // Add source line info if available.
1002     if (!CTy->isForwardDecl())
1003       addSourceLine(Buffer, CTy);
1004 
1005     // No harm in adding the runtime language to the declaration.
1006     unsigned RLang = CTy->getRuntimeLang();
1007     if (RLang)
1008       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1009               RLang);
1010 
1011     // Add align info if available.
1012     if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1013       addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1014               AlignInBytes);
1015   }
1016 }
1017 
1018 void DwarfUnit::constructTemplateTypeParameterDIE(
1019     DIE &Buffer, const DITemplateTypeParameter *TP) {
1020   DIE &ParamDIE =
1021       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1022   // Add the type if it exists, it could be void and therefore no type.
1023   if (TP->getType())
1024     addType(ParamDIE, resolve(TP->getType()));
1025   if (!TP->getName().empty())
1026     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1027 }
1028 
1029 void DwarfUnit::constructTemplateValueParameterDIE(
1030     DIE &Buffer, const DITemplateValueParameter *VP) {
1031   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1032 
1033   // Add the type if there is one, template template and template parameter
1034   // packs will not have a type.
1035   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1036     addType(ParamDIE, resolve(VP->getType()));
1037   if (!VP->getName().empty())
1038     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1039   if (Metadata *Val = VP->getValue()) {
1040     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1041       addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1042     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1043       // We cannot describe the location of dllimport'd entities: the
1044       // computation of their address requires loads from the IAT.
1045       if (!GV->hasDLLImportStorageClass()) {
1046         // For declaration non-type template parameters (such as global values
1047         // and functions)
1048         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1049         addOpAddress(*Loc, Asm->getSymbol(GV));
1050         // Emit DW_OP_stack_value to use the address as the immediate value of
1051         // the parameter, rather than a pointer to it.
1052         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1053         addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1054       }
1055     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1056       assert(isa<MDString>(Val));
1057       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1058                 cast<MDString>(Val)->getString());
1059     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1060       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1061     }
1062   }
1063 }
1064 
1065 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1066   // Construct the context before querying for the existence of the DIE in case
1067   // such construction creates the DIE.
1068   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1069 
1070   if (DIE *NDie = getDIE(NS))
1071     return NDie;
1072   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1073 
1074   StringRef Name = NS->getName();
1075   if (!Name.empty())
1076     addString(NDie, dwarf::DW_AT_name, NS->getName());
1077   else
1078     Name = "(anonymous namespace)";
1079   DD->addAccelNamespace(Name, NDie);
1080   addGlobalName(Name, NDie, NS->getScope());
1081   addSourceLine(NDie, NS);
1082   return &NDie;
1083 }
1084 
1085 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1086   // Construct the context before querying for the existence of the DIE in case
1087   // such construction creates the DIE.
1088   DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1089 
1090   if (DIE *MDie = getDIE(M))
1091     return MDie;
1092   DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1093 
1094   if (!M->getName().empty()) {
1095     addString(MDie, dwarf::DW_AT_name, M->getName());
1096     addGlobalName(M->getName(), MDie, M->getScope());
1097   }
1098   if (!M->getConfigurationMacros().empty())
1099     addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1100               M->getConfigurationMacros());
1101   if (!M->getIncludePath().empty())
1102     addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1103   if (!M->getISysRoot().empty())
1104     addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1105 
1106   return &MDie;
1107 }
1108 
1109 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1110   // Construct the context before querying for the existence of the DIE in case
1111   // such construction creates the DIE (as is the case for member function
1112   // declarations).
1113   DIE *ContextDIE =
1114       Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1115 
1116   if (DIE *SPDie = getDIE(SP))
1117     return SPDie;
1118 
1119   if (auto *SPDecl = SP->getDeclaration()) {
1120     if (!Minimal) {
1121       // Add subprogram definitions to the CU die directly.
1122       ContextDIE = &getUnitDie();
1123       // Build the decl now to ensure it precedes the definition.
1124       getOrCreateSubprogramDIE(SPDecl);
1125     }
1126   }
1127 
1128   // DW_TAG_inlined_subroutine may refer to this DIE.
1129   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1130 
1131   // Stop here and fill this in later, depending on whether or not this
1132   // subprogram turns out to have inlined instances or not.
1133   if (SP->isDefinition())
1134     return &SPDie;
1135 
1136   applySubprogramAttributes(SP, SPDie);
1137   return &SPDie;
1138 }
1139 
1140 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1141                                                     DIE &SPDie) {
1142   DIE *DeclDie = nullptr;
1143   StringRef DeclLinkageName;
1144   if (auto *SPDecl = SP->getDeclaration()) {
1145     DeclDie = getDIE(SPDecl);
1146     assert(DeclDie && "This DIE should've already been constructed when the "
1147                       "definition DIE was created in "
1148                       "getOrCreateSubprogramDIE");
1149     DeclLinkageName = SPDecl->getLinkageName();
1150     unsigned DeclID =
1151         getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1152     unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1153     if (DeclID != DefID)
1154       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1155 
1156     if (SP->getLine() != SPDecl->getLine())
1157       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1158   }
1159 
1160   // Add function template parameters.
1161   addTemplateParams(SPDie, SP->getTemplateParams());
1162 
1163   // Add the linkage name if we have one and it isn't in the Decl.
1164   StringRef LinkageName = SP->getLinkageName();
1165   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1166           LinkageName == DeclLinkageName) &&
1167          "decl has a linkage name and it is different");
1168   if (DeclLinkageName.empty() &&
1169       // Always emit it for abstract subprograms.
1170       (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1171     addLinkageName(SPDie, LinkageName);
1172 
1173   if (!DeclDie)
1174     return false;
1175 
1176   // Refer to the function declaration where all the other attributes will be
1177   // found.
1178   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1179   return true;
1180 }
1181 
1182 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1183                                           bool Minimal) {
1184   if (!Minimal)
1185     if (applySubprogramDefinitionAttributes(SP, SPDie))
1186       return;
1187 
1188   // Constructors and operators for anonymous aggregates do not have names.
1189   if (!SP->getName().empty())
1190     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1191 
1192   // Skip the rest of the attributes under -gmlt to save space.
1193   if (Minimal)
1194     return;
1195 
1196   addSourceLine(SPDie, SP);
1197 
1198   // Add the prototype if we have a prototype and we have a C like
1199   // language.
1200   uint16_t Language = getLanguage();
1201   if (SP->isPrototyped() &&
1202       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1203        Language == dwarf::DW_LANG_ObjC))
1204     addFlag(SPDie, dwarf::DW_AT_prototyped);
1205 
1206   unsigned CC = 0;
1207   DITypeRefArray Args;
1208   if (const DISubroutineType *SPTy = SP->getType()) {
1209     Args = SPTy->getTypeArray();
1210     CC = SPTy->getCC();
1211   }
1212 
1213   // Add a DW_AT_calling_convention if this has an explicit convention.
1214   if (CC && CC != dwarf::DW_CC_normal)
1215     addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1216 
1217   // Add a return type. If this is a type like a C/C++ void type we don't add a
1218   // return type.
1219   if (Args.size())
1220     if (auto Ty = resolve(Args[0]))
1221       addType(SPDie, Ty);
1222 
1223   unsigned VK = SP->getVirtuality();
1224   if (VK) {
1225     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1226     if (SP->getVirtualIndex() != -1u) {
1227       DIELoc *Block = getDIELoc();
1228       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1229       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1230       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1231     }
1232     ContainingTypeMap.insert(
1233         std::make_pair(&SPDie, resolve(SP->getContainingType())));
1234   }
1235 
1236   if (!SP->isDefinition()) {
1237     addFlag(SPDie, dwarf::DW_AT_declaration);
1238 
1239     // Add arguments. Do not add arguments for subprogram definition. They will
1240     // be handled while processing variables.
1241     constructSubprogramArguments(SPDie, Args);
1242   }
1243 
1244   if (SP->isArtificial())
1245     addFlag(SPDie, dwarf::DW_AT_artificial);
1246 
1247   if (!SP->isLocalToUnit())
1248     addFlag(SPDie, dwarf::DW_AT_external);
1249 
1250   if (DD->useAppleExtensionAttributes()) {
1251     if (SP->isOptimized())
1252       addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1253 
1254     if (unsigned isa = Asm->getISAEncoding())
1255       addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1256   }
1257 
1258   if (SP->isLValueReference())
1259     addFlag(SPDie, dwarf::DW_AT_reference);
1260 
1261   if (SP->isRValueReference())
1262     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1263 
1264   if (SP->isNoReturn())
1265     addFlag(SPDie, dwarf::DW_AT_noreturn);
1266 
1267   if (SP->isProtected())
1268     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1269             dwarf::DW_ACCESS_protected);
1270   else if (SP->isPrivate())
1271     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1272             dwarf::DW_ACCESS_private);
1273   else if (SP->isPublic())
1274     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1275             dwarf::DW_ACCESS_public);
1276 
1277   if (SP->isExplicit())
1278     addFlag(SPDie, dwarf::DW_AT_explicit);
1279 }
1280 
1281 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1282                                      DIE *IndexTy) {
1283   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1284   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1285 
1286   // The LowerBound value defines the lower bounds which is typically zero for
1287   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1288   // Count == -1 then the array is unbounded and we do not emit
1289   // DW_AT_lower_bound and DW_AT_count attributes.
1290   int64_t LowerBound = SR->getLowerBound();
1291   int64_t DefaultLowerBound = getDefaultLowerBound();
1292   int64_t Count = SR->getCount();
1293 
1294   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1295     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1296 
1297   if (Count != -1)
1298     // FIXME: An unbounded array should reference the expression that defines
1299     // the array.
1300     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1301 }
1302 
1303 DIE *DwarfUnit::getIndexTyDie() {
1304   if (IndexTyDie)
1305     return IndexTyDie;
1306   // Construct an integer type to use for indexes.
1307   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1308   addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1309   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1310   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1311           dwarf::DW_ATE_unsigned);
1312   return IndexTyDie;
1313 }
1314 
1315 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1316   if (CTy->isVector())
1317     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1318 
1319   // Emit the element type.
1320   addType(Buffer, resolve(CTy->getBaseType()));
1321 
1322   // Get an anonymous type for index type.
1323   // FIXME: This type should be passed down from the front end
1324   // as different languages may have different sizes for indexes.
1325   DIE *IdxTy = getIndexTyDie();
1326 
1327   // Add subranges to array type.
1328   DINodeArray Elements = CTy->getElements();
1329   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1330     // FIXME: Should this really be such a loose cast?
1331     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1332       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1333         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1334   }
1335 }
1336 
1337 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1338   DINodeArray Elements = CTy->getElements();
1339 
1340   // Add enumerators to enumeration type.
1341   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1342     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1343     if (Enum) {
1344       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1345       StringRef Name = Enum->getName();
1346       addString(Enumerator, dwarf::DW_AT_name, Name);
1347       int64_t Value = Enum->getValue();
1348       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1349               Value);
1350     }
1351   }
1352   const DIType *DTy = resolve(CTy->getBaseType());
1353   if (DTy) {
1354     addType(Buffer, DTy);
1355     addFlag(Buffer, dwarf::DW_AT_enum_class);
1356   }
1357 }
1358 
1359 void DwarfUnit::constructContainingTypeDIEs() {
1360   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1361        CI != CE; ++CI) {
1362     DIE &SPDie = *CI->first;
1363     const DINode *D = CI->second;
1364     if (!D)
1365       continue;
1366     DIE *NDie = getDIE(D);
1367     if (!NDie)
1368       continue;
1369     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1370   }
1371 }
1372 
1373 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1374   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1375   StringRef Name = DT->getName();
1376   if (!Name.empty())
1377     addString(MemberDie, dwarf::DW_AT_name, Name);
1378 
1379   addType(MemberDie, resolve(DT->getBaseType()));
1380 
1381   addSourceLine(MemberDie, DT);
1382 
1383   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1384 
1385     // For C++, virtual base classes are not at fixed offset. Use following
1386     // expression to extract appropriate offset from vtable.
1387     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1388 
1389     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1390     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1391     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1392     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1393     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1394     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1395     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1396     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1397 
1398     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1399   } else {
1400     uint64_t Size = DT->getSizeInBits();
1401     uint64_t FieldSize = DD->getBaseTypeSize(DT);
1402     uint32_t AlignInBytes = DT->getAlignInBytes();
1403     uint64_t OffsetInBytes;
1404 
1405     bool IsBitfield = FieldSize && Size != FieldSize;
1406     if (IsBitfield) {
1407       // Handle bitfield, assume bytes are 8 bits.
1408       if (DD->useDWARF2Bitfields())
1409         addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1410       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1411 
1412       uint64_t Offset = DT->getOffsetInBits();
1413       // We can't use DT->getAlignInBits() here: AlignInBits for member type
1414       // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1415       // which can't be done with bitfields. Thus we use FieldSize here.
1416       uint32_t AlignInBits = FieldSize;
1417       uint32_t AlignMask = ~(AlignInBits - 1);
1418       // The bits from the start of the storage unit to the start of the field.
1419       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1420       // The byte offset of the field's aligned storage unit inside the struct.
1421       OffsetInBytes = (Offset - StartBitOffset) / 8;
1422 
1423       if (DD->useDWARF2Bitfields()) {
1424         uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1425         uint64_t FieldOffset = (HiMark - FieldSize);
1426         Offset -= FieldOffset;
1427 
1428         // Maybe we need to work from the other end.
1429         if (Asm->getDataLayout().isLittleEndian())
1430           Offset = FieldSize - (Offset + Size);
1431 
1432         addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1433         OffsetInBytes = FieldOffset >> 3;
1434       } else {
1435         addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1436       }
1437     } else {
1438       // This is not a bitfield.
1439       OffsetInBytes = DT->getOffsetInBits() / 8;
1440       if (AlignInBytes)
1441         addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1442                 AlignInBytes);
1443     }
1444 
1445     if (DD->getDwarfVersion() <= 2) {
1446       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1447       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1448       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1449       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1450     } else if (!IsBitfield || DD->useDWARF2Bitfields())
1451       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1452               OffsetInBytes);
1453   }
1454 
1455   if (DT->isProtected())
1456     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1457             dwarf::DW_ACCESS_protected);
1458   else if (DT->isPrivate())
1459     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1460             dwarf::DW_ACCESS_private);
1461   // Otherwise C++ member and base classes are considered public.
1462   else if (DT->isPublic())
1463     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1464             dwarf::DW_ACCESS_public);
1465   if (DT->isVirtual())
1466     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1467             dwarf::DW_VIRTUALITY_virtual);
1468 
1469   // Objective-C properties.
1470   if (DINode *PNode = DT->getObjCProperty())
1471     if (DIE *PDie = getDIE(PNode))
1472       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1473                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1474 
1475   if (DT->isArtificial())
1476     addFlag(MemberDie, dwarf::DW_AT_artificial);
1477 }
1478 
1479 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1480   if (!DT)
1481     return nullptr;
1482 
1483   // Construct the context before querying for the existence of the DIE in case
1484   // such construction creates the DIE.
1485   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1486   assert(dwarf::isType(ContextDIE->getTag()) &&
1487          "Static member should belong to a type.");
1488 
1489   if (DIE *StaticMemberDIE = getDIE(DT))
1490     return StaticMemberDIE;
1491 
1492   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1493 
1494   const DIType *Ty = resolve(DT->getBaseType());
1495 
1496   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1497   addType(StaticMemberDIE, Ty);
1498   addSourceLine(StaticMemberDIE, DT);
1499   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1500   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1501 
1502   // FIXME: We could omit private if the parent is a class_type, and
1503   // public if the parent is something else.
1504   if (DT->isProtected())
1505     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1506             dwarf::DW_ACCESS_protected);
1507   else if (DT->isPrivate())
1508     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1509             dwarf::DW_ACCESS_private);
1510   else if (DT->isPublic())
1511     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1512             dwarf::DW_ACCESS_public);
1513 
1514   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1515     addConstantValue(StaticMemberDIE, CI, Ty);
1516   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1517     addConstantFPValue(StaticMemberDIE, CFP);
1518 
1519   if (uint32_t AlignInBytes = DT->getAlignInBytes())
1520     addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1521             AlignInBytes);
1522 
1523   return &StaticMemberDIE;
1524 }
1525 
1526 void DwarfUnit::emitHeader(bool UseOffsets) {
1527   // Emit size of content not including length itself
1528   Asm->OutStreamer->AddComment("Length of Unit");
1529   Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1530 
1531   Asm->OutStreamer->AddComment("DWARF version number");
1532   Asm->EmitInt16(DD->getDwarfVersion());
1533   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1534 
1535   // We share one abbreviations table across all units so it's always at the
1536   // start of the section. Use a relocatable offset where needed to ensure
1537   // linking doesn't invalidate that offset.
1538   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1539   if (UseOffsets)
1540     Asm->EmitInt32(0);
1541   else
1542     Asm->emitDwarfSymbolReference(
1543         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1544 
1545   Asm->OutStreamer->AddComment("Address Size (in bytes)");
1546   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1547 }
1548 
1549 void DwarfUnit::initSection(MCSection *Section) {
1550   assert(!this->Section);
1551   this->Section = Section;
1552 }
1553 
1554 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1555   DwarfUnit::emitHeader(UseOffsets);
1556   Asm->OutStreamer->AddComment("Type Signature");
1557   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1558   Asm->OutStreamer->AddComment("Type DIE Offset");
1559   // In a skeleton type unit there is no type DIE so emit a zero offset.
1560   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1561                                  sizeof(Ty->getOffset()));
1562 }
1563 
1564 bool DwarfTypeUnit::isDwoUnit() const {
1565   // Since there are no skeleton type units, all type units are dwo type units
1566   // when split DWARF is being used.
1567   return DD->useSplitDwarf();
1568 }
1569