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