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