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