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