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