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