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