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/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/MCAsmInfo.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MachineLocation.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 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     if (auto *ContainingType =
964             dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
965       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
966                   *getOrCreateTypeDIE(ContainingType));
967 
968     if (CTy->isObjcClassComplete())
969       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
970 
971     // Add template parameters to a class, structure or union types.
972     // FIXME: The support isn't in the metadata for this yet.
973     if (Tag == dwarf::DW_TAG_class_type ||
974         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
975       addTemplateParams(Buffer, CTy->getTemplateParams());
976 
977     break;
978   }
979   default:
980     break;
981   }
982 
983   // Add name if not anonymous or intermediate type.
984   if (!Name.empty())
985     addString(Buffer, dwarf::DW_AT_name, Name);
986 
987   if (Tag == dwarf::DW_TAG_enumeration_type ||
988       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
989       Tag == dwarf::DW_TAG_union_type) {
990     // Add size if non-zero (derived types might be zero-sized.)
991     // TODO: Do we care about size for enum forward declarations?
992     if (Size)
993       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
994     else if (!CTy->isForwardDecl())
995       // Add zero size if it is not a forward declaration.
996       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
997 
998     // If we're a forward decl, say so.
999     if (CTy->isForwardDecl())
1000       addFlag(Buffer, dwarf::DW_AT_declaration);
1001 
1002     // Add source line info if available.
1003     if (!CTy->isForwardDecl())
1004       addSourceLine(Buffer, CTy);
1005 
1006     // No harm in adding the runtime language to the declaration.
1007     unsigned RLang = CTy->getRuntimeLang();
1008     if (RLang)
1009       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1010               RLang);
1011 
1012     // Add align info if available.
1013     if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1014       addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1015               AlignInBytes);
1016   }
1017 }
1018 
1019 void DwarfUnit::constructTemplateTypeParameterDIE(
1020     DIE &Buffer, const DITemplateTypeParameter *TP) {
1021   DIE &ParamDIE =
1022       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1023   // Add the type if it exists, it could be void and therefore no type.
1024   if (TP->getType())
1025     addType(ParamDIE, resolve(TP->getType()));
1026   if (!TP->getName().empty())
1027     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1028 }
1029 
1030 void DwarfUnit::constructTemplateValueParameterDIE(
1031     DIE &Buffer, const DITemplateValueParameter *VP) {
1032   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1033 
1034   // Add the type if there is one, template template and template parameter
1035   // packs will not have a type.
1036   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1037     addType(ParamDIE, resolve(VP->getType()));
1038   if (!VP->getName().empty())
1039     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1040   if (Metadata *Val = VP->getValue()) {
1041     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1042       addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1043     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1044       // We cannot describe the location of dllimport'd entities: the
1045       // computation of their address requires loads from the IAT.
1046       if (!GV->hasDLLImportStorageClass()) {
1047         // For declaration non-type template parameters (such as global values
1048         // and functions)
1049         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1050         addOpAddress(*Loc, Asm->getSymbol(GV));
1051         // Emit DW_OP_stack_value to use the address as the immediate value of
1052         // the parameter, rather than a pointer to it.
1053         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1054         addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1055       }
1056     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1057       assert(isa<MDString>(Val));
1058       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1059                 cast<MDString>(Val)->getString());
1060     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1061       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1062     }
1063   }
1064 }
1065 
1066 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1067   // Construct the context before querying for the existence of the DIE in case
1068   // such construction creates the DIE.
1069   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1070 
1071   if (DIE *NDie = getDIE(NS))
1072     return NDie;
1073   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1074 
1075   StringRef Name = NS->getName();
1076   if (!Name.empty())
1077     addString(NDie, dwarf::DW_AT_name, NS->getName());
1078   else
1079     Name = "(anonymous namespace)";
1080   DD->addAccelNamespace(Name, NDie);
1081   addGlobalName(Name, NDie, NS->getScope());
1082   if (NS->getExportSymbols())
1083     addFlag(NDie, dwarf::DW_AT_export_symbols);
1084   return &NDie;
1085 }
1086 
1087 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1088   // Construct the context before querying for the existence of the DIE in case
1089   // such construction creates the DIE.
1090   DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1091 
1092   if (DIE *MDie = getDIE(M))
1093     return MDie;
1094   DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1095 
1096   if (!M->getName().empty()) {
1097     addString(MDie, dwarf::DW_AT_name, M->getName());
1098     addGlobalName(M->getName(), MDie, M->getScope());
1099   }
1100   if (!M->getConfigurationMacros().empty())
1101     addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1102               M->getConfigurationMacros());
1103   if (!M->getIncludePath().empty())
1104     addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1105   if (!M->getISysRoot().empty())
1106     addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1107 
1108   return &MDie;
1109 }
1110 
1111 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1112   // Construct the context before querying for the existence of the DIE in case
1113   // such construction creates the DIE (as is the case for member function
1114   // declarations).
1115   DIE *ContextDIE =
1116       Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1117 
1118   if (DIE *SPDie = getDIE(SP))
1119     return SPDie;
1120 
1121   if (auto *SPDecl = SP->getDeclaration()) {
1122     if (!Minimal) {
1123       // Add subprogram definitions to the CU die directly.
1124       ContextDIE = &getUnitDie();
1125       // Build the decl now to ensure it precedes the definition.
1126       getOrCreateSubprogramDIE(SPDecl);
1127     }
1128   }
1129 
1130   // DW_TAG_inlined_subroutine may refer to this DIE.
1131   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1132 
1133   // Stop here and fill this in later, depending on whether or not this
1134   // subprogram turns out to have inlined instances or not.
1135   if (SP->isDefinition())
1136     return &SPDie;
1137 
1138   applySubprogramAttributes(SP, SPDie);
1139   return &SPDie;
1140 }
1141 
1142 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1143                                                     DIE &SPDie) {
1144   DIE *DeclDie = nullptr;
1145   StringRef DeclLinkageName;
1146   if (auto *SPDecl = SP->getDeclaration()) {
1147     DeclDie = getDIE(SPDecl);
1148     assert(DeclDie && "This DIE should've already been constructed when the "
1149                       "definition DIE was created in "
1150                       "getOrCreateSubprogramDIE");
1151     // Look at the Decl's linkage name only if we emitted it.
1152     if (DD->useAllLinkageNames())
1153       DeclLinkageName = SPDecl->getLinkageName();
1154     unsigned DeclID =
1155         getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1156     unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1157     if (DeclID != DefID)
1158       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1159 
1160     if (SP->getLine() != SPDecl->getLine())
1161       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1162   }
1163 
1164   // Add function template parameters.
1165   addTemplateParams(SPDie, SP->getTemplateParams());
1166 
1167   // Add the linkage name if we have one and it isn't in the Decl.
1168   StringRef LinkageName = SP->getLinkageName();
1169   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1170           LinkageName == DeclLinkageName) &&
1171          "decl has a linkage name and it is different");
1172   if (DeclLinkageName.empty() &&
1173       // Always emit it for abstract subprograms.
1174       (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1175     addLinkageName(SPDie, LinkageName);
1176 
1177   if (!DeclDie)
1178     return false;
1179 
1180   // Refer to the function declaration where all the other attributes will be
1181   // found.
1182   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1183   return true;
1184 }
1185 
1186 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1187                                           bool SkipSPAttributes) {
1188   // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1189   // and its source location.
1190   bool SkipSPSourceLocation = SkipSPAttributes &&
1191                               !CUNode->getDebugInfoForProfiling();
1192   if (!SkipSPSourceLocation)
1193     if (applySubprogramDefinitionAttributes(SP, SPDie))
1194       return;
1195 
1196   // Constructors and operators for anonymous aggregates do not have names.
1197   if (!SP->getName().empty())
1198     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1199 
1200   if (!SkipSPSourceLocation)
1201     addSourceLine(SPDie, SP);
1202 
1203   // Skip the rest of the attributes under -gmlt to save space.
1204   if (SkipSPAttributes)
1205     return;
1206 
1207   // Add the prototype if we have a prototype and we have a C like
1208   // language.
1209   uint16_t Language = getLanguage();
1210   if (SP->isPrototyped() &&
1211       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1212        Language == dwarf::DW_LANG_ObjC))
1213     addFlag(SPDie, dwarf::DW_AT_prototyped);
1214 
1215   unsigned CC = 0;
1216   DITypeRefArray Args;
1217   if (const DISubroutineType *SPTy = SP->getType()) {
1218     Args = SPTy->getTypeArray();
1219     CC = SPTy->getCC();
1220   }
1221 
1222   // Add a DW_AT_calling_convention if this has an explicit convention.
1223   if (CC && CC != dwarf::DW_CC_normal)
1224     addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1225 
1226   // Add a return type. If this is a type like a C/C++ void type we don't add a
1227   // return type.
1228   if (Args.size())
1229     if (auto Ty = resolve(Args[0]))
1230       addType(SPDie, Ty);
1231 
1232   unsigned VK = SP->getVirtuality();
1233   if (VK) {
1234     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1235     if (SP->getVirtualIndex() != -1u) {
1236       DIELoc *Block = getDIELoc();
1237       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1238       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1239       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1240     }
1241     ContainingTypeMap.insert(
1242         std::make_pair(&SPDie, resolve(SP->getContainingType())));
1243   }
1244 
1245   if (!SP->isDefinition()) {
1246     addFlag(SPDie, dwarf::DW_AT_declaration);
1247 
1248     // Add arguments. Do not add arguments for subprogram definition. They will
1249     // be handled while processing variables.
1250     constructSubprogramArguments(SPDie, Args);
1251   }
1252 
1253   addThrownTypes(SPDie, SP->getThrownTypes());
1254 
1255   if (SP->isArtificial())
1256     addFlag(SPDie, dwarf::DW_AT_artificial);
1257 
1258   if (!SP->isLocalToUnit())
1259     addFlag(SPDie, dwarf::DW_AT_external);
1260 
1261   if (DD->useAppleExtensionAttributes()) {
1262     if (SP->isOptimized())
1263       addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1264 
1265     if (unsigned isa = Asm->getISAEncoding())
1266       addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1267   }
1268 
1269   if (SP->isLValueReference())
1270     addFlag(SPDie, dwarf::DW_AT_reference);
1271 
1272   if (SP->isRValueReference())
1273     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1274 
1275   if (SP->isNoReturn())
1276     addFlag(SPDie, dwarf::DW_AT_noreturn);
1277 
1278   if (SP->isProtected())
1279     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1280             dwarf::DW_ACCESS_protected);
1281   else if (SP->isPrivate())
1282     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1283             dwarf::DW_ACCESS_private);
1284   else if (SP->isPublic())
1285     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1286             dwarf::DW_ACCESS_public);
1287 
1288   if (SP->isExplicit())
1289     addFlag(SPDie, dwarf::DW_AT_explicit);
1290 
1291   if (SP->isMainSubprogram())
1292     addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1293 }
1294 
1295 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1296                                      DIE *IndexTy) {
1297   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1298   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1299 
1300   // The LowerBound value defines the lower bounds which is typically zero for
1301   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1302   // Count == -1 then the array is unbounded and we do not emit
1303   // DW_AT_lower_bound and DW_AT_count attributes.
1304   int64_t LowerBound = SR->getLowerBound();
1305   int64_t DefaultLowerBound = getDefaultLowerBound();
1306   int64_t Count = SR->getCount();
1307 
1308   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1309     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1310 
1311   if (Count != -1)
1312     // FIXME: An unbounded array should reference the expression that defines
1313     // the array.
1314     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1315 }
1316 
1317 DIE *DwarfUnit::getIndexTyDie() {
1318   if (IndexTyDie)
1319     return IndexTyDie;
1320   // Construct an integer type to use for indexes.
1321   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1322   addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1323   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1324   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1325           dwarf::DW_ATE_unsigned);
1326   return IndexTyDie;
1327 }
1328 
1329 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1330   if (CTy->isVector())
1331     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1332 
1333   // Emit the element type.
1334   addType(Buffer, resolve(CTy->getBaseType()));
1335 
1336   // Get an anonymous type for index type.
1337   // FIXME: This type should be passed down from the front end
1338   // as different languages may have different sizes for indexes.
1339   DIE *IdxTy = getIndexTyDie();
1340 
1341   // Add subranges to array type.
1342   DINodeArray Elements = CTy->getElements();
1343   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1344     // FIXME: Should this really be such a loose cast?
1345     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1346       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1347         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1348   }
1349 }
1350 
1351 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1352   DINodeArray Elements = CTy->getElements();
1353 
1354   // Add enumerators to enumeration type.
1355   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1356     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1357     if (Enum) {
1358       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1359       StringRef Name = Enum->getName();
1360       addString(Enumerator, dwarf::DW_AT_name, Name);
1361       int64_t Value = Enum->getValue();
1362       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1363               Value);
1364     }
1365   }
1366   const DIType *DTy = resolve(CTy->getBaseType());
1367   if (DTy) {
1368     addType(Buffer, DTy);
1369     addFlag(Buffer, dwarf::DW_AT_enum_class);
1370   }
1371 }
1372 
1373 void DwarfUnit::constructContainingTypeDIEs() {
1374   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1375        CI != CE; ++CI) {
1376     DIE &SPDie = *CI->first;
1377     const DINode *D = CI->second;
1378     if (!D)
1379       continue;
1380     DIE *NDie = getDIE(D);
1381     if (!NDie)
1382       continue;
1383     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1384   }
1385 }
1386 
1387 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1388   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1389   StringRef Name = DT->getName();
1390   if (!Name.empty())
1391     addString(MemberDie, dwarf::DW_AT_name, Name);
1392 
1393   addType(MemberDie, resolve(DT->getBaseType()));
1394 
1395   addSourceLine(MemberDie, DT);
1396 
1397   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1398 
1399     // For C++, virtual base classes are not at fixed offset. Use following
1400     // expression to extract appropriate offset from vtable.
1401     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1402 
1403     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1404     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1405     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1406     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1407     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1408     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1409     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1410     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1411 
1412     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1413   } else {
1414     uint64_t Size = DT->getSizeInBits();
1415     uint64_t FieldSize = DD->getBaseTypeSize(DT);
1416     uint32_t AlignInBytes = DT->getAlignInBytes();
1417     uint64_t OffsetInBytes;
1418 
1419     bool IsBitfield = FieldSize && Size != FieldSize;
1420     if (IsBitfield) {
1421       // Handle bitfield, assume bytes are 8 bits.
1422       if (DD->useDWARF2Bitfields())
1423         addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1424       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1425 
1426       uint64_t Offset = DT->getOffsetInBits();
1427       // We can't use DT->getAlignInBits() here: AlignInBits for member type
1428       // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1429       // which can't be done with bitfields. Thus we use FieldSize here.
1430       uint32_t AlignInBits = FieldSize;
1431       uint32_t AlignMask = ~(AlignInBits - 1);
1432       // The bits from the start of the storage unit to the start of the field.
1433       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1434       // The byte offset of the field's aligned storage unit inside the struct.
1435       OffsetInBytes = (Offset - StartBitOffset) / 8;
1436 
1437       if (DD->useDWARF2Bitfields()) {
1438         uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1439         uint64_t FieldOffset = (HiMark - FieldSize);
1440         Offset -= FieldOffset;
1441 
1442         // Maybe we need to work from the other end.
1443         if (Asm->getDataLayout().isLittleEndian())
1444           Offset = FieldSize - (Offset + Size);
1445 
1446         addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1447         OffsetInBytes = FieldOffset >> 3;
1448       } else {
1449         addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1450       }
1451     } else {
1452       // This is not a bitfield.
1453       OffsetInBytes = DT->getOffsetInBits() / 8;
1454       if (AlignInBytes)
1455         addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1456                 AlignInBytes);
1457     }
1458 
1459     if (DD->getDwarfVersion() <= 2) {
1460       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1461       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1462       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1463       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1464     } else if (!IsBitfield || DD->useDWARF2Bitfields())
1465       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1466               OffsetInBytes);
1467   }
1468 
1469   if (DT->isProtected())
1470     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1471             dwarf::DW_ACCESS_protected);
1472   else if (DT->isPrivate())
1473     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1474             dwarf::DW_ACCESS_private);
1475   // Otherwise C++ member and base classes are considered public.
1476   else if (DT->isPublic())
1477     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1478             dwarf::DW_ACCESS_public);
1479   if (DT->isVirtual())
1480     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1481             dwarf::DW_VIRTUALITY_virtual);
1482 
1483   // Objective-C properties.
1484   if (DINode *PNode = DT->getObjCProperty())
1485     if (DIE *PDie = getDIE(PNode))
1486       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1487                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1488 
1489   if (DT->isArtificial())
1490     addFlag(MemberDie, dwarf::DW_AT_artificial);
1491 }
1492 
1493 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1494   if (!DT)
1495     return nullptr;
1496 
1497   // Construct the context before querying for the existence of the DIE in case
1498   // such construction creates the DIE.
1499   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1500   assert(dwarf::isType(ContextDIE->getTag()) &&
1501          "Static member should belong to a type.");
1502 
1503   if (DIE *StaticMemberDIE = getDIE(DT))
1504     return StaticMemberDIE;
1505 
1506   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1507 
1508   const DIType *Ty = resolve(DT->getBaseType());
1509 
1510   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1511   addType(StaticMemberDIE, Ty);
1512   addSourceLine(StaticMemberDIE, DT);
1513   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1514   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1515 
1516   // FIXME: We could omit private if the parent is a class_type, and
1517   // public if the parent is something else.
1518   if (DT->isProtected())
1519     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1520             dwarf::DW_ACCESS_protected);
1521   else if (DT->isPrivate())
1522     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1523             dwarf::DW_ACCESS_private);
1524   else if (DT->isPublic())
1525     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1526             dwarf::DW_ACCESS_public);
1527 
1528   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1529     addConstantValue(StaticMemberDIE, CI, Ty);
1530   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1531     addConstantFPValue(StaticMemberDIE, CFP);
1532 
1533   if (uint32_t AlignInBytes = DT->getAlignInBytes())
1534     addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1535             AlignInBytes);
1536 
1537   return &StaticMemberDIE;
1538 }
1539 
1540 void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1541   // Emit size of content not including length itself
1542   Asm->OutStreamer->AddComment("Length of Unit");
1543   Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize());
1544 
1545   Asm->OutStreamer->AddComment("DWARF version number");
1546   unsigned Version = DD->getDwarfVersion();
1547   Asm->EmitInt16(Version);
1548 
1549   // DWARF v5 reorders the address size and adds a unit type.
1550   if (Version >= 5) {
1551     Asm->OutStreamer->AddComment("DWARF Unit Type");
1552     Asm->EmitInt8(UT);
1553     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1554     Asm->EmitInt8(Asm->MAI->getCodePointerSize());
1555   }
1556 
1557   // We share one abbreviations table across all units so it's always at the
1558   // start of the section. Use a relocatable offset where needed to ensure
1559   // linking doesn't invalidate that offset.
1560   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1561   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1562   if (UseOffsets)
1563     Asm->EmitInt32(0);
1564   else
1565     Asm->emitDwarfSymbolReference(
1566         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1567 
1568   if (Version <= 4) {
1569     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1570     Asm->EmitInt8(Asm->MAI->getCodePointerSize());
1571   }
1572 }
1573 
1574 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1575   DwarfUnit::emitCommonHeader(UseOffsets,
1576                               DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1577                                                   : dwarf::DW_UT_type);
1578   Asm->OutStreamer->AddComment("Type Signature");
1579   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1580   Asm->OutStreamer->AddComment("Type DIE Offset");
1581   // In a skeleton type unit there is no type DIE so emit a zero offset.
1582   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1583                                  sizeof(Ty->getOffset()));
1584 }
1585 
1586 DIE::value_iterator
1587 DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
1588                            const MCSymbol *Hi, const MCSymbol *Lo) {
1589   return Die.addValue(DIEValueAllocator, Attribute,
1590                       DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1591                                                  : dwarf::DW_FORM_data4,
1592                       new (DIEValueAllocator) DIEDelta(Hi, Lo));
1593 }
1594 
1595 DIE::value_iterator
1596 DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
1597                            const MCSymbol *Label, const MCSymbol *Sec) {
1598   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1599     return addLabel(Die, Attribute,
1600                     DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1601                                                : dwarf::DW_FORM_data4,
1602                     Label);
1603   return addSectionDelta(Die, Attribute, Label, Sec);
1604 }
1605 
1606 bool DwarfTypeUnit::isDwoUnit() const {
1607   // Since there are no skeleton type units, all type units are dwo type units
1608   // when split DWARF is being used.
1609   return DD->useSplitDwarf();
1610 }
1611 
1612 void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1613                                   const DIScope *Context) {
1614   getCU().addGlobalNameForTypeUnit(Name, Context);
1615 }
1616 
1617 void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1618                                   const DIScope *Context) {
1619   getCU().addGlobalTypeUnitType(Ty, Context);
1620 }
1621 
1622 const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
1623   if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1624     return nullptr;
1625   if (isDwoUnit())
1626     return nullptr;
1627   return getSection()->getBeginSymbol();
1628 }
1629