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