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