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 *ST = dyn_cast<DIStringType>(Ty))
639     constructTypeDIE(TyDIE, ST);
640   else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
641     constructTypeDIE(TyDIE, STy);
642   else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
643     if (DD->generateTypeUnits() && !Ty->isForwardDecl() &&
644         (Ty->getRawName() || CTy->getRawIdentifier())) {
645       // Skip updating the accelerator tables since this is not the full type.
646       if (MDString *TypeId = CTy->getRawIdentifier())
647         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
648       else {
649         auto X = DD->enterNonTypeUnitContext();
650         finishNonUnitTypeDIE(TyDIE, CTy);
651       }
652       return &TyDIE;
653     }
654     constructTypeDIE(TyDIE, CTy);
655   } else {
656     constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
657   }
658 
659   return &TyDIE;
660 }
661 
662 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
663   if (!TyNode)
664     return nullptr;
665 
666   auto *Ty = cast<DIType>(TyNode);
667 
668   // DW_TAG_restrict_type is not supported in DWARF2
669   if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
670     return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType());
671 
672   // DW_TAG_atomic_type is not supported in DWARF < 5
673   if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
674     return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType());
675 
676   // Construct the context before querying for the existence of the DIE in case
677   // such construction creates the DIE.
678   auto *Context = Ty->getScope();
679   DIE *ContextDIE = getOrCreateContextDIE(Context);
680   assert(ContextDIE);
681 
682   if (DIE *TyDIE = getDIE(Ty))
683     return TyDIE;
684 
685   return static_cast<DwarfUnit *>(ContextDIE->getUnit())
686       ->createTypeDIE(Context, *ContextDIE, Ty);
687 }
688 
689 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
690                                         const DIType *Ty, const DIE &TyDIE) {
691   if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
692     bool IsImplementation = false;
693     if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
694       // A runtime language of 0 actually means C/C++ and that any
695       // non-negative value is some version of Objective-C/C++.
696       IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
697     }
698     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
699     DD->addAccelType(*CUNode, Ty->getName(), TyDIE, Flags);
700 
701     if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
702         isa<DINamespace>(Context) || isa<DICommonBlock>(Context))
703       addGlobalType(Ty, TyDIE, Context);
704   }
705 }
706 
707 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
708                         dwarf::Attribute Attribute) {
709   assert(Ty && "Trying to add a type that doesn't exist?");
710   addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
711 }
712 
713 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
714   if (!Context)
715     return "";
716 
717   // FIXME: Decide whether to implement this for non-C++ languages.
718   if (!dwarf::isCPlusPlus((dwarf::SourceLanguage)getLanguage()))
719     return "";
720 
721   std::string CS;
722   SmallVector<const DIScope *, 1> Parents;
723   while (!isa<DICompileUnit>(Context)) {
724     Parents.push_back(Context);
725     if (const DIScope *S = Context->getScope())
726       Context = S;
727     else
728       // Structure, etc types will have a NULL context if they're at the top
729       // level.
730       break;
731   }
732 
733   // Reverse iterate over our list to go from the outermost construct to the
734   // innermost.
735   for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
736     StringRef Name = Ctx->getName();
737     if (Name.empty() && isa<DINamespace>(Ctx))
738       Name = "(anonymous namespace)";
739     if (!Name.empty()) {
740       CS += Name;
741       CS += "::";
742     }
743   }
744   return CS;
745 }
746 
747 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
748   // Get core information.
749   StringRef Name = BTy->getName();
750   // Add name if not anonymous or intermediate type.
751   if (!Name.empty())
752     addString(Buffer, dwarf::DW_AT_name, Name);
753 
754   // An unspecified type only has a name attribute.
755   if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
756     return;
757 
758   if (BTy->getTag() != dwarf::DW_TAG_string_type)
759     addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
760             BTy->getEncoding());
761 
762   uint64_t Size = BTy->getSizeInBits() >> 3;
763   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
764 
765   if (BTy->isBigEndian())
766     addUInt(Buffer, dwarf::DW_AT_endianity, None, dwarf::DW_END_big);
767   else if (BTy->isLittleEndian())
768     addUInt(Buffer, dwarf::DW_AT_endianity, None, dwarf::DW_END_little);
769 }
770 
771 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIStringType *STy) {
772   // Get core information.
773   StringRef Name = STy->getName();
774   // Add name if not anonymous or intermediate type.
775   if (!Name.empty())
776     addString(Buffer, dwarf::DW_AT_name, Name);
777 
778   if (DIVariable *Var = STy->getStringLength()) {
779     if (auto *VarDIE = getDIE(Var))
780       addDIEEntry(Buffer, dwarf::DW_AT_string_length, *VarDIE);
781   } else {
782     uint64_t Size = STy->getSizeInBits() >> 3;
783     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
784   }
785 
786   if (STy->getEncoding()) {
787     // For eventual Unicode support.
788     addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
789             STy->getEncoding());
790   }
791 }
792 
793 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
794   // Get core information.
795   StringRef Name = DTy->getName();
796   uint64_t Size = DTy->getSizeInBits() >> 3;
797   uint16_t Tag = Buffer.getTag();
798 
799   // Map to main type, void will not have a type.
800   const DIType *FromTy = DTy->getBaseType();
801   if (FromTy)
802     addType(Buffer, FromTy);
803 
804   // Add name if not anonymous or intermediate type.
805   if (!Name.empty())
806     addString(Buffer, dwarf::DW_AT_name, Name);
807 
808   // If alignment is specified for a typedef , create and insert DW_AT_alignment
809   // attribute in DW_TAG_typedef DIE.
810   if (Tag == dwarf::DW_TAG_typedef && DD->getDwarfVersion() >= 5) {
811     uint32_t AlignInBytes = DTy->getAlignInBytes();
812     if (AlignInBytes > 0)
813       addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
814               AlignInBytes);
815   }
816 
817   // Add size if non-zero (derived types might be zero-sized.)
818   if (Size && Tag != dwarf::DW_TAG_pointer_type
819            && Tag != dwarf::DW_TAG_ptr_to_member_type
820            && Tag != dwarf::DW_TAG_reference_type
821            && Tag != dwarf::DW_TAG_rvalue_reference_type)
822     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
823 
824   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
825     addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
826                 *getOrCreateTypeDIE(cast<DIDerivedType>(DTy)->getClassType()));
827   // Add source line info if available and TyDesc is not a forward declaration.
828   if (!DTy->isForwardDecl())
829     addSourceLine(Buffer, DTy);
830 
831   // If DWARF address space value is other than None, add it.  The IR
832   // verifier checks that DWARF address space only exists for pointer
833   // or reference types.
834   if (DTy->getDWARFAddressSpace())
835     addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
836             DTy->getDWARFAddressSpace().getValue());
837 }
838 
839 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
840   for (unsigned i = 1, N = Args.size(); i < N; ++i) {
841     const DIType *Ty = Args[i];
842     if (!Ty) {
843       assert(i == N-1 && "Unspecified parameter must be the last argument");
844       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
845     } else {
846       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
847       addType(Arg, Ty);
848       if (Ty->isArtificial())
849         addFlag(Arg, dwarf::DW_AT_artificial);
850     }
851   }
852 }
853 
854 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
855   // Add return type.  A void return won't have a type.
856   auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
857   if (Elements.size())
858     if (auto RTy = Elements[0])
859       addType(Buffer, RTy);
860 
861   bool isPrototyped = true;
862   if (Elements.size() == 2 && !Elements[1])
863     isPrototyped = false;
864 
865   constructSubprogramArguments(Buffer, Elements);
866 
867   // Add prototype flag if we're dealing with a C language and the function has
868   // been prototyped.
869   uint16_t Language = getLanguage();
870   if (isPrototyped &&
871       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
872        Language == dwarf::DW_LANG_ObjC))
873     addFlag(Buffer, dwarf::DW_AT_prototyped);
874 
875   // Add a DW_AT_calling_convention if this has an explicit convention.
876   if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
877     addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
878             CTy->getCC());
879 
880   if (CTy->isLValueReference())
881     addFlag(Buffer, dwarf::DW_AT_reference);
882 
883   if (CTy->isRValueReference())
884     addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
885 }
886 
887 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
888   // Add name if not anonymous or intermediate type.
889   StringRef Name = CTy->getName();
890 
891   uint64_t Size = CTy->getSizeInBits() >> 3;
892   uint16_t Tag = Buffer.getTag();
893 
894   switch (Tag) {
895   case dwarf::DW_TAG_array_type:
896     constructArrayTypeDIE(Buffer, CTy);
897     break;
898   case dwarf::DW_TAG_enumeration_type:
899     constructEnumTypeDIE(Buffer, CTy);
900     break;
901   case dwarf::DW_TAG_variant_part:
902   case dwarf::DW_TAG_structure_type:
903   case dwarf::DW_TAG_union_type:
904   case dwarf::DW_TAG_class_type: {
905     // Emit the discriminator for a variant part.
906     DIDerivedType *Discriminator = nullptr;
907     if (Tag == dwarf::DW_TAG_variant_part) {
908       Discriminator = CTy->getDiscriminator();
909       if (Discriminator) {
910         // DWARF says:
911         //    If the variant part has a discriminant, the discriminant is
912         //    represented by a separate debugging information entry which is
913         //    a child of the variant part entry.
914         DIE &DiscMember = constructMemberDIE(Buffer, Discriminator);
915         addDIEEntry(Buffer, dwarf::DW_AT_discr, DiscMember);
916       }
917     }
918 
919     // Add template parameters to a class, structure or union types.
920     if (Tag == dwarf::DW_TAG_class_type ||
921         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
922       addTemplateParams(Buffer, CTy->getTemplateParams());
923 
924     // Add elements to structure type.
925     DINodeArray Elements = CTy->getElements();
926     for (const auto *Element : Elements) {
927       if (!Element)
928         continue;
929       if (auto *SP = dyn_cast<DISubprogram>(Element))
930         getOrCreateSubprogramDIE(SP);
931       else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
932         if (DDTy->getTag() == dwarf::DW_TAG_friend) {
933           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
934           addType(ElemDie, DDTy->getBaseType(), dwarf::DW_AT_friend);
935         } else if (DDTy->isStaticMember()) {
936           getOrCreateStaticMemberDIE(DDTy);
937         } else if (Tag == dwarf::DW_TAG_variant_part) {
938           // When emitting a variant part, wrap each member in
939           // DW_TAG_variant.
940           DIE &Variant = createAndAddDIE(dwarf::DW_TAG_variant, Buffer);
941           if (const ConstantInt *CI =
942               dyn_cast_or_null<ConstantInt>(DDTy->getDiscriminantValue())) {
943             if (isUnsignedDIType(DD, Discriminator->getBaseType()))
944               addUInt(Variant, dwarf::DW_AT_discr_value, None, CI->getZExtValue());
945             else
946               addSInt(Variant, dwarf::DW_AT_discr_value, None, CI->getSExtValue());
947           }
948           constructMemberDIE(Variant, DDTy);
949         } else {
950           constructMemberDIE(Buffer, DDTy);
951         }
952       } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
953         DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
954         StringRef PropertyName = Property->getName();
955         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
956         if (Property->getType())
957           addType(ElemDie, Property->getType());
958         addSourceLine(ElemDie, Property);
959         StringRef GetterName = Property->getGetterName();
960         if (!GetterName.empty())
961           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
962         StringRef SetterName = Property->getSetterName();
963         if (!SetterName.empty())
964           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
965         if (unsigned PropertyAttributes = Property->getAttributes())
966           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
967                   PropertyAttributes);
968       } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
969         if (Composite->getTag() == dwarf::DW_TAG_variant_part) {
970           DIE &VariantPart = createAndAddDIE(Composite->getTag(), Buffer);
971           constructTypeDIE(VariantPart, Composite);
972         }
973       }
974     }
975 
976     if (CTy->isAppleBlockExtension())
977       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
978 
979     if (CTy->getExportSymbols())
980       addFlag(Buffer, dwarf::DW_AT_export_symbols);
981 
982     // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
983     // inside C++ composite types to point to the base class with the vtable.
984     // Rust uses DW_AT_containing_type to link a vtable to the type
985     // for which it was created.
986     if (auto *ContainingType = CTy->getVTableHolder())
987       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
988                   *getOrCreateTypeDIE(ContainingType));
989 
990     if (CTy->isObjcClassComplete())
991       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
992 
993     // Add the type's non-standard calling convention.
994     uint8_t CC = 0;
995     if (CTy->isTypePassByValue())
996       CC = dwarf::DW_CC_pass_by_value;
997     else if (CTy->isTypePassByReference())
998       CC = dwarf::DW_CC_pass_by_reference;
999     if (CC)
1000       addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
1001               CC);
1002     break;
1003   }
1004   default:
1005     break;
1006   }
1007 
1008   // Add name if not anonymous or intermediate type.
1009   if (!Name.empty())
1010     addString(Buffer, dwarf::DW_AT_name, Name);
1011 
1012   if (Tag == dwarf::DW_TAG_enumeration_type ||
1013       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1014       Tag == dwarf::DW_TAG_union_type) {
1015     // Add size if non-zero (derived types might be zero-sized.)
1016     // Ignore the size if it's a non-enum forward decl.
1017     // TODO: Do we care about size for enum forward declarations?
1018     if (Size &&
1019         (!CTy->isForwardDecl() || Tag == dwarf::DW_TAG_enumeration_type))
1020       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1021     else if (!CTy->isForwardDecl())
1022       // Add zero size if it is not a forward declaration.
1023       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1024 
1025     // If we're a forward decl, say so.
1026     if (CTy->isForwardDecl())
1027       addFlag(Buffer, dwarf::DW_AT_declaration);
1028 
1029     // Add source line info if available.
1030     if (!CTy->isForwardDecl())
1031       addSourceLine(Buffer, CTy);
1032 
1033     // No harm in adding the runtime language to the declaration.
1034     unsigned RLang = CTy->getRuntimeLang();
1035     if (RLang)
1036       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1037               RLang);
1038 
1039     // Add align info if available.
1040     if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1041       addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1042               AlignInBytes);
1043   }
1044 }
1045 
1046 void DwarfUnit::constructTemplateTypeParameterDIE(
1047     DIE &Buffer, const DITemplateTypeParameter *TP) {
1048   DIE &ParamDIE =
1049       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1050   // Add the type if it exists, it could be void and therefore no type.
1051   if (TP->getType())
1052     addType(ParamDIE, TP->getType());
1053   if (!TP->getName().empty())
1054     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1055   if (TP->isDefault() && (DD->getDwarfVersion() >= 5))
1056     addFlag(ParamDIE, dwarf::DW_AT_default_value);
1057 }
1058 
1059 void DwarfUnit::constructTemplateValueParameterDIE(
1060     DIE &Buffer, const DITemplateValueParameter *VP) {
1061   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1062 
1063   // Add the type if there is one, template template and template parameter
1064   // packs will not have a type.
1065   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1066     addType(ParamDIE, VP->getType());
1067   if (!VP->getName().empty())
1068     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1069   if (VP->isDefault() && (DD->getDwarfVersion() >= 5))
1070     addFlag(ParamDIE, dwarf::DW_AT_default_value);
1071   if (Metadata *Val = VP->getValue()) {
1072     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1073       addConstantValue(ParamDIE, CI, VP->getType());
1074     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1075       // We cannot describe the location of dllimport'd entities: the
1076       // computation of their address requires loads from the IAT.
1077       if (!GV->hasDLLImportStorageClass()) {
1078         // For declaration non-type template parameters (such as global values
1079         // and functions)
1080         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1081         addOpAddress(*Loc, Asm->getSymbol(GV));
1082         // Emit DW_OP_stack_value to use the address as the immediate value of
1083         // the parameter, rather than a pointer to it.
1084         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1085         addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1086       }
1087     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1088       assert(isa<MDString>(Val));
1089       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1090                 cast<MDString>(Val)->getString());
1091     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1092       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1093     }
1094   }
1095 }
1096 
1097 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1098   // Construct the context before querying for the existence of the DIE in case
1099   // such construction creates the DIE.
1100   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1101 
1102   if (DIE *NDie = getDIE(NS))
1103     return NDie;
1104   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1105 
1106   StringRef Name = NS->getName();
1107   if (!Name.empty())
1108     addString(NDie, dwarf::DW_AT_name, NS->getName());
1109   else
1110     Name = "(anonymous namespace)";
1111   DD->addAccelNamespace(*CUNode, Name, NDie);
1112   addGlobalName(Name, NDie, NS->getScope());
1113   if (NS->getExportSymbols())
1114     addFlag(NDie, dwarf::DW_AT_export_symbols);
1115   return &NDie;
1116 }
1117 
1118 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1119   // Construct the context before querying for the existence of the DIE in case
1120   // such construction creates the DIE.
1121   DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1122 
1123   if (DIE *MDie = getDIE(M))
1124     return MDie;
1125   DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1126 
1127   if (!M->getName().empty()) {
1128     addString(MDie, dwarf::DW_AT_name, M->getName());
1129     addGlobalName(M->getName(), MDie, M->getScope());
1130   }
1131   if (!M->getConfigurationMacros().empty())
1132     addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1133               M->getConfigurationMacros());
1134   if (!M->getIncludePath().empty())
1135     addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1136   if (!M->getAPINotesFile().empty())
1137     addString(MDie, dwarf::DW_AT_LLVM_apinotes, M->getAPINotesFile());
1138   if (M->getFile())
1139     addUInt(MDie, dwarf::DW_AT_decl_file, None,
1140             getOrCreateSourceID(M->getFile()));
1141   if (M->getLineNo())
1142     addUInt(MDie, dwarf::DW_AT_decl_line, None, M->getLineNo());
1143 
1144   return &MDie;
1145 }
1146 
1147 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1148   // Construct the context before querying for the existence of the DIE in case
1149   // such construction creates the DIE (as is the case for member function
1150   // declarations).
1151   DIE *ContextDIE =
1152       Minimal ? &getUnitDie() : getOrCreateContextDIE(SP->getScope());
1153 
1154   if (DIE *SPDie = getDIE(SP))
1155     return SPDie;
1156 
1157   if (auto *SPDecl = SP->getDeclaration()) {
1158     if (!Minimal) {
1159       // Add subprogram definitions to the CU die directly.
1160       ContextDIE = &getUnitDie();
1161       // Build the decl now to ensure it precedes the definition.
1162       getOrCreateSubprogramDIE(SPDecl);
1163     }
1164   }
1165 
1166   // DW_TAG_inlined_subroutine may refer to this DIE.
1167   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1168 
1169   // Stop here and fill this in later, depending on whether or not this
1170   // subprogram turns out to have inlined instances or not.
1171   if (SP->isDefinition())
1172     return &SPDie;
1173 
1174   static_cast<DwarfUnit *>(SPDie.getUnit())
1175       ->applySubprogramAttributes(SP, SPDie);
1176   return &SPDie;
1177 }
1178 
1179 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1180                                                     DIE &SPDie) {
1181   DIE *DeclDie = nullptr;
1182   StringRef DeclLinkageName;
1183   if (auto *SPDecl = SP->getDeclaration()) {
1184     DITypeRefArray DeclArgs, DefinitionArgs;
1185     DeclArgs = SPDecl->getType()->getTypeArray();
1186     DefinitionArgs = SP->getType()->getTypeArray();
1187 
1188     if (DeclArgs.size() && DefinitionArgs.size())
1189       if (DefinitionArgs[0] != NULL && DeclArgs[0] != DefinitionArgs[0])
1190         addType(SPDie, DefinitionArgs[0]);
1191 
1192     DeclDie = getDIE(SPDecl);
1193     assert(DeclDie && "This DIE should've already been constructed when the "
1194                       "definition DIE was created in "
1195                       "getOrCreateSubprogramDIE");
1196     // Look at the Decl's linkage name only if we emitted it.
1197     if (DD->useAllLinkageNames())
1198       DeclLinkageName = SPDecl->getLinkageName();
1199     unsigned DeclID = getOrCreateSourceID(SPDecl->getFile());
1200     unsigned DefID = getOrCreateSourceID(SP->getFile());
1201     if (DeclID != DefID)
1202       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1203 
1204     if (SP->getLine() != SPDecl->getLine())
1205       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1206   }
1207 
1208   // Add function template parameters.
1209   addTemplateParams(SPDie, SP->getTemplateParams());
1210 
1211   // Add the linkage name if we have one and it isn't in the Decl.
1212   StringRef LinkageName = SP->getLinkageName();
1213   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1214           LinkageName == DeclLinkageName) &&
1215          "decl has a linkage name and it is different");
1216   if (DeclLinkageName.empty() &&
1217       // Always emit it for abstract subprograms.
1218       (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1219     addLinkageName(SPDie, LinkageName);
1220 
1221   if (!DeclDie)
1222     return false;
1223 
1224   // Refer to the function declaration where all the other attributes will be
1225   // found.
1226   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1227   return true;
1228 }
1229 
1230 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1231                                           bool SkipSPAttributes) {
1232   // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1233   // and its source location.
1234   bool SkipSPSourceLocation = SkipSPAttributes &&
1235                               !CUNode->getDebugInfoForProfiling();
1236   if (!SkipSPSourceLocation)
1237     if (applySubprogramDefinitionAttributes(SP, SPDie))
1238       return;
1239 
1240   // Constructors and operators for anonymous aggregates do not have names.
1241   if (!SP->getName().empty())
1242     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1243 
1244   if (!SkipSPSourceLocation)
1245     addSourceLine(SPDie, SP);
1246 
1247   // Skip the rest of the attributes under -gmlt to save space.
1248   if (SkipSPAttributes)
1249     return;
1250 
1251   // Add the prototype if we have a prototype and we have a C like
1252   // language.
1253   uint16_t Language = getLanguage();
1254   if (SP->isPrototyped() &&
1255       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1256        Language == dwarf::DW_LANG_ObjC))
1257     addFlag(SPDie, dwarf::DW_AT_prototyped);
1258 
1259   if (SP->isObjCDirect())
1260     addFlag(SPDie, dwarf::DW_AT_APPLE_objc_direct);
1261 
1262   unsigned CC = 0;
1263   DITypeRefArray Args;
1264   if (const DISubroutineType *SPTy = SP->getType()) {
1265     Args = SPTy->getTypeArray();
1266     CC = SPTy->getCC();
1267   }
1268 
1269   // Add a DW_AT_calling_convention if this has an explicit convention.
1270   if (CC && CC != dwarf::DW_CC_normal)
1271     addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1272 
1273   // Add a return type. If this is a type like a C/C++ void type we don't add a
1274   // return type.
1275   if (Args.size())
1276     if (auto Ty = Args[0])
1277       addType(SPDie, Ty);
1278 
1279   unsigned VK = SP->getVirtuality();
1280   if (VK) {
1281     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1282     if (SP->getVirtualIndex() != -1u) {
1283       DIELoc *Block = getDIELoc();
1284       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1285       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1286       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1287     }
1288     ContainingTypeMap.insert(std::make_pair(&SPDie, SP->getContainingType()));
1289   }
1290 
1291   if (!SP->isDefinition()) {
1292     addFlag(SPDie, dwarf::DW_AT_declaration);
1293 
1294     // Add arguments. Do not add arguments for subprogram definition. They will
1295     // be handled while processing variables.
1296     constructSubprogramArguments(SPDie, Args);
1297   }
1298 
1299   addThrownTypes(SPDie, SP->getThrownTypes());
1300 
1301   if (SP->isArtificial())
1302     addFlag(SPDie, dwarf::DW_AT_artificial);
1303 
1304   if (!SP->isLocalToUnit())
1305     addFlag(SPDie, dwarf::DW_AT_external);
1306 
1307   if (DD->useAppleExtensionAttributes()) {
1308     if (SP->isOptimized())
1309       addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1310 
1311     if (unsigned isa = Asm->getISAEncoding())
1312       addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1313   }
1314 
1315   if (SP->isLValueReference())
1316     addFlag(SPDie, dwarf::DW_AT_reference);
1317 
1318   if (SP->isRValueReference())
1319     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1320 
1321   if (SP->isNoReturn())
1322     addFlag(SPDie, dwarf::DW_AT_noreturn);
1323 
1324   if (SP->isProtected())
1325     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1326             dwarf::DW_ACCESS_protected);
1327   else if (SP->isPrivate())
1328     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1329             dwarf::DW_ACCESS_private);
1330   else if (SP->isPublic())
1331     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1332             dwarf::DW_ACCESS_public);
1333 
1334   if (SP->isExplicit())
1335     addFlag(SPDie, dwarf::DW_AT_explicit);
1336 
1337   if (SP->isMainSubprogram())
1338     addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1339   if (SP->isPure())
1340     addFlag(SPDie, dwarf::DW_AT_pure);
1341   if (SP->isElemental())
1342     addFlag(SPDie, dwarf::DW_AT_elemental);
1343   if (SP->isRecursive())
1344     addFlag(SPDie, dwarf::DW_AT_recursive);
1345 
1346   if (DD->getDwarfVersion() >= 5 && SP->isDeleted())
1347     addFlag(SPDie, dwarf::DW_AT_deleted);
1348 }
1349 
1350 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1351                                      DIE *IndexTy) {
1352   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1353   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1354 
1355   // The LowerBound value defines the lower bounds which is typically zero for
1356   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1357   // Count == -1 then the array is unbounded and we do not emit
1358   // DW_AT_lower_bound and DW_AT_count attributes.
1359   int64_t DefaultLowerBound = getDefaultLowerBound();
1360   int64_t Count = -1;
1361   if (auto *CI = SR->getCount().dyn_cast<ConstantInt*>())
1362     Count = CI->getSExtValue();
1363 
1364   auto addBoundTypeEntry = [&](dwarf::Attribute Attr,
1365                                DISubrange::BoundType Bound) -> void {
1366     if (auto *BV = Bound.dyn_cast<DIVariable *>()) {
1367       if (auto *VarDIE = getDIE(BV))
1368         addDIEEntry(DW_Subrange, Attr, *VarDIE);
1369     } else if (auto *BE = Bound.dyn_cast<DIExpression *>()) {
1370       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1371       DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1372       DwarfExpr.setMemoryLocationKind();
1373       DwarfExpr.addExpression(BE);
1374       addBlock(DW_Subrange, Attr, DwarfExpr.finalize());
1375     } else if (auto *BI = Bound.dyn_cast<ConstantInt *>()) {
1376       if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
1377           BI->getSExtValue() != DefaultLowerBound)
1378         addSInt(DW_Subrange, Attr, dwarf::DW_FORM_sdata, BI->getSExtValue());
1379     }
1380   };
1381 
1382   addBoundTypeEntry(dwarf::DW_AT_lower_bound, SR->getLowerBound());
1383 
1384   if (auto *CV = SR->getCount().dyn_cast<DIVariable*>()) {
1385     if (auto *CountVarDIE = getDIE(CV))
1386       addDIEEntry(DW_Subrange, dwarf::DW_AT_count, *CountVarDIE);
1387   } else if (Count != -1)
1388     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1389 
1390   addBoundTypeEntry(dwarf::DW_AT_upper_bound, SR->getUpperBound());
1391 
1392   addBoundTypeEntry(dwarf::DW_AT_byte_stride, SR->getStride());
1393 }
1394 
1395 DIE *DwarfUnit::getIndexTyDie() {
1396   if (IndexTyDie)
1397     return IndexTyDie;
1398   // Construct an integer type to use for indexes.
1399   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1400   StringRef Name = "__ARRAY_SIZE_TYPE__";
1401   addString(*IndexTyDie, dwarf::DW_AT_name, Name);
1402   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1403   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1404           dwarf::DW_ATE_unsigned);
1405   DD->addAccelType(*CUNode, Name, *IndexTyDie, /*Flags*/ 0);
1406   return IndexTyDie;
1407 }
1408 
1409 /// Returns true if the vector's size differs from the sum of sizes of elements
1410 /// the user specified.  This can occur if the vector has been rounded up to
1411 /// fit memory alignment constraints.
1412 static bool hasVectorBeenPadded(const DICompositeType *CTy) {
1413   assert(CTy && CTy->isVector() && "Composite type is not a vector");
1414   const uint64_t ActualSize = CTy->getSizeInBits();
1415 
1416   // Obtain the size of each element in the vector.
1417   DIType *BaseTy = CTy->getBaseType();
1418   assert(BaseTy && "Unknown vector element type.");
1419   const uint64_t ElementSize = BaseTy->getSizeInBits();
1420 
1421   // Locate the number of elements in the vector.
1422   const DINodeArray Elements = CTy->getElements();
1423   assert(Elements.size() == 1 &&
1424          Elements[0]->getTag() == dwarf::DW_TAG_subrange_type &&
1425          "Invalid vector element array, expected one element of type subrange");
1426   const auto Subrange = cast<DISubrange>(Elements[0]);
1427   const auto NumVecElements =
1428       Subrange->getCount()
1429           ? Subrange->getCount().get<ConstantInt *>()->getSExtValue()
1430           : 0;
1431 
1432   // Ensure we found the element count and that the actual size is wide
1433   // enough to contain the requested size.
1434   assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size");
1435   return ActualSize != (NumVecElements * ElementSize);
1436 }
1437 
1438 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1439   if (CTy->isVector()) {
1440     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1441     if (hasVectorBeenPadded(CTy))
1442       addUInt(Buffer, dwarf::DW_AT_byte_size, None,
1443               CTy->getSizeInBits() / CHAR_BIT);
1444   }
1445 
1446   if (DIVariable *Var = CTy->getDataLocation()) {
1447     if (auto *VarDIE = getDIE(Var))
1448       addDIEEntry(Buffer, dwarf::DW_AT_data_location, *VarDIE);
1449   } else if (DIExpression *Expr = CTy->getDataLocationExp()) {
1450     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1451     DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1452     DwarfExpr.setMemoryLocationKind();
1453     DwarfExpr.addExpression(Expr);
1454     addBlock(Buffer, dwarf::DW_AT_data_location, DwarfExpr.finalize());
1455   }
1456 
1457   if (DIVariable *Var = CTy->getAssociated()) {
1458     if (auto *VarDIE = getDIE(Var))
1459       addDIEEntry(Buffer, dwarf::DW_AT_associated, *VarDIE);
1460   } else if (DIExpression *Expr = CTy->getAssociatedExp()) {
1461     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1462     DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1463     DwarfExpr.setMemoryLocationKind();
1464     DwarfExpr.addExpression(Expr);
1465     addBlock(Buffer, dwarf::DW_AT_associated, DwarfExpr.finalize());
1466   }
1467 
1468   if (DIVariable *Var = CTy->getAllocated()) {
1469     if (auto *VarDIE = getDIE(Var))
1470       addDIEEntry(Buffer, dwarf::DW_AT_allocated, *VarDIE);
1471   } else if (DIExpression *Expr = CTy->getAllocatedExp()) {
1472     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1473     DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1474     DwarfExpr.setMemoryLocationKind();
1475     DwarfExpr.addExpression(Expr);
1476     addBlock(Buffer, dwarf::DW_AT_allocated, DwarfExpr.finalize());
1477   }
1478 
1479   // Emit the element type.
1480   addType(Buffer, CTy->getBaseType());
1481 
1482   // Get an anonymous type for index type.
1483   // FIXME: This type should be passed down from the front end
1484   // as different languages may have different sizes for indexes.
1485   DIE *IdxTy = getIndexTyDie();
1486 
1487   // Add subranges to array type.
1488   DINodeArray Elements = CTy->getElements();
1489   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1490     // FIXME: Should this really be such a loose cast?
1491     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1492       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1493         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1494   }
1495 }
1496 
1497 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1498   const DIType *DTy = CTy->getBaseType();
1499   bool IsUnsigned = DTy && isUnsignedDIType(DD, DTy);
1500   if (DTy) {
1501     if (DD->getDwarfVersion() >= 3)
1502       addType(Buffer, DTy);
1503     if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass))
1504       addFlag(Buffer, dwarf::DW_AT_enum_class);
1505   }
1506 
1507   auto *Context = CTy->getScope();
1508   bool IndexEnumerators = !Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
1509       isa<DINamespace>(Context) || isa<DICommonBlock>(Context);
1510   DINodeArray Elements = CTy->getElements();
1511 
1512   // Add enumerators to enumeration type.
1513   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1514     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1515     if (Enum) {
1516       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1517       StringRef Name = Enum->getName();
1518       addString(Enumerator, dwarf::DW_AT_name, Name);
1519       addConstantValue(Enumerator, Enum->getValue(), IsUnsigned);
1520       if (IndexEnumerators)
1521         addGlobalName(Name, Enumerator, Context);
1522     }
1523   }
1524 }
1525 
1526 void DwarfUnit::constructContainingTypeDIEs() {
1527   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1528        CI != CE; ++CI) {
1529     DIE &SPDie = *CI->first;
1530     const DINode *D = CI->second;
1531     if (!D)
1532       continue;
1533     DIE *NDie = getDIE(D);
1534     if (!NDie)
1535       continue;
1536     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1537   }
1538 }
1539 
1540 DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1541   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1542   StringRef Name = DT->getName();
1543   if (!Name.empty())
1544     addString(MemberDie, dwarf::DW_AT_name, Name);
1545 
1546   if (DIType *Resolved = DT->getBaseType())
1547     addType(MemberDie, Resolved);
1548 
1549   addSourceLine(MemberDie, DT);
1550 
1551   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1552 
1553     // For C++, virtual base classes are not at fixed offset. Use following
1554     // expression to extract appropriate offset from vtable.
1555     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1556 
1557     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1558     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1559     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1560     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1561     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1562     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1563     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1564     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1565 
1566     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1567   } else {
1568     uint64_t Size = DT->getSizeInBits();
1569     uint64_t FieldSize = DD->getBaseTypeSize(DT);
1570     uint32_t AlignInBytes = DT->getAlignInBytes();
1571     uint64_t OffsetInBytes;
1572 
1573     bool IsBitfield = FieldSize && Size != FieldSize;
1574     if (IsBitfield) {
1575       // Handle bitfield, assume bytes are 8 bits.
1576       if (DD->useDWARF2Bitfields())
1577         addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1578       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1579 
1580       uint64_t Offset = DT->getOffsetInBits();
1581       // We can't use DT->getAlignInBits() here: AlignInBits for member type
1582       // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1583       // which can't be done with bitfields. Thus we use FieldSize here.
1584       uint32_t AlignInBits = FieldSize;
1585       uint32_t AlignMask = ~(AlignInBits - 1);
1586       // The bits from the start of the storage unit to the start of the field.
1587       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1588       // The byte offset of the field's aligned storage unit inside the struct.
1589       OffsetInBytes = (Offset - StartBitOffset) / 8;
1590 
1591       if (DD->useDWARF2Bitfields()) {
1592         uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1593         uint64_t FieldOffset = (HiMark - FieldSize);
1594         Offset -= FieldOffset;
1595 
1596         // Maybe we need to work from the other end.
1597         if (Asm->getDataLayout().isLittleEndian())
1598           Offset = FieldSize - (Offset + Size);
1599 
1600         addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1601         OffsetInBytes = FieldOffset >> 3;
1602       } else {
1603         addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1604       }
1605     } else {
1606       // This is not a bitfield.
1607       OffsetInBytes = DT->getOffsetInBits() / 8;
1608       if (AlignInBytes)
1609         addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1610                 AlignInBytes);
1611     }
1612 
1613     if (DD->getDwarfVersion() <= 2) {
1614       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1615       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1616       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1617       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1618     } else if (!IsBitfield || DD->useDWARF2Bitfields())
1619       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1620               OffsetInBytes);
1621   }
1622 
1623   if (DT->isProtected())
1624     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1625             dwarf::DW_ACCESS_protected);
1626   else if (DT->isPrivate())
1627     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1628             dwarf::DW_ACCESS_private);
1629   // Otherwise C++ member and base classes are considered public.
1630   else if (DT->isPublic())
1631     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1632             dwarf::DW_ACCESS_public);
1633   if (DT->isVirtual())
1634     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1635             dwarf::DW_VIRTUALITY_virtual);
1636 
1637   // Objective-C properties.
1638   if (DINode *PNode = DT->getObjCProperty())
1639     if (DIE *PDie = getDIE(PNode))
1640       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1641                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1642 
1643   if (DT->isArtificial())
1644     addFlag(MemberDie, dwarf::DW_AT_artificial);
1645 
1646   return MemberDie;
1647 }
1648 
1649 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1650   if (!DT)
1651     return nullptr;
1652 
1653   // Construct the context before querying for the existence of the DIE in case
1654   // such construction creates the DIE.
1655   DIE *ContextDIE = getOrCreateContextDIE(DT->getScope());
1656   assert(dwarf::isType(ContextDIE->getTag()) &&
1657          "Static member should belong to a type.");
1658 
1659   if (DIE *StaticMemberDIE = getDIE(DT))
1660     return StaticMemberDIE;
1661 
1662   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1663 
1664   const DIType *Ty = DT->getBaseType();
1665 
1666   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1667   addType(StaticMemberDIE, Ty);
1668   addSourceLine(StaticMemberDIE, DT);
1669   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1670   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1671 
1672   // FIXME: We could omit private if the parent is a class_type, and
1673   // public if the parent is something else.
1674   if (DT->isProtected())
1675     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1676             dwarf::DW_ACCESS_protected);
1677   else if (DT->isPrivate())
1678     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1679             dwarf::DW_ACCESS_private);
1680   else if (DT->isPublic())
1681     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1682             dwarf::DW_ACCESS_public);
1683 
1684   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1685     addConstantValue(StaticMemberDIE, CI, Ty);
1686   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1687     addConstantFPValue(StaticMemberDIE, CFP);
1688 
1689   if (uint32_t AlignInBytes = DT->getAlignInBytes())
1690     addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1691             AlignInBytes);
1692 
1693   return &StaticMemberDIE;
1694 }
1695 
1696 void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1697   // Emit size of content not including length itself
1698   Asm->OutStreamer->AddComment("Length of Unit");
1699   if (!DD->useSectionsAsReferences()) {
1700     StringRef Prefix = isDwoUnit() ? "debug_info_dwo_" : "debug_info_";
1701     MCSymbol *BeginLabel = Asm->createTempSymbol(Prefix + "start");
1702     EndLabel = Asm->createTempSymbol(Prefix + "end");
1703     Asm->emitLabelDifference(EndLabel, BeginLabel, 4);
1704     Asm->OutStreamer->emitLabel(BeginLabel);
1705   } else
1706     Asm->emitInt32(getHeaderSize() + getUnitDie().getSize());
1707 
1708   Asm->OutStreamer->AddComment("DWARF version number");
1709   unsigned Version = DD->getDwarfVersion();
1710   Asm->emitInt16(Version);
1711 
1712   // DWARF v5 reorders the address size and adds a unit type.
1713   if (Version >= 5) {
1714     Asm->OutStreamer->AddComment("DWARF Unit Type");
1715     Asm->emitInt8(UT);
1716     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1717     Asm->emitInt8(Asm->MAI->getCodePointerSize());
1718   }
1719 
1720   // We share one abbreviations table across all units so it's always at the
1721   // start of the section. Use a relocatable offset where needed to ensure
1722   // linking doesn't invalidate that offset.
1723   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1724   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1725   if (UseOffsets)
1726     Asm->emitInt32(0);
1727   else
1728     Asm->emitDwarfSymbolReference(
1729         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1730 
1731   if (Version <= 4) {
1732     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1733     Asm->emitInt8(Asm->MAI->getCodePointerSize());
1734   }
1735 }
1736 
1737 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1738   DwarfUnit::emitCommonHeader(UseOffsets,
1739                               DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1740                                                   : dwarf::DW_UT_type);
1741   Asm->OutStreamer->AddComment("Type Signature");
1742   Asm->OutStreamer->emitIntValue(TypeSignature, sizeof(TypeSignature));
1743   Asm->OutStreamer->AddComment("Type DIE Offset");
1744   // In a skeleton type unit there is no type DIE so emit a zero offset.
1745   Asm->OutStreamer->emitIntValue(Ty ? Ty->getOffset() : 0,
1746                                  sizeof(Ty->getOffset()));
1747 }
1748 
1749 DIE::value_iterator
1750 DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
1751                            const MCSymbol *Hi, const MCSymbol *Lo) {
1752   return Die.addValue(DIEValueAllocator, Attribute,
1753                       DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1754                                                  : dwarf::DW_FORM_data4,
1755                       new (DIEValueAllocator) DIEDelta(Hi, Lo));
1756 }
1757 
1758 DIE::value_iterator
1759 DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
1760                            const MCSymbol *Label, const MCSymbol *Sec) {
1761   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1762     return addLabel(Die, Attribute,
1763                     DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1764                                                : dwarf::DW_FORM_data4,
1765                     Label);
1766   return addSectionDelta(Die, Attribute, Label, Sec);
1767 }
1768 
1769 bool DwarfTypeUnit::isDwoUnit() const {
1770   // Since there are no skeleton type units, all type units are dwo type units
1771   // when split DWARF is being used.
1772   return DD->useSplitDwarf();
1773 }
1774 
1775 void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1776                                   const DIScope *Context) {
1777   getCU().addGlobalNameForTypeUnit(Name, Context);
1778 }
1779 
1780 void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1781                                   const DIScope *Context) {
1782   getCU().addGlobalTypeUnitType(Ty, Context);
1783 }
1784 
1785 const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
1786   if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1787     return nullptr;
1788   if (isDwoUnit())
1789     return nullptr;
1790   return getSection()->getBeginSymbol();
1791 }
1792 
1793 void DwarfUnit::addStringOffsetsStart() {
1794   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1795   addSectionLabel(getUnitDie(), dwarf::DW_AT_str_offsets_base,
1796                   DU->getStringOffsetsStartSym(),
1797                   TLOF.getDwarfStrOffSection()->getBeginSymbol());
1798 }
1799 
1800 void DwarfUnit::addRnglistsBase() {
1801   assert(DD->getDwarfVersion() >= 5 &&
1802          "DW_AT_rnglists_base requires DWARF version 5 or later");
1803   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1804   addSectionLabel(getUnitDie(), dwarf::DW_AT_rnglists_base,
1805                   DU->getRnglistsTableBaseSym(),
1806                   TLOF.getDwarfRnglistsSection()->getBeginSymbol());
1807 }
1808 
1809 void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1810   addFlag(D, dwarf::DW_AT_declaration);
1811   StringRef Name = CTy->getName();
1812   if (!Name.empty())
1813     addString(D, dwarf::DW_AT_name, Name);
1814   getCU().createTypeDIE(CTy);
1815 }
1816