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