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