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 
476   SmallVector<uint64_t, 9> Ops;
477   if (Location.isIndirect() && Location.getOffset()) {
478     Ops.push_back(dwarf::DW_OP_plus);
479     Ops.push_back(Location.getOffset());
480   }
481   // If we started with a pointer to the __Block_byref... struct, then
482   // the first thing we need to do is dereference the pointer (DW_OP_deref).
483   if (isPointer)
484     Ops.push_back(dwarf::DW_OP_deref);
485 
486   // Next add the offset for the '__forwarding' field:
487   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
488   // adding the offset if it's 0.
489   if (forwardingFieldOffset > 0) {
490     Ops.push_back(dwarf::DW_OP_plus);
491     Ops.push_back(forwardingFieldOffset);
492   }
493 
494   // Now dereference the __forwarding field to get to the real __Block_byref
495   // struct:  DW_OP_deref.
496   Ops.push_back(dwarf::DW_OP_deref);
497 
498   // Now that we've got the real __Block_byref... struct, add the offset
499   // for the variable's field to get to the location of the actual variable:
500   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
501   if (varFieldOffset > 0) {
502     Ops.push_back(dwarf::DW_OP_plus);
503     Ops.push_back(varFieldOffset);
504   }
505 
506   DIExpressionCursor Cursor(Ops);
507   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
508   if (!DwarfExpr.addMachineLocExpression(TRI, Cursor, Location))
509     return;
510   DwarfExpr.addExpression(std::move(Cursor));
511 
512   // Now attach the location information to the DIE.
513   addBlock(Die, Attribute, DwarfExpr.finalize());
514 }
515 
516 /// Return true if type encoding is unsigned.
517 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
518   if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
519     // FIXME: Enums without a fixed underlying type have unknown signedness
520     // here, leading to incorrectly emitted constants.
521     if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
522       return false;
523 
524     // (Pieces of) aggregate types that get hacked apart by SROA may be
525     // represented by a constant. Encode them as unsigned bytes.
526     return true;
527   }
528 
529   if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
530     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
531     // Encode pointer constants as unsigned bytes. This is used at least for
532     // null pointer constant emission.
533     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
534     // here, but accept them for now due to a bug in SROA producing bogus
535     // dbg.values.
536     if (T == dwarf::DW_TAG_pointer_type ||
537         T == dwarf::DW_TAG_ptr_to_member_type ||
538         T == dwarf::DW_TAG_reference_type ||
539         T == dwarf::DW_TAG_rvalue_reference_type)
540       return true;
541     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
542            T == dwarf::DW_TAG_volatile_type ||
543            T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
544     DITypeRef Deriv = DTy->getBaseType();
545     assert(Deriv && "Expected valid base type");
546     return isUnsignedDIType(DD, DD->resolve(Deriv));
547   }
548 
549   auto *BTy = cast<DIBasicType>(Ty);
550   unsigned Encoding = BTy->getEncoding();
551   assert((Encoding == dwarf::DW_ATE_unsigned ||
552           Encoding == dwarf::DW_ATE_unsigned_char ||
553           Encoding == dwarf::DW_ATE_signed ||
554           Encoding == dwarf::DW_ATE_signed_char ||
555           Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
556           Encoding == dwarf::DW_ATE_boolean ||
557           (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
558            Ty->getName() == "decltype(nullptr)")) &&
559          "Unsupported encoding");
560   return Encoding == dwarf::DW_ATE_unsigned ||
561          Encoding == dwarf::DW_ATE_unsigned_char ||
562          Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
563          Ty->getTag() == dwarf::DW_TAG_unspecified_type;
564 }
565 
566 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
567   assert(MO.isFPImm() && "Invalid machine operand!");
568   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
569   APFloat FPImm = MO.getFPImm()->getValueAPF();
570 
571   // Get the raw data form of the floating point.
572   const APInt FltVal = FPImm.bitcastToAPInt();
573   const char *FltPtr = (const char *)FltVal.getRawData();
574 
575   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
576   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
577   int Incr = (LittleEndian ? 1 : -1);
578   int Start = (LittleEndian ? 0 : NumBytes - 1);
579   int Stop = (LittleEndian ? NumBytes : -1);
580 
581   // Output the constant to DWARF one byte at a time.
582   for (; Start != Stop; Start += Incr)
583     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
584 
585   addBlock(Die, dwarf::DW_AT_const_value, Block);
586 }
587 
588 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
589   // Pass this down to addConstantValue as an unsigned bag of bits.
590   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
591 }
592 
593 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
594                                  const DIType *Ty) {
595   addConstantValue(Die, CI->getValue(), Ty);
596 }
597 
598 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
599                                  const DIType *Ty) {
600   assert(MO.isImm() && "Invalid machine operand!");
601 
602   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
603 }
604 
605 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
606   // FIXME: This is a bit conservative/simple - it emits negative values always
607   // sign extended to 64 bits rather than minimizing the number of bytes.
608   addUInt(Die, dwarf::DW_AT_const_value,
609           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
610 }
611 
612 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
613   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
614 }
615 
616 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
617   unsigned CIBitWidth = Val.getBitWidth();
618   if (CIBitWidth <= 64) {
619     addConstantValue(Die, Unsigned,
620                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
621     return;
622   }
623 
624   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
625 
626   // Get the raw data form of the large APInt.
627   const uint64_t *Ptr64 = Val.getRawData();
628 
629   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
630   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
631 
632   // Output the constant to DWARF one byte at a time.
633   for (int i = 0; i < NumBytes; i++) {
634     uint8_t c;
635     if (LittleEndian)
636       c = Ptr64[i / 8] >> (8 * (i & 7));
637     else
638       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
639     addUInt(*Block, dwarf::DW_FORM_data1, c);
640   }
641 
642   addBlock(Die, dwarf::DW_AT_const_value, Block);
643 }
644 
645 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
646   if (!LinkageName.empty())
647     addString(Die,
648               DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
649                                          : dwarf::DW_AT_MIPS_linkage_name,
650               GlobalValue::getRealLinkageName(LinkageName));
651 }
652 
653 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
654   // Add template parameters.
655   for (const auto *Element : TParams) {
656     if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
657       constructTemplateTypeParameterDIE(Buffer, TTP);
658     else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
659       constructTemplateValueParameterDIE(Buffer, TVP);
660   }
661 }
662 
663 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
664   if (!Context || isa<DIFile>(Context))
665     return &getUnitDie();
666   if (auto *T = dyn_cast<DIType>(Context))
667     return getOrCreateTypeDIE(T);
668   if (auto *NS = dyn_cast<DINamespace>(Context))
669     return getOrCreateNameSpace(NS);
670   if (auto *SP = dyn_cast<DISubprogram>(Context))
671     return getOrCreateSubprogramDIE(SP);
672   if (auto *M = dyn_cast<DIModule>(Context))
673     return getOrCreateModule(M);
674   return getDIE(Context);
675 }
676 
677 DIE *DwarfTypeUnit::createTypeDIE(const DICompositeType *Ty) {
678   auto *Context = resolve(Ty->getScope());
679   DIE *ContextDIE = getOrCreateContextDIE(Context);
680 
681   if (DIE *TyDIE = getDIE(Ty))
682     return TyDIE;
683 
684   // Create new type.
685   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
686 
687   constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
688 
689   updateAcceleratorTables(Context, Ty, TyDIE);
690   return &TyDIE;
691 }
692 
693 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
694   if (!TyNode)
695     return nullptr;
696 
697   auto *Ty = cast<DIType>(TyNode);
698 
699   // DW_TAG_restrict_type is not supported in DWARF2
700   if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
701     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
702 
703   // DW_TAG_atomic_type is not supported in DWARF < 5
704   if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
705     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
706 
707   // Construct the context before querying for the existence of the DIE in case
708   // such construction creates the DIE.
709   auto *Context = resolve(Ty->getScope());
710   DIE *ContextDIE = getOrCreateContextDIE(Context);
711   assert(ContextDIE);
712 
713   if (DIE *TyDIE = getDIE(Ty))
714     return TyDIE;
715 
716   // Create new type.
717   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
718 
719   updateAcceleratorTables(Context, Ty, TyDIE);
720 
721   if (auto *BT = dyn_cast<DIBasicType>(Ty))
722     constructTypeDIE(TyDIE, BT);
723   else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
724     constructTypeDIE(TyDIE, STy);
725   else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
726     if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
727       if (MDString *TypeId = CTy->getRawIdentifier()) {
728         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
729         // Skip updating the accelerator tables since this is not the full type.
730         return &TyDIE;
731       }
732     constructTypeDIE(TyDIE, CTy);
733   } else {
734     constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
735   }
736 
737   return &TyDIE;
738 }
739 
740 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
741                                         const DIType *Ty, const DIE &TyDIE) {
742   if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
743     bool IsImplementation = false;
744     if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
745       // A runtime language of 0 actually means C/C++ and that any
746       // non-negative value is some version of Objective-C/C++.
747       IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
748     }
749     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
750     DD->addAccelType(Ty->getName(), TyDIE, Flags);
751 
752     if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
753         isa<DINamespace>(Context))
754       addGlobalType(Ty, TyDIE, Context);
755   }
756 }
757 
758 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
759                         dwarf::Attribute Attribute) {
760   assert(Ty && "Trying to add a type that doesn't exist?");
761   addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
762 }
763 
764 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
765   if (!Context)
766     return "";
767 
768   // FIXME: Decide whether to implement this for non-C++ languages.
769   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
770     return "";
771 
772   std::string CS;
773   SmallVector<const DIScope *, 1> Parents;
774   while (!isa<DICompileUnit>(Context)) {
775     Parents.push_back(Context);
776     if (Context->getScope())
777       Context = resolve(Context->getScope());
778     else
779       // Structure, etc types will have a NULL context if they're at the top
780       // level.
781       break;
782   }
783 
784   // Reverse iterate over our list to go from the outermost construct to the
785   // innermost.
786   for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
787     StringRef Name = Ctx->getName();
788     if (Name.empty() && isa<DINamespace>(Ctx))
789       Name = "(anonymous namespace)";
790     if (!Name.empty()) {
791       CS += Name;
792       CS += "::";
793     }
794   }
795   return CS;
796 }
797 
798 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
799   // Get core information.
800   StringRef Name = BTy->getName();
801   // Add name if not anonymous or intermediate type.
802   if (!Name.empty())
803     addString(Buffer, dwarf::DW_AT_name, Name);
804 
805   // An unspecified type only has a name attribute.
806   if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
807     return;
808 
809   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
810           BTy->getEncoding());
811 
812   uint64_t Size = BTy->getSizeInBits() >> 3;
813   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
814 }
815 
816 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
817   // Get core information.
818   StringRef Name = DTy->getName();
819   uint64_t Size = DTy->getSizeInBits() >> 3;
820   uint16_t Tag = Buffer.getTag();
821 
822   // Map to main type, void will not have a type.
823   const DIType *FromTy = resolve(DTy->getBaseType());
824   if (FromTy)
825     addType(Buffer, FromTy);
826 
827   // Add name if not anonymous or intermediate type.
828   if (!Name.empty())
829     addString(Buffer, dwarf::DW_AT_name, Name);
830 
831   // Add size if non-zero (derived types might be zero-sized.)
832   if (Size && Tag != dwarf::DW_TAG_pointer_type
833            && Tag != dwarf::DW_TAG_ptr_to_member_type
834            && Tag != dwarf::DW_TAG_reference_type
835            && Tag != dwarf::DW_TAG_rvalue_reference_type)
836     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
837 
838   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
839     addDIEEntry(
840         Buffer, dwarf::DW_AT_containing_type,
841         *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
842   // Add source line info if available and TyDesc is not a forward declaration.
843   if (!DTy->isForwardDecl())
844     addSourceLine(Buffer, DTy);
845 
846   // If DWARF address space value is other than None, add it for pointer and
847   // reference types as DW_AT_address_class.
848   if (DTy->getDWARFAddressSpace() && (Tag == dwarf::DW_TAG_pointer_type ||
849                                       Tag == dwarf::DW_TAG_reference_type))
850     addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
851             DTy->getDWARFAddressSpace().getValue());
852 }
853 
854 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
855   for (unsigned i = 1, N = Args.size(); i < N; ++i) {
856     const DIType *Ty = resolve(Args[i]);
857     if (!Ty) {
858       assert(i == N-1 && "Unspecified parameter must be the last argument");
859       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
860     } else {
861       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
862       addType(Arg, Ty);
863       if (Ty->isArtificial())
864         addFlag(Arg, dwarf::DW_AT_artificial);
865     }
866   }
867 }
868 
869 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
870   // Add return type.  A void return won't have a type.
871   auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
872   if (Elements.size())
873     if (auto RTy = resolve(Elements[0]))
874       addType(Buffer, RTy);
875 
876   bool isPrototyped = true;
877   if (Elements.size() == 2 && !Elements[1])
878     isPrototyped = false;
879 
880   constructSubprogramArguments(Buffer, Elements);
881 
882   // Add prototype flag if we're dealing with a C language and the function has
883   // been prototyped.
884   uint16_t Language = getLanguage();
885   if (isPrototyped &&
886       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
887        Language == dwarf::DW_LANG_ObjC))
888     addFlag(Buffer, dwarf::DW_AT_prototyped);
889 
890   // Add a DW_AT_calling_convention if this has an explicit convention.
891   if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
892     addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
893             CTy->getCC());
894 
895   if (CTy->isLValueReference())
896     addFlag(Buffer, dwarf::DW_AT_reference);
897 
898   if (CTy->isRValueReference())
899     addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
900 }
901 
902 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
903   // Add name if not anonymous or intermediate type.
904   StringRef Name = CTy->getName();
905 
906   uint64_t Size = CTy->getSizeInBits() >> 3;
907   uint16_t Tag = Buffer.getTag();
908 
909   switch (Tag) {
910   case dwarf::DW_TAG_array_type:
911     constructArrayTypeDIE(Buffer, CTy);
912     break;
913   case dwarf::DW_TAG_enumeration_type:
914     constructEnumTypeDIE(Buffer, CTy);
915     break;
916   case dwarf::DW_TAG_structure_type:
917   case dwarf::DW_TAG_union_type:
918   case dwarf::DW_TAG_class_type: {
919     // Add elements to structure type.
920     DINodeArray Elements = CTy->getElements();
921     for (const auto *Element : Elements) {
922       if (!Element)
923         continue;
924       if (auto *SP = dyn_cast<DISubprogram>(Element))
925         getOrCreateSubprogramDIE(SP);
926       else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
927         if (DDTy->getTag() == dwarf::DW_TAG_friend) {
928           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
929           addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
930         } else if (DDTy->isStaticMember()) {
931           getOrCreateStaticMemberDIE(DDTy);
932         } else {
933           constructMemberDIE(Buffer, DDTy);
934         }
935       } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
936         DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
937         StringRef PropertyName = Property->getName();
938         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
939         if (Property->getType())
940           addType(ElemDie, resolve(Property->getType()));
941         addSourceLine(ElemDie, Property);
942         StringRef GetterName = Property->getGetterName();
943         if (!GetterName.empty())
944           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
945         StringRef SetterName = Property->getSetterName();
946         if (!SetterName.empty())
947           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
948         if (unsigned PropertyAttributes = Property->getAttributes())
949           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
950                   PropertyAttributes);
951       }
952     }
953 
954     if (CTy->isAppleBlockExtension())
955       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
956 
957     // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
958     // inside C++ composite types to point to the base class with the vtable.
959     if (auto *ContainingType =
960             dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
961       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
962                   *getOrCreateTypeDIE(ContainingType));
963 
964     if (CTy->isObjcClassComplete())
965       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
966 
967     // Add template parameters to a class, structure or union types.
968     // FIXME: The support isn't in the metadata for this yet.
969     if (Tag == dwarf::DW_TAG_class_type ||
970         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
971       addTemplateParams(Buffer, CTy->getTemplateParams());
972 
973     break;
974   }
975   default:
976     break;
977   }
978 
979   // Add name if not anonymous or intermediate type.
980   if (!Name.empty())
981     addString(Buffer, dwarf::DW_AT_name, Name);
982 
983   if (Tag == dwarf::DW_TAG_enumeration_type ||
984       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
985       Tag == dwarf::DW_TAG_union_type) {
986     // Add size if non-zero (derived types might be zero-sized.)
987     // TODO: Do we care about size for enum forward declarations?
988     if (Size)
989       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
990     else if (!CTy->isForwardDecl())
991       // Add zero size if it is not a forward declaration.
992       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
993 
994     // If we're a forward decl, say so.
995     if (CTy->isForwardDecl())
996       addFlag(Buffer, dwarf::DW_AT_declaration);
997 
998     // Add source line info if available.
999     if (!CTy->isForwardDecl())
1000       addSourceLine(Buffer, CTy);
1001 
1002     // No harm in adding the runtime language to the declaration.
1003     unsigned RLang = CTy->getRuntimeLang();
1004     if (RLang)
1005       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1006               RLang);
1007 
1008     // Add align info if available.
1009     if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1010       addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1011               AlignInBytes);
1012   }
1013 }
1014 
1015 void DwarfUnit::constructTemplateTypeParameterDIE(
1016     DIE &Buffer, const DITemplateTypeParameter *TP) {
1017   DIE &ParamDIE =
1018       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1019   // Add the type if it exists, it could be void and therefore no type.
1020   if (TP->getType())
1021     addType(ParamDIE, resolve(TP->getType()));
1022   if (!TP->getName().empty())
1023     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1024 }
1025 
1026 void DwarfUnit::constructTemplateValueParameterDIE(
1027     DIE &Buffer, const DITemplateValueParameter *VP) {
1028   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1029 
1030   // Add the type if there is one, template template and template parameter
1031   // packs will not have a type.
1032   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1033     addType(ParamDIE, resolve(VP->getType()));
1034   if (!VP->getName().empty())
1035     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1036   if (Metadata *Val = VP->getValue()) {
1037     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1038       addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1039     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1040       // We cannot describe the location of dllimport'd entities: the
1041       // computation of their address requires loads from the IAT.
1042       if (!GV->hasDLLImportStorageClass()) {
1043         // For declaration non-type template parameters (such as global values
1044         // and functions)
1045         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1046         addOpAddress(*Loc, Asm->getSymbol(GV));
1047         // Emit DW_OP_stack_value to use the address as the immediate value of
1048         // the parameter, rather than a pointer to it.
1049         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1050         addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1051       }
1052     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1053       assert(isa<MDString>(Val));
1054       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1055                 cast<MDString>(Val)->getString());
1056     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1057       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1058     }
1059   }
1060 }
1061 
1062 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1063   // Construct the context before querying for the existence of the DIE in case
1064   // such construction creates the DIE.
1065   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1066 
1067   if (DIE *NDie = getDIE(NS))
1068     return NDie;
1069   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1070 
1071   StringRef Name = NS->getName();
1072   if (!Name.empty())
1073     addString(NDie, dwarf::DW_AT_name, NS->getName());
1074   else
1075     Name = "(anonymous namespace)";
1076   DD->addAccelNamespace(Name, NDie);
1077   addGlobalName(Name, NDie, NS->getScope());
1078   addSourceLine(NDie, NS);
1079   if (NS->getExportSymbols())
1080     addFlag(NDie, dwarf::DW_AT_export_symbols);
1081   return &NDie;
1082 }
1083 
1084 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1085   // Construct the context before querying for the existence of the DIE in case
1086   // such construction creates the DIE.
1087   DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1088 
1089   if (DIE *MDie = getDIE(M))
1090     return MDie;
1091   DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1092 
1093   if (!M->getName().empty()) {
1094     addString(MDie, dwarf::DW_AT_name, M->getName());
1095     addGlobalName(M->getName(), MDie, M->getScope());
1096   }
1097   if (!M->getConfigurationMacros().empty())
1098     addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1099               M->getConfigurationMacros());
1100   if (!M->getIncludePath().empty())
1101     addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1102   if (!M->getISysRoot().empty())
1103     addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1104 
1105   return &MDie;
1106 }
1107 
1108 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1109   // Construct the context before querying for the existence of the DIE in case
1110   // such construction creates the DIE (as is the case for member function
1111   // declarations).
1112   DIE *ContextDIE =
1113       Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1114 
1115   if (DIE *SPDie = getDIE(SP))
1116     return SPDie;
1117 
1118   if (auto *SPDecl = SP->getDeclaration()) {
1119     if (!Minimal) {
1120       // Add subprogram definitions to the CU die directly.
1121       ContextDIE = &getUnitDie();
1122       // Build the decl now to ensure it precedes the definition.
1123       getOrCreateSubprogramDIE(SPDecl);
1124     }
1125   }
1126 
1127   // DW_TAG_inlined_subroutine may refer to this DIE.
1128   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1129 
1130   // Stop here and fill this in later, depending on whether or not this
1131   // subprogram turns out to have inlined instances or not.
1132   if (SP->isDefinition())
1133     return &SPDie;
1134 
1135   applySubprogramAttributes(SP, SPDie);
1136   return &SPDie;
1137 }
1138 
1139 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1140                                                     DIE &SPDie) {
1141   DIE *DeclDie = nullptr;
1142   StringRef DeclLinkageName;
1143   if (auto *SPDecl = SP->getDeclaration()) {
1144     DeclDie = getDIE(SPDecl);
1145     assert(DeclDie && "This DIE should've already been constructed when the "
1146                       "definition DIE was created in "
1147                       "getOrCreateSubprogramDIE");
1148     // Look at the Decl's linkage name only if we emitted it.
1149     if (DD->useAllLinkageNames())
1150       DeclLinkageName = SPDecl->getLinkageName();
1151     unsigned DeclID =
1152         getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1153     unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1154     if (DeclID != DefID)
1155       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1156 
1157     if (SP->getLine() != SPDecl->getLine())
1158       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1159   }
1160 
1161   // Add function template parameters.
1162   addTemplateParams(SPDie, SP->getTemplateParams());
1163 
1164   // Add the linkage name if we have one and it isn't in the Decl.
1165   StringRef LinkageName = SP->getLinkageName();
1166   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1167           LinkageName == DeclLinkageName) &&
1168          "decl has a linkage name and it is different");
1169   if (DeclLinkageName.empty() &&
1170       // Always emit it for abstract subprograms.
1171       (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1172     addLinkageName(SPDie, LinkageName);
1173 
1174   if (!DeclDie)
1175     return false;
1176 
1177   // Refer to the function declaration where all the other attributes will be
1178   // found.
1179   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1180   return true;
1181 }
1182 
1183 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1184                                           bool SkipSPAttributes) {
1185   // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1186   // and its source location.
1187   bool SkipSPSourceLocation = SkipSPAttributes &&
1188                               !CUNode->getDebugInfoForProfiling();
1189   if (!SkipSPSourceLocation)
1190     if (applySubprogramDefinitionAttributes(SP, SPDie))
1191       return;
1192 
1193   // Constructors and operators for anonymous aggregates do not have names.
1194   if (!SP->getName().empty())
1195     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1196 
1197   if (!SkipSPSourceLocation)
1198     addSourceLine(SPDie, SP);
1199 
1200   // Skip the rest of the attributes under -gmlt to save space.
1201   if (SkipSPAttributes)
1202     return;
1203 
1204   // Add the prototype if we have a prototype and we have a C like
1205   // language.
1206   uint16_t Language = getLanguage();
1207   if (SP->isPrototyped() &&
1208       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1209        Language == dwarf::DW_LANG_ObjC))
1210     addFlag(SPDie, dwarf::DW_AT_prototyped);
1211 
1212   unsigned CC = 0;
1213   DITypeRefArray Args;
1214   if (const DISubroutineType *SPTy = SP->getType()) {
1215     Args = SPTy->getTypeArray();
1216     CC = SPTy->getCC();
1217   }
1218 
1219   // Add a DW_AT_calling_convention if this has an explicit convention.
1220   if (CC && CC != dwarf::DW_CC_normal)
1221     addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1222 
1223   // Add a return type. If this is a type like a C/C++ void type we don't add a
1224   // return type.
1225   if (Args.size())
1226     if (auto Ty = resolve(Args[0]))
1227       addType(SPDie, Ty);
1228 
1229   unsigned VK = SP->getVirtuality();
1230   if (VK) {
1231     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1232     if (SP->getVirtualIndex() != -1u) {
1233       DIELoc *Block = getDIELoc();
1234       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1235       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1236       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1237     }
1238     ContainingTypeMap.insert(
1239         std::make_pair(&SPDie, resolve(SP->getContainingType())));
1240   }
1241 
1242   if (!SP->isDefinition()) {
1243     addFlag(SPDie, dwarf::DW_AT_declaration);
1244 
1245     // Add arguments. Do not add arguments for subprogram definition. They will
1246     // be handled while processing variables.
1247     constructSubprogramArguments(SPDie, Args);
1248   }
1249 
1250   if (SP->isArtificial())
1251     addFlag(SPDie, dwarf::DW_AT_artificial);
1252 
1253   if (!SP->isLocalToUnit())
1254     addFlag(SPDie, dwarf::DW_AT_external);
1255 
1256   if (DD->useAppleExtensionAttributes()) {
1257     if (SP->isOptimized())
1258       addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1259 
1260     if (unsigned isa = Asm->getISAEncoding())
1261       addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1262   }
1263 
1264   if (SP->isLValueReference())
1265     addFlag(SPDie, dwarf::DW_AT_reference);
1266 
1267   if (SP->isRValueReference())
1268     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1269 
1270   if (SP->isNoReturn())
1271     addFlag(SPDie, dwarf::DW_AT_noreturn);
1272 
1273   if (SP->isProtected())
1274     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1275             dwarf::DW_ACCESS_protected);
1276   else if (SP->isPrivate())
1277     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1278             dwarf::DW_ACCESS_private);
1279   else if (SP->isPublic())
1280     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1281             dwarf::DW_ACCESS_public);
1282 
1283   if (SP->isExplicit())
1284     addFlag(SPDie, dwarf::DW_AT_explicit);
1285 
1286   if (SP->isMainSubprogram())
1287     addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1288 }
1289 
1290 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1291                                      DIE *IndexTy) {
1292   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1293   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1294 
1295   // The LowerBound value defines the lower bounds which is typically zero for
1296   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1297   // Count == -1 then the array is unbounded and we do not emit
1298   // DW_AT_lower_bound and DW_AT_count attributes.
1299   int64_t LowerBound = SR->getLowerBound();
1300   int64_t DefaultLowerBound = getDefaultLowerBound();
1301   int64_t Count = SR->getCount();
1302 
1303   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1304     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1305 
1306   if (Count != -1)
1307     // FIXME: An unbounded array should reference the expression that defines
1308     // the array.
1309     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1310 }
1311 
1312 DIE *DwarfUnit::getIndexTyDie() {
1313   if (IndexTyDie)
1314     return IndexTyDie;
1315   // Construct an integer type to use for indexes.
1316   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1317   addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1318   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1319   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1320           dwarf::DW_ATE_unsigned);
1321   return IndexTyDie;
1322 }
1323 
1324 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1325   if (CTy->isVector())
1326     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1327 
1328   // Emit the element type.
1329   addType(Buffer, resolve(CTy->getBaseType()));
1330 
1331   // Get an anonymous type for index type.
1332   // FIXME: This type should be passed down from the front end
1333   // as different languages may have different sizes for indexes.
1334   DIE *IdxTy = getIndexTyDie();
1335 
1336   // Add subranges to array type.
1337   DINodeArray Elements = CTy->getElements();
1338   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1339     // FIXME: Should this really be such a loose cast?
1340     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1341       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1342         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1343   }
1344 }
1345 
1346 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1347   DINodeArray Elements = CTy->getElements();
1348 
1349   // Add enumerators to enumeration type.
1350   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1351     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1352     if (Enum) {
1353       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1354       StringRef Name = Enum->getName();
1355       addString(Enumerator, dwarf::DW_AT_name, Name);
1356       int64_t Value = Enum->getValue();
1357       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1358               Value);
1359     }
1360   }
1361   const DIType *DTy = resolve(CTy->getBaseType());
1362   if (DTy) {
1363     addType(Buffer, DTy);
1364     addFlag(Buffer, dwarf::DW_AT_enum_class);
1365   }
1366 }
1367 
1368 void DwarfUnit::constructContainingTypeDIEs() {
1369   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1370        CI != CE; ++CI) {
1371     DIE &SPDie = *CI->first;
1372     const DINode *D = CI->second;
1373     if (!D)
1374       continue;
1375     DIE *NDie = getDIE(D);
1376     if (!NDie)
1377       continue;
1378     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1379   }
1380 }
1381 
1382 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1383   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1384   StringRef Name = DT->getName();
1385   if (!Name.empty())
1386     addString(MemberDie, dwarf::DW_AT_name, Name);
1387 
1388   addType(MemberDie, resolve(DT->getBaseType()));
1389 
1390   addSourceLine(MemberDie, DT);
1391 
1392   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1393 
1394     // For C++, virtual base classes are not at fixed offset. Use following
1395     // expression to extract appropriate offset from vtable.
1396     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1397 
1398     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1399     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1400     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1401     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1402     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1403     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1404     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1405     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1406 
1407     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1408   } else {
1409     uint64_t Size = DT->getSizeInBits();
1410     uint64_t FieldSize = DD->getBaseTypeSize(DT);
1411     uint32_t AlignInBytes = DT->getAlignInBytes();
1412     uint64_t OffsetInBytes;
1413 
1414     bool IsBitfield = FieldSize && Size != FieldSize;
1415     if (IsBitfield) {
1416       // Handle bitfield, assume bytes are 8 bits.
1417       if (DD->useDWARF2Bitfields())
1418         addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1419       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1420 
1421       uint64_t Offset = DT->getOffsetInBits();
1422       // We can't use DT->getAlignInBits() here: AlignInBits for member type
1423       // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1424       // which can't be done with bitfields. Thus we use FieldSize here.
1425       uint32_t AlignInBits = FieldSize;
1426       uint32_t AlignMask = ~(AlignInBits - 1);
1427       // The bits from the start of the storage unit to the start of the field.
1428       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1429       // The byte offset of the field's aligned storage unit inside the struct.
1430       OffsetInBytes = (Offset - StartBitOffset) / 8;
1431 
1432       if (DD->useDWARF2Bitfields()) {
1433         uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1434         uint64_t FieldOffset = (HiMark - FieldSize);
1435         Offset -= FieldOffset;
1436 
1437         // Maybe we need to work from the other end.
1438         if (Asm->getDataLayout().isLittleEndian())
1439           Offset = FieldSize - (Offset + Size);
1440 
1441         addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1442         OffsetInBytes = FieldOffset >> 3;
1443       } else {
1444         addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1445       }
1446     } else {
1447       // This is not a bitfield.
1448       OffsetInBytes = DT->getOffsetInBits() / 8;
1449       if (AlignInBytes)
1450         addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1451                 AlignInBytes);
1452     }
1453 
1454     if (DD->getDwarfVersion() <= 2) {
1455       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1456       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1457       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1458       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1459     } else if (!IsBitfield || DD->useDWARF2Bitfields())
1460       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1461               OffsetInBytes);
1462   }
1463 
1464   if (DT->isProtected())
1465     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1466             dwarf::DW_ACCESS_protected);
1467   else if (DT->isPrivate())
1468     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1469             dwarf::DW_ACCESS_private);
1470   // Otherwise C++ member and base classes are considered public.
1471   else if (DT->isPublic())
1472     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1473             dwarf::DW_ACCESS_public);
1474   if (DT->isVirtual())
1475     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1476             dwarf::DW_VIRTUALITY_virtual);
1477 
1478   // Objective-C properties.
1479   if (DINode *PNode = DT->getObjCProperty())
1480     if (DIE *PDie = getDIE(PNode))
1481       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1482                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1483 
1484   if (DT->isArtificial())
1485     addFlag(MemberDie, dwarf::DW_AT_artificial);
1486 }
1487 
1488 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1489   if (!DT)
1490     return nullptr;
1491 
1492   // Construct the context before querying for the existence of the DIE in case
1493   // such construction creates the DIE.
1494   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1495   assert(dwarf::isType(ContextDIE->getTag()) &&
1496          "Static member should belong to a type.");
1497 
1498   if (DIE *StaticMemberDIE = getDIE(DT))
1499     return StaticMemberDIE;
1500 
1501   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1502 
1503   const DIType *Ty = resolve(DT->getBaseType());
1504 
1505   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1506   addType(StaticMemberDIE, Ty);
1507   addSourceLine(StaticMemberDIE, DT);
1508   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1509   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1510 
1511   // FIXME: We could omit private if the parent is a class_type, and
1512   // public if the parent is something else.
1513   if (DT->isProtected())
1514     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1515             dwarf::DW_ACCESS_protected);
1516   else if (DT->isPrivate())
1517     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1518             dwarf::DW_ACCESS_private);
1519   else if (DT->isPublic())
1520     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1521             dwarf::DW_ACCESS_public);
1522 
1523   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1524     addConstantValue(StaticMemberDIE, CI, Ty);
1525   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1526     addConstantFPValue(StaticMemberDIE, CFP);
1527 
1528   if (uint32_t AlignInBytes = DT->getAlignInBytes())
1529     addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1530             AlignInBytes);
1531 
1532   return &StaticMemberDIE;
1533 }
1534 
1535 void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1536   // Emit size of content not including length itself
1537   Asm->OutStreamer->AddComment("Length of Unit");
1538   Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize());
1539 
1540   Asm->OutStreamer->AddComment("DWARF version number");
1541   unsigned Version = DD->getDwarfVersion();
1542   Asm->EmitInt16(Version);
1543 
1544   // DWARF v5 reorders the address size and adds a unit type.
1545   if (Version >= 5) {
1546     Asm->OutStreamer->AddComment("DWARF Unit Type");
1547     Asm->EmitInt8(UT);
1548     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1549     Asm->EmitInt8(Asm->MAI->getCodePointerSize());
1550   }
1551 
1552   // We share one abbreviations table across all units so it's always at the
1553   // start of the section. Use a relocatable offset where needed to ensure
1554   // linking doesn't invalidate that offset.
1555   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1556   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1557   if (UseOffsets)
1558     Asm->EmitInt32(0);
1559   else
1560     Asm->emitDwarfSymbolReference(
1561         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1562 
1563   if (Version <= 4) {
1564     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1565     Asm->EmitInt8(Asm->MAI->getCodePointerSize());
1566   }
1567 }
1568 
1569 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1570   DwarfUnit::emitCommonHeader(UseOffsets,
1571                               DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1572                                                   : dwarf::DW_UT_type);
1573   Asm->OutStreamer->AddComment("Type Signature");
1574   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1575   Asm->OutStreamer->AddComment("Type DIE Offset");
1576   // In a skeleton type unit there is no type DIE so emit a zero offset.
1577   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1578                                  sizeof(Ty->getOffset()));
1579 }
1580 
1581 bool DwarfTypeUnit::isDwoUnit() const {
1582   // Since there are no skeleton type units, all type units are dwo type units
1583   // when split DWARF is being used.
1584   return DD->useSplitDwarf();
1585 }
1586 
1587 void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1588                                   const DIScope *Context) {
1589   getCU().addGlobalNameForTypeUnit(Name, Context);
1590 }
1591 
1592 void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1593                                   const DIScope *Context) {
1594   getCU().addGlobalTypeUnitType(Ty, Context);
1595 }
1596