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