1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for constructing a dwarf compile unit.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "DwarfUnit.h"
15 #include "DwarfAccelTable.h"
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "DwarfExpression.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Mangler.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Target/TargetFrameLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "dwarfdebug"
41 
42 static cl::opt<bool>
43 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
44                        cl::desc("Generate DWARF4 type units."),
45                        cl::init(false));
46 
47 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
48                                        DIELoc &DIE)
49     : DwarfExpression(*AP.MF->getSubtarget().getRegisterInfo(),
50                       AP.getDwarfDebug()->getDwarfVersion()),
51       AP(AP), DU(DU), DIE(DIE) {}
52 
53 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
54   DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
55 }
56 void DIEDwarfExpression::EmitSigned(int64_t Value) {
57   DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
58 }
59 void DIEDwarfExpression::EmitUnsigned(uint64_t Value) {
60   DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
61 }
62 bool DIEDwarfExpression::isFrameRegister(unsigned MachineReg) {
63   return MachineReg == TRI.getFrameRegister(*AP.MF);
64 }
65 
66 DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
67                      AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
68     : CUNode(Node), UnitDie(*DIE::get(DIEValueAllocator, UnitTag)), Asm(A),
69       DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
70   assert(UnitTag == dwarf::DW_TAG_compile_unit ||
71          UnitTag == dwarf::DW_TAG_type_unit);
72 }
73 
74 DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
75                              DwarfDebug *DW, DwarfFile *DWU,
76                              MCDwarfDwoLineTable *SplitLineTable)
77     : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
78       SplitLineTable(SplitLineTable) {
79   if (SplitLineTable)
80     addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
81 }
82 
83 DwarfUnit::~DwarfUnit() {
84   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
85     DIEBlocks[j]->~DIEBlock();
86   for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
87     DIELocs[j]->~DIELoc();
88 }
89 
90 int64_t DwarfUnit::getDefaultLowerBound() const {
91   switch (getLanguage()) {
92   default:
93     break;
94 
95   case dwarf::DW_LANG_C89:
96   case dwarf::DW_LANG_C99:
97   case dwarf::DW_LANG_C:
98   case dwarf::DW_LANG_C_plus_plus:
99   case dwarf::DW_LANG_ObjC:
100   case dwarf::DW_LANG_ObjC_plus_plus:
101     return 0;
102 
103   case dwarf::DW_LANG_Fortran77:
104   case dwarf::DW_LANG_Fortran90:
105   case dwarf::DW_LANG_Fortran95:
106     return 1;
107 
108   // The languages below have valid values only if the DWARF version >= 4.
109   case dwarf::DW_LANG_Java:
110   case dwarf::DW_LANG_Python:
111   case dwarf::DW_LANG_UPC:
112   case dwarf::DW_LANG_D:
113     if (dwarf::DWARF_VERSION >= 4)
114       return 0;
115     break;
116 
117   case dwarf::DW_LANG_Ada83:
118   case dwarf::DW_LANG_Ada95:
119   case dwarf::DW_LANG_Cobol74:
120   case dwarf::DW_LANG_Cobol85:
121   case dwarf::DW_LANG_Modula2:
122   case dwarf::DW_LANG_Pascal83:
123   case dwarf::DW_LANG_PLI:
124     if (dwarf::DWARF_VERSION >= 4)
125       return 1;
126     break;
127 
128   // The languages below have valid values only if the DWARF version >= 5.
129   case dwarf::DW_LANG_OpenCL:
130   case dwarf::DW_LANG_Go:
131   case dwarf::DW_LANG_Haskell:
132   case dwarf::DW_LANG_C_plus_plus_03:
133   case dwarf::DW_LANG_C_plus_plus_11:
134   case dwarf::DW_LANG_OCaml:
135   case dwarf::DW_LANG_Rust:
136   case dwarf::DW_LANG_C11:
137   case dwarf::DW_LANG_Swift:
138   case dwarf::DW_LANG_Dylan:
139   case dwarf::DW_LANG_C_plus_plus_14:
140     if (dwarf::DWARF_VERSION >= 5)
141       return 0;
142     break;
143 
144   case dwarf::DW_LANG_Modula3:
145   case dwarf::DW_LANG_Julia:
146   case dwarf::DW_LANG_Fortran03:
147   case dwarf::DW_LANG_Fortran08:
148     if (dwarf::DWARF_VERSION >= 5)
149       return 1;
150     break;
151   }
152 
153   return -1;
154 }
155 
156 /// Check whether the DIE for this MDNode can be shared across CUs.
157 static bool isShareableAcrossCUs(const DINode *D) {
158   // When the MDNode can be part of the type system, the DIE can be shared
159   // across CUs.
160   // Combining type units and cross-CU DIE sharing is lower value (since
161   // cross-CU DIE sharing is used in LTO and removes type redundancy at that
162   // level already) but may be implementable for some value in projects
163   // building multiple independent libraries with LTO and then linking those
164   // together.
165   return (isa<DIType>(D) ||
166           (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
167          !GenerateDwarfTypeUnits;
168 }
169 
170 DIE *DwarfUnit::getDIE(const DINode *D) const {
171   if (isShareableAcrossCUs(D))
172     return DU->getDIE(D);
173   return MDNodeToDieMap.lookup(D);
174 }
175 
176 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
177   if (isShareableAcrossCUs(Desc)) {
178     DU->insertDIE(Desc, D);
179     return;
180   }
181   MDNodeToDieMap.insert(std::make_pair(Desc, D));
182 }
183 
184 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
185   if (DD->getDwarfVersion() >= 4)
186     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
187                  DIEInteger(1));
188   else
189     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
190                  DIEInteger(1));
191 }
192 
193 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
194                         Optional<dwarf::Form> Form, uint64_t Integer) {
195   if (!Form)
196     Form = DIEInteger::BestForm(false, Integer);
197   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
198 }
199 
200 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
201                         uint64_t Integer) {
202   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
203 }
204 
205 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
206                         Optional<dwarf::Form> Form, int64_t Integer) {
207   if (!Form)
208     Form = DIEInteger::BestForm(true, Integer);
209   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
210 }
211 
212 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
213                         int64_t Integer) {
214   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
215 }
216 
217 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
218                           StringRef String) {
219   Die.addValue(DIEValueAllocator, Attribute,
220                isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
221                DIEString(DU->getStringPool().getEntry(*Asm, String)));
222 }
223 
224 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
225                                                  dwarf::Attribute Attribute,
226                                                  dwarf::Form Form,
227                                                  const MCSymbol *Label) {
228   return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
229 }
230 
231 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
232   addLabel(Die, (dwarf::Attribute)0, Form, Label);
233 }
234 
235 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
236                                  uint64_t Integer) {
237   if (DD->getDwarfVersion() >= 4)
238     addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
239   else
240     addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
241 }
242 
243 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
244   return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
245                         : getCU().getOrCreateSourceID(FileName, DirName);
246 }
247 
248 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
249   if (!DD->useSplitDwarf()) {
250     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
251     addLabel(Die, dwarf::DW_FORM_udata, Sym);
252   } else {
253     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
254     addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
255             DD->getAddressPool().getIndex(Sym));
256   }
257 }
258 
259 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
260                               const MCSymbol *Hi, const MCSymbol *Lo) {
261   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
262                new (DIEValueAllocator) DIEDelta(Hi, Lo));
263 }
264 
265 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
266   addDIEEntry(Die, Attribute, DIEEntry(Entry));
267 }
268 
269 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
270   // Flag the type unit reference as a declaration so that if it contains
271   // members (implicit special members, static data member definitions, member
272   // declarations for definitions in this CU, etc) consumers don't get confused
273   // and think this is a full definition.
274   addFlag(Die, dwarf::DW_AT_declaration);
275 
276   Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
277                dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
278 }
279 
280 void DwarfUnit::addDIETypeSignature(DIE &Die, dwarf::Attribute Attribute,
281                                     StringRef Identifier) {
282   uint64_t Signature = DD->makeTypeSignature(Identifier);
283   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_ref_sig8,
284                DIEInteger(Signature));
285 }
286 
287 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
288                             DIEEntry Entry) {
289   const DIE *DieCU = Die.getUnitOrNull();
290   const DIE *EntryCU = Entry.getEntry().getUnitOrNull();
291   if (!DieCU)
292     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
293     DieCU = &getUnitDie();
294   if (!EntryCU)
295     EntryCU = &getUnitDie();
296   Die.addValue(DIEValueAllocator, Attribute,
297                EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
298                Entry);
299 }
300 
301 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
302   DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
303   if (N)
304     insertDIE(N, &Die);
305   return Die;
306 }
307 
308 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
309   Loc->ComputeSize(Asm);
310   DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
311   Die.addValue(DIEValueAllocator, Attribute,
312                Loc->BestForm(DD->getDwarfVersion()), Loc);
313 }
314 
315 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
316                          DIEBlock *Block) {
317   Block->ComputeSize(Asm);
318   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
319   Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
320 }
321 
322 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
323                               StringRef Directory) {
324   if (Line == 0)
325     return;
326 
327   unsigned FileID = getOrCreateSourceID(File, Directory);
328   assert(FileID && "Invalid file id");
329   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
330   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
331 }
332 
333 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
334   assert(V);
335 
336   addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
337                 V->getScope()->getDirectory());
338 }
339 
340 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
341   assert(G);
342 
343   addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
344 }
345 
346 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
347   assert(SP);
348 
349   addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
350 }
351 
352 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
353   assert(Ty);
354 
355   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
356 }
357 
358 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
359   assert(Ty);
360 
361   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
362 }
363 
364 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
365   addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
366 }
367 
368 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
369                                    unsigned SizeInBits, unsigned OffsetInBits) {
370   DIEDwarfExpression Expr(*Asm, *this, TheDie);
371   Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits);
372   return true;
373 }
374 
375 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
376                                   int64_t Offset) {
377   DIEDwarfExpression Expr(*Asm, *this, TheDie);
378   return Expr.AddMachineRegIndirect(Reg, Offset);
379 }
380 
381 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
382    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
383    gives the variable VarName either the struct, or a pointer to the struct, as
384    its type.  This is necessary for various behind-the-scenes things the
385    compiler needs to do with by-reference variables in Blocks.
386 
387    However, as far as the original *programmer* is concerned, the variable
388    should still have type 'SomeType', as originally declared.
389 
390    The function getBlockByrefType dives into the __Block_byref_x_VarName
391    struct to find the original type of the variable, which is then assigned to
392    the variable's Debug Information Entry as its real type.  So far, so good.
393    However now the debugger will expect the variable VarName to have the type
394    SomeType.  So we need the location attribute for the variable to be an
395    expression that explains to the debugger how to navigate through the
396    pointers and struct to find the actual variable of type SomeType.
397 
398    The following function does just that.  We start by getting
399    the "normal" location for the variable. This will be the location
400    of either the struct __Block_byref_x_VarName or the pointer to the
401    struct __Block_byref_x_VarName.
402 
403    The struct will look something like:
404 
405    struct __Block_byref_x_VarName {
406      ... <various fields>
407      struct __Block_byref_x_VarName *forwarding;
408      ... <various other fields>
409      SomeType VarName;
410      ... <maybe more fields>
411    };
412 
413    If we are given the struct directly (as our starting point) we
414    need to tell the debugger to:
415 
416    1).  Add the offset of the forwarding field.
417 
418    2).  Follow that pointer to get the real __Block_byref_x_VarName
419    struct to use (the real one may have been copied onto the heap).
420 
421    3).  Add the offset for the field VarName, to find the actual variable.
422 
423    If we started with a pointer to the struct, then we need to
424    dereference that pointer first, before the other steps.
425    Translating this into DWARF ops, we will need to append the following
426    to the current location description for the variable:
427 
428    DW_OP_deref                    -- optional, if we start with a pointer
429    DW_OP_plus_uconst <forward_fld_offset>
430    DW_OP_deref
431    DW_OP_plus_uconst <varName_fld_offset>
432 
433    That is what this function does.  */
434 
435 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
436                                      dwarf::Attribute Attribute,
437                                      const MachineLocation &Location) {
438   const DIType *Ty = DV.getType();
439   const DIType *TmpTy = Ty;
440   uint16_t Tag = Ty->getTag();
441   bool isPointer = false;
442 
443   StringRef varName = DV.getName();
444 
445   if (Tag == dwarf::DW_TAG_pointer_type) {
446     auto *DTy = cast<DIDerivedType>(Ty);
447     TmpTy = resolve(DTy->getBaseType());
448     isPointer = true;
449   }
450 
451   // Find the __forwarding field and the variable field in the __Block_byref
452   // struct.
453   DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements();
454   const DIDerivedType *varField = nullptr;
455   const DIDerivedType *forwardingField = nullptr;
456 
457   for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
458     auto *DT = cast<DIDerivedType>(Fields[i]);
459     StringRef fieldName = DT->getName();
460     if (fieldName == "__forwarding")
461       forwardingField = DT;
462     else if (fieldName == varName)
463       varField = DT;
464   }
465 
466   // Get the offsets for the forwarding field and the variable field.
467   unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
468   unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
469 
470   // Decode the original location, and use that as the start of the byref
471   // variable's location.
472   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
473 
474   bool validReg;
475   if (Location.isReg())
476     validReg = addRegisterOpPiece(*Loc, Location.getReg());
477   else
478     validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
479 
480   if (!validReg)
481     return;
482 
483   // If we started with a pointer to the __Block_byref... struct, then
484   // the first thing we need to do is dereference the pointer (DW_OP_deref).
485   if (isPointer)
486     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
487 
488   // Next add the offset for the '__forwarding' field:
489   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
490   // adding the offset if it's 0.
491   if (forwardingFieldOffset > 0) {
492     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
493     addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
494   }
495 
496   // Now dereference the __forwarding field to get to the real __Block_byref
497   // struct:  DW_OP_deref.
498   addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
499 
500   // Now that we've got the real __Block_byref... struct, add the offset
501   // for the variable's field to get to the location of the actual variable:
502   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
503   if (varFieldOffset > 0) {
504     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
505     addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
506   }
507 
508   // Now attach the location information to the DIE.
509   addBlock(Die, Attribute, Loc);
510 }
511 
512 /// Return true if type encoding is unsigned.
513 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
514   if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
515     // FIXME: Enums without a fixed underlying type have unknown signedness
516     // here, leading to incorrectly emitted constants.
517     if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
518       return false;
519 
520     // (Pieces of) aggregate types that get hacked apart by SROA may be
521     // represented by a constant. Encode them as unsigned bytes.
522     return true;
523   }
524 
525   if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
526     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
527     // Encode pointer constants as unsigned bytes. This is used at least for
528     // null pointer constant emission.
529     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
530     // here, but accept them for now due to a bug in SROA producing bogus
531     // dbg.values.
532     if (T == dwarf::DW_TAG_pointer_type ||
533         T == dwarf::DW_TAG_ptr_to_member_type ||
534         T == dwarf::DW_TAG_reference_type ||
535         T == dwarf::DW_TAG_rvalue_reference_type)
536       return true;
537     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
538            T == dwarf::DW_TAG_volatile_type ||
539            T == dwarf::DW_TAG_restrict_type);
540     DITypeRef Deriv = DTy->getBaseType();
541     assert(Deriv && "Expected valid base type");
542     return isUnsignedDIType(DD, DD->resolve(Deriv));
543   }
544 
545   auto *BTy = cast<DIBasicType>(Ty);
546   unsigned Encoding = BTy->getEncoding();
547   assert((Encoding == dwarf::DW_ATE_unsigned ||
548           Encoding == dwarf::DW_ATE_unsigned_char ||
549           Encoding == dwarf::DW_ATE_signed ||
550           Encoding == dwarf::DW_ATE_signed_char ||
551           Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
552           Encoding == dwarf::DW_ATE_boolean ||
553           (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
554            Ty->getName() == "decltype(nullptr)")) &&
555          "Unsupported encoding");
556   return Encoding == dwarf::DW_ATE_unsigned ||
557          Encoding == dwarf::DW_ATE_unsigned_char ||
558          Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
559          Ty->getTag() == dwarf::DW_TAG_unspecified_type;
560 }
561 
562 /// If this type is derived from a base type then return base type size.
563 static uint64_t getBaseTypeSize(DwarfDebug *DD, const DIDerivedType *Ty) {
564   unsigned Tag = Ty->getTag();
565 
566   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
567       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
568       Tag != dwarf::DW_TAG_restrict_type)
569     return Ty->getSizeInBits();
570 
571   auto *BaseType = DD->resolve(Ty->getBaseType());
572 
573   assert(BaseType && "Unexpected invalid base type");
574 
575   // If this is a derived type, go ahead and get the base type, unless it's a
576   // reference then it's just the size of the field. Pointer types have no need
577   // of this since they're a different type of qualification on the type.
578   if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
579       BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
580     return Ty->getSizeInBits();
581 
582   if (auto *DT = dyn_cast<DIDerivedType>(BaseType))
583     return getBaseTypeSize(DD, DT);
584 
585   return BaseType->getSizeInBits();
586 }
587 
588 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
589   assert(MO.isFPImm() && "Invalid machine operand!");
590   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
591   APFloat FPImm = MO.getFPImm()->getValueAPF();
592 
593   // Get the raw data form of the floating point.
594   const APInt FltVal = FPImm.bitcastToAPInt();
595   const char *FltPtr = (const char *)FltVal.getRawData();
596 
597   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
598   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
599   int Incr = (LittleEndian ? 1 : -1);
600   int Start = (LittleEndian ? 0 : NumBytes - 1);
601   int Stop = (LittleEndian ? NumBytes : -1);
602 
603   // Output the constant to DWARF one byte at a time.
604   for (; Start != Stop; Start += Incr)
605     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
606 
607   addBlock(Die, dwarf::DW_AT_const_value, Block);
608 }
609 
610 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
611   // Pass this down to addConstantValue as an unsigned bag of bits.
612   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
613 }
614 
615 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
616                                  const DIType *Ty) {
617   addConstantValue(Die, CI->getValue(), Ty);
618 }
619 
620 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
621                                  const DIType *Ty) {
622   assert(MO.isImm() && "Invalid machine operand!");
623 
624   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
625 }
626 
627 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
628   // FIXME: This is a bit conservative/simple - it emits negative values always
629   // sign extended to 64 bits rather than minimizing the number of bytes.
630   addUInt(Die, dwarf::DW_AT_const_value,
631           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
632 }
633 
634 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
635   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
636 }
637 
638 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
639   unsigned CIBitWidth = Val.getBitWidth();
640   if (CIBitWidth <= 64) {
641     addConstantValue(Die, Unsigned,
642                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
643     return;
644   }
645 
646   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
647 
648   // Get the raw data form of the large APInt.
649   const uint64_t *Ptr64 = Val.getRawData();
650 
651   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
652   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
653 
654   // Output the constant to DWARF one byte at a time.
655   for (int i = 0; i < NumBytes; i++) {
656     uint8_t c;
657     if (LittleEndian)
658       c = Ptr64[i / 8] >> (8 * (i & 7));
659     else
660       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
661     addUInt(*Block, dwarf::DW_FORM_data1, c);
662   }
663 
664   addBlock(Die, dwarf::DW_AT_const_value, Block);
665 }
666 
667 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
668   if (!LinkageName.empty() && DD->useLinkageNames())
669     addString(Die,
670               DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
671                                          : dwarf::DW_AT_MIPS_linkage_name,
672               GlobalValue::getRealLinkageName(LinkageName));
673 }
674 
675 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
676   // Add template parameters.
677   for (const auto *Element : TParams) {
678     if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
679       constructTemplateTypeParameterDIE(Buffer, TTP);
680     else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
681       constructTemplateValueParameterDIE(Buffer, TVP);
682   }
683 }
684 
685 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
686   if (!Context || isa<DIFile>(Context))
687     return &getUnitDie();
688   if (auto *T = dyn_cast<DIType>(Context))
689     return getOrCreateTypeDIE(T);
690   if (auto *NS = dyn_cast<DINamespace>(Context))
691     return getOrCreateNameSpace(NS);
692   if (auto *SP = dyn_cast<DISubprogram>(Context))
693     return getOrCreateSubprogramDIE(SP);
694   if (auto *M = dyn_cast<DIModule>(Context))
695     return getOrCreateModule(M);
696   return getDIE(Context);
697 }
698 
699 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
700   auto *Context = resolve(Ty->getScope());
701   DIE *ContextDIE = getOrCreateContextDIE(Context);
702 
703   if (DIE *TyDIE = getDIE(Ty))
704     return TyDIE;
705 
706   // Create new type.
707   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
708 
709   constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
710 
711   if (!Ty->isExternalTypeRef())
712     updateAcceleratorTables(Context, Ty, TyDIE);
713   return &TyDIE;
714 }
715 
716 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
717   if (!TyNode)
718     return nullptr;
719 
720   auto *Ty = cast<DIType>(TyNode);
721   assert(Ty == resolve(Ty->getRef()) &&
722          "type was not uniqued, possible ODR violation.");
723 
724   // DW_TAG_restrict_type is not supported in DWARF2
725   if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
726     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
727 
728   // Construct the context before querying for the existence of the DIE in case
729   // such construction creates the DIE.
730   auto *Context = resolve(Ty->getScope());
731   DIE *ContextDIE = getOrCreateContextDIE(Context);
732   assert(ContextDIE);
733 
734   if (DIE *TyDIE = getDIE(Ty))
735     return TyDIE;
736 
737   // Create new type.
738   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
739 
740   updateAcceleratorTables(Context, Ty, TyDIE);
741 
742   if (auto *BT = dyn_cast<DIBasicType>(Ty))
743     constructTypeDIE(TyDIE, BT);
744   else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
745     constructTypeDIE(TyDIE, STy);
746   else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
747     if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
748       if (MDString *TypeId = CTy->getRawIdentifier()) {
749         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
750         // Skip updating the accelerator tables since this is not the full type.
751         return &TyDIE;
752       }
753     constructTypeDIE(TyDIE, CTy);
754   } else {
755     constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
756   }
757 
758   return &TyDIE;
759 }
760 
761 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
762                                         const DIType *Ty, const DIE &TyDIE) {
763   if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
764     bool IsImplementation = 0;
765     if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
766       // A runtime language of 0 actually means C/C++ and that any
767       // non-negative value is some version of Objective-C/C++.
768       IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
769     }
770     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
771     DD->addAccelType(Ty->getName(), TyDIE, Flags);
772 
773     if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
774         isa<DINamespace>(Context))
775       addGlobalType(Ty, TyDIE, Context);
776   }
777 }
778 
779 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
780                         dwarf::Attribute Attribute) {
781   assert(Ty && "Trying to add a type that doesn't exist?");
782   addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
783 }
784 
785 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
786   if (!Context)
787     return "";
788 
789   // FIXME: Decide whether to implement this for non-C++ languages.
790   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
791     return "";
792 
793   std::string CS;
794   SmallVector<const DIScope *, 1> Parents;
795   while (!isa<DICompileUnit>(Context)) {
796     Parents.push_back(Context);
797     if (Context->getScope())
798       Context = resolve(Context->getScope());
799     else
800       // Structure, etc types will have a NULL context if they're at the top
801       // level.
802       break;
803   }
804 
805   // Reverse iterate over our list to go from the outermost construct to the
806   // innermost.
807   for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
808     StringRef Name = Ctx->getName();
809     if (Name.empty() && isa<DINamespace>(Ctx))
810       Name = "(anonymous namespace)";
811     if (!Name.empty()) {
812       CS += Name;
813       CS += "::";
814     }
815   }
816   return CS;
817 }
818 
819 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
820   // Get core information.
821   StringRef Name = BTy->getName();
822   // Add name if not anonymous or intermediate type.
823   if (!Name.empty())
824     addString(Buffer, dwarf::DW_AT_name, Name);
825 
826   // An unspecified type only has a name attribute.
827   if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
828     return;
829 
830   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
831           BTy->getEncoding());
832 
833   uint64_t Size = BTy->getSizeInBits() >> 3;
834   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
835 }
836 
837 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
838   // Get core information.
839   StringRef Name = DTy->getName();
840   uint64_t Size = DTy->getSizeInBits() >> 3;
841   uint16_t Tag = Buffer.getTag();
842 
843   // Map to main type, void will not have a type.
844   const DIType *FromTy = resolve(DTy->getBaseType());
845   if (FromTy)
846     addType(Buffer, FromTy);
847 
848   // Add name if not anonymous or intermediate type.
849   if (!Name.empty())
850     addString(Buffer, dwarf::DW_AT_name, Name);
851 
852   // Add size if non-zero (derived types might be zero-sized.)
853   if (Size && Tag != dwarf::DW_TAG_pointer_type
854            && Tag != dwarf::DW_TAG_ptr_to_member_type
855            && Tag != dwarf::DW_TAG_reference_type
856            && Tag != dwarf::DW_TAG_rvalue_reference_type)
857     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
858 
859   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
860     addDIEEntry(
861         Buffer, dwarf::DW_AT_containing_type,
862         *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
863   // Add source line info if available and TyDesc is not a forward declaration.
864   if (!DTy->isForwardDecl())
865     addSourceLine(Buffer, DTy);
866 }
867 
868 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
869   for (unsigned i = 1, N = Args.size(); i < N; ++i) {
870     const DIType *Ty = resolve(Args[i]);
871     if (!Ty) {
872       assert(i == N-1 && "Unspecified parameter must be the last argument");
873       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
874     } else {
875       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
876       addType(Arg, Ty);
877       if (Ty->isArtificial())
878         addFlag(Arg, dwarf::DW_AT_artificial);
879     }
880   }
881 }
882 
883 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
884   // Add return type.  A void return won't have a type.
885   auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
886   if (Elements.size())
887     if (auto RTy = resolve(Elements[0]))
888       addType(Buffer, RTy);
889 
890   bool isPrototyped = true;
891   if (Elements.size() == 2 && !Elements[1])
892     isPrototyped = false;
893 
894   constructSubprogramArguments(Buffer, Elements);
895 
896   // Add prototype flag if we're dealing with a C language and the function has
897   // been prototyped.
898   uint16_t Language = getLanguage();
899   if (isPrototyped &&
900       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
901        Language == dwarf::DW_LANG_ObjC))
902     addFlag(Buffer, dwarf::DW_AT_prototyped);
903 
904   if (CTy->isLValueReference())
905     addFlag(Buffer, dwarf::DW_AT_reference);
906 
907   if (CTy->isRValueReference())
908     addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
909 }
910 
911 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
912   if (CTy->isExternalTypeRef()) {
913     StringRef Identifier = CTy->getIdentifier();
914     assert(!Identifier.empty() && "external type ref without identifier");
915     addFlag(Buffer, dwarf::DW_AT_declaration);
916     return addDIETypeSignature(Buffer, dwarf::DW_AT_signature, Identifier);
917   }
918 
919   // Add name if not anonymous or intermediate type.
920   StringRef Name = CTy->getName();
921 
922   uint64_t Size = CTy->getSizeInBits() >> 3;
923   uint16_t Tag = Buffer.getTag();
924 
925   switch (Tag) {
926   case dwarf::DW_TAG_array_type:
927     constructArrayTypeDIE(Buffer, CTy);
928     break;
929   case dwarf::DW_TAG_enumeration_type:
930     constructEnumTypeDIE(Buffer, CTy);
931     break;
932   case dwarf::DW_TAG_structure_type:
933   case dwarf::DW_TAG_union_type:
934   case dwarf::DW_TAG_class_type: {
935     // Add elements to structure type.
936     DINodeArray Elements = CTy->getElements();
937     for (const auto *Element : Elements) {
938       if (!Element)
939         continue;
940       if (auto *SP = dyn_cast<DISubprogram>(Element))
941         getOrCreateSubprogramDIE(SP);
942       else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
943         if (DDTy->getTag() == dwarf::DW_TAG_friend) {
944           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
945           addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
946         } else if (DDTy->isStaticMember()) {
947           getOrCreateStaticMemberDIE(DDTy);
948         } else {
949           constructMemberDIE(Buffer, DDTy);
950         }
951       } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
952         DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
953         StringRef PropertyName = Property->getName();
954         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
955         if (Property->getType())
956           addType(ElemDie, resolve(Property->getType()));
957         addSourceLine(ElemDie, Property);
958         StringRef GetterName = Property->getGetterName();
959         if (!GetterName.empty())
960           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
961         StringRef SetterName = Property->getSetterName();
962         if (!SetterName.empty())
963           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
964         if (unsigned PropertyAttributes = Property->getAttributes())
965           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
966                   PropertyAttributes);
967       }
968     }
969 
970     if (CTy->isAppleBlockExtension())
971       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
972 
973     // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
974     // inside C++ composite types to point to the base class with the vtable.
975     if (auto *ContainingType =
976             dyn_cast_or_null<DICompositeType>(resolve(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 template parameters to a class, structure or union types.
984     // FIXME: The support isn't in the metadata for this yet.
985     if (Tag == dwarf::DW_TAG_class_type ||
986         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
987       addTemplateParams(Buffer, CTy->getTemplateParams());
988 
989     break;
990   }
991   default:
992     break;
993   }
994 
995   // Add name if not anonymous or intermediate type.
996   if (!Name.empty())
997     addString(Buffer, dwarf::DW_AT_name, Name);
998 
999   if (Tag == dwarf::DW_TAG_enumeration_type ||
1000       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1001       Tag == dwarf::DW_TAG_union_type) {
1002     // Add size if non-zero (derived types might be zero-sized.)
1003     // TODO: Do we care about size for enum forward declarations?
1004     if (Size)
1005       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1006     else if (!CTy->isForwardDecl())
1007       // Add zero size if it is not a forward declaration.
1008       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1009 
1010     // If we're a forward decl, say so.
1011     if (CTy->isForwardDecl())
1012       addFlag(Buffer, dwarf::DW_AT_declaration);
1013 
1014     // Add source line info if available.
1015     if (!CTy->isForwardDecl())
1016       addSourceLine(Buffer, CTy);
1017 
1018     // No harm in adding the runtime language to the declaration.
1019     unsigned RLang = CTy->getRuntimeLang();
1020     if (RLang)
1021       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1022               RLang);
1023   }
1024 }
1025 
1026 void DwarfUnit::constructTemplateTypeParameterDIE(
1027     DIE &Buffer, const DITemplateTypeParameter *TP) {
1028   DIE &ParamDIE =
1029       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1030   // Add the type if it exists, it could be void and therefore no type.
1031   if (TP->getType())
1032     addType(ParamDIE, resolve(TP->getType()));
1033   if (!TP->getName().empty())
1034     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1035 }
1036 
1037 void DwarfUnit::constructTemplateValueParameterDIE(
1038     DIE &Buffer, const DITemplateValueParameter *VP) {
1039   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1040 
1041   // Add the type if there is one, template template and template parameter
1042   // packs will not have a type.
1043   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1044     addType(ParamDIE, resolve(VP->getType()));
1045   if (!VP->getName().empty())
1046     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1047   if (Metadata *Val = VP->getValue()) {
1048     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1049       addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1050     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1051       // For declaration non-type template parameters (such as global values and
1052       // functions)
1053       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1054       addOpAddress(*Loc, Asm->getSymbol(GV));
1055       // Emit DW_OP_stack_value to use the address as the immediate value of the
1056       // parameter, rather than a pointer to it.
1057       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1058       addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1059     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1060       assert(isa<MDString>(Val));
1061       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1062                 cast<MDString>(Val)->getString());
1063     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1064       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1065     }
1066   }
1067 }
1068 
1069 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1070   // Construct the context before querying for the existence of the DIE in case
1071   // such construction creates the DIE.
1072   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1073 
1074   if (DIE *NDie = getDIE(NS))
1075     return NDie;
1076   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1077 
1078   StringRef Name = NS->getName();
1079   if (!Name.empty())
1080     addString(NDie, dwarf::DW_AT_name, NS->getName());
1081   else
1082     Name = "(anonymous namespace)";
1083   DD->addAccelNamespace(Name, NDie);
1084   addGlobalName(Name, NDie, NS->getScope());
1085   addSourceLine(NDie, NS);
1086   return &NDie;
1087 }
1088 
1089 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1090   // Construct the context before querying for the existence of the DIE in case
1091   // such construction creates the DIE.
1092   DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1093 
1094   if (DIE *MDie = getDIE(M))
1095     return MDie;
1096   DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1097 
1098   if (!M->getName().empty()) {
1099     addString(MDie, dwarf::DW_AT_name, M->getName());
1100     addGlobalName(M->getName(), MDie, M->getScope());
1101   }
1102   if (!M->getConfigurationMacros().empty())
1103     addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1104               M->getConfigurationMacros());
1105   if (!M->getIncludePath().empty())
1106     addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1107   if (!M->getISysRoot().empty())
1108     addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1109 
1110   return &MDie;
1111 }
1112 
1113 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1114   // Construct the context before querying for the existence of the DIE in case
1115   // such construction creates the DIE (as is the case for member function
1116   // declarations).
1117   DIE *ContextDIE =
1118       Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1119 
1120   if (DIE *SPDie = getDIE(SP))
1121     return SPDie;
1122 
1123   if (auto *SPDecl = SP->getDeclaration()) {
1124     if (!Minimal) {
1125       // Add subprogram definitions to the CU die directly.
1126       ContextDIE = &getUnitDie();
1127       // Build the decl now to ensure it precedes the definition.
1128       getOrCreateSubprogramDIE(SPDecl);
1129     }
1130   }
1131 
1132   // DW_TAG_inlined_subroutine may refer to this DIE.
1133   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1134 
1135   // Stop here and fill this in later, depending on whether or not this
1136   // subprogram turns out to have inlined instances or not.
1137   if (SP->isDefinition())
1138     return &SPDie;
1139 
1140   applySubprogramAttributes(SP, SPDie);
1141   return &SPDie;
1142 }
1143 
1144 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1145                                                     DIE &SPDie) {
1146   DIE *DeclDie = nullptr;
1147   StringRef DeclLinkageName;
1148   if (auto *SPDecl = SP->getDeclaration()) {
1149     DeclDie = getDIE(SPDecl);
1150     assert(DeclDie && "This DIE should've already been constructed when the "
1151                       "definition DIE was created in "
1152                       "getOrCreateSubprogramDIE");
1153     DeclLinkageName = SPDecl->getLinkageName();
1154     unsigned DeclID =
1155         getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1156     unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1157     if (DeclID != DefID)
1158       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1159 
1160     if (SP->getLine() != SPDecl->getLine())
1161       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1162   }
1163 
1164   // Add function template parameters.
1165   addTemplateParams(SPDie, SP->getTemplateParams());
1166 
1167   // Add the linkage name if we have one and it isn't in the Decl.
1168   StringRef LinkageName = SP->getLinkageName();
1169   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1170           LinkageName == DeclLinkageName) &&
1171          "decl has a linkage name and it is different");
1172   if (DeclLinkageName.empty())
1173     addLinkageName(SPDie, LinkageName);
1174 
1175   if (!DeclDie)
1176     return false;
1177 
1178   // Refer to the function declaration where all the other attributes will be
1179   // found.
1180   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1181   return true;
1182 }
1183 
1184 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1185                                           bool Minimal) {
1186   if (!Minimal)
1187     if (applySubprogramDefinitionAttributes(SP, SPDie))
1188       return;
1189 
1190   // Constructors and operators for anonymous aggregates do not have names.
1191   if (!SP->getName().empty())
1192     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1193 
1194   // Skip the rest of the attributes under -gmlt to save space.
1195   if (Minimal)
1196     return;
1197 
1198   addSourceLine(SPDie, SP);
1199 
1200   // Add the prototype if we have a prototype and we have a C like
1201   // language.
1202   uint16_t Language = getLanguage();
1203   if (SP->isPrototyped() &&
1204       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1205        Language == dwarf::DW_LANG_ObjC))
1206     addFlag(SPDie, dwarf::DW_AT_prototyped);
1207 
1208   DITypeRefArray Args;
1209   if (const DISubroutineType *SPTy = SP->getType())
1210     Args = SPTy->getTypeArray();
1211 
1212   // Add a return type. If this is a type like a C/C++ void type we don't add a
1213   // return type.
1214   if (Args.size())
1215     if (auto Ty = resolve(Args[0]))
1216       addType(SPDie, Ty);
1217 
1218   unsigned VK = SP->getVirtuality();
1219   if (VK) {
1220     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1221     if (SP->getVirtualIndex() != -1u) {
1222       DIELoc *Block = getDIELoc();
1223       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1224       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1225       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1226     }
1227     ContainingTypeMap.insert(
1228         std::make_pair(&SPDie, resolve(SP->getContainingType())));
1229   }
1230 
1231   if (!SP->isDefinition()) {
1232     addFlag(SPDie, dwarf::DW_AT_declaration);
1233 
1234     // Add arguments. Do not add arguments for subprogram definition. They will
1235     // be handled while processing variables.
1236     constructSubprogramArguments(SPDie, Args);
1237   }
1238 
1239   if (SP->isArtificial())
1240     addFlag(SPDie, dwarf::DW_AT_artificial);
1241 
1242   if (!SP->isLocalToUnit())
1243     addFlag(SPDie, dwarf::DW_AT_external);
1244 
1245   if (SP->isOptimized())
1246     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1247 
1248   if (unsigned isa = Asm->getISAEncoding())
1249     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1250 
1251   if (SP->isLValueReference())
1252     addFlag(SPDie, dwarf::DW_AT_reference);
1253 
1254   if (SP->isRValueReference())
1255     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1256 
1257   if (SP->isProtected())
1258     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1259             dwarf::DW_ACCESS_protected);
1260   else if (SP->isPrivate())
1261     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1262             dwarf::DW_ACCESS_private);
1263   else if (SP->isPublic())
1264     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1265             dwarf::DW_ACCESS_public);
1266 
1267   if (SP->isExplicit())
1268     addFlag(SPDie, dwarf::DW_AT_explicit);
1269 }
1270 
1271 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1272                                      DIE *IndexTy) {
1273   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1274   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1275 
1276   // The LowerBound value defines the lower bounds which is typically zero for
1277   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1278   // Count == -1 then the array is unbounded and we do not emit
1279   // DW_AT_lower_bound and DW_AT_count attributes.
1280   int64_t LowerBound = SR->getLowerBound();
1281   int64_t DefaultLowerBound = getDefaultLowerBound();
1282   int64_t Count = SR->getCount();
1283 
1284   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1285     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1286 
1287   if (Count != -1)
1288     // FIXME: An unbounded array should reference the expression that defines
1289     // the array.
1290     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1291 }
1292 
1293 DIE *DwarfUnit::getIndexTyDie() {
1294   if (IndexTyDie)
1295     return IndexTyDie;
1296   // Construct an integer type to use for indexes.
1297   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1298   addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1299   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1300   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1301           dwarf::DW_ATE_unsigned);
1302   return IndexTyDie;
1303 }
1304 
1305 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1306   if (CTy->isVector())
1307     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1308 
1309   // Emit the element type.
1310   addType(Buffer, resolve(CTy->getBaseType()));
1311 
1312   // Get an anonymous type for index type.
1313   // FIXME: This type should be passed down from the front end
1314   // as different languages may have different sizes for indexes.
1315   DIE *IdxTy = getIndexTyDie();
1316 
1317   // Add subranges to array type.
1318   DINodeArray Elements = CTy->getElements();
1319   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1320     // FIXME: Should this really be such a loose cast?
1321     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1322       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1323         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1324   }
1325 }
1326 
1327 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1328   DINodeArray Elements = CTy->getElements();
1329 
1330   // Add enumerators to enumeration type.
1331   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1332     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1333     if (Enum) {
1334       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1335       StringRef Name = Enum->getName();
1336       addString(Enumerator, dwarf::DW_AT_name, Name);
1337       int64_t Value = Enum->getValue();
1338       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1339               Value);
1340     }
1341   }
1342   const DIType *DTy = resolve(CTy->getBaseType());
1343   if (DTy) {
1344     addType(Buffer, DTy);
1345     addFlag(Buffer, dwarf::DW_AT_enum_class);
1346   }
1347 }
1348 
1349 void DwarfUnit::constructContainingTypeDIEs() {
1350   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1351        CI != CE; ++CI) {
1352     DIE &SPDie = *CI->first;
1353     const DINode *D = CI->second;
1354     if (!D)
1355       continue;
1356     DIE *NDie = getDIE(D);
1357     if (!NDie)
1358       continue;
1359     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1360   }
1361 }
1362 
1363 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1364   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1365   StringRef Name = DT->getName();
1366   if (!Name.empty())
1367     addString(MemberDie, dwarf::DW_AT_name, Name);
1368 
1369   addType(MemberDie, resolve(DT->getBaseType()));
1370 
1371   addSourceLine(MemberDie, DT);
1372 
1373   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1374 
1375     // For C++, virtual base classes are not at fixed offset. Use following
1376     // expression to extract appropriate offset from vtable.
1377     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1378 
1379     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1380     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1381     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1382     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1383     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1384     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1385     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1386     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1387 
1388     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1389   } else {
1390     uint64_t Size = DT->getSizeInBits();
1391     uint64_t FieldSize = getBaseTypeSize(DD, DT);
1392     uint64_t OffsetInBytes;
1393 
1394     if (FieldSize && Size != FieldSize) {
1395       // Handle bitfield, assume bytes are 8 bits.
1396       addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1397       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1398       //
1399       // The DWARF 2 DW_AT_bit_offset is counting the bits between the most
1400       // significant bit of the aligned storage unit containing the bit field to
1401       // the most significan bit of the bit field.
1402       //
1403       // FIXME: DWARF 4 states that DW_AT_data_bit_offset (which
1404       // counts from the beginning, regardless of endianness) should
1405       // be used instead.
1406       //
1407       //
1408       // Struct      Align       Align       Align
1409       // v           v           v           v
1410       // +-----------+-----*-----+-----*-----+--
1411       // | ...             |b1|b2|b3|b4|
1412       // +-----------+-----*-----+-----*-----+--
1413       // |           |     |<-- Size ->|     |
1414       // |<---- Offset --->|           |<--->|
1415       // |           |     |              \_ DW_AT_bit_offset (little endian)
1416       // |           |<--->|
1417       // |<--------->|  \_ StartBitOffset = DW_AT_bit_offset (big endian)
1418       //     \                            = DW_AT_data_bit_offset (biendian)
1419       //      \_ OffsetInBytes
1420       uint64_t Offset = DT->getOffsetInBits();
1421       uint64_t Align = DT->getAlignInBits() ? DT->getAlignInBits() : FieldSize;
1422       uint64_t AlignMask = ~(Align - 1);
1423       // The bits from the start of the storage unit to the start of the field.
1424       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1425       // The endian-dependent DWARF 2 offset.
1426       uint64_t DwarfBitOffset = Asm->getDataLayout().isLittleEndian()
1427         ? OffsetToAlignment(Offset + Size, Align)
1428         : StartBitOffset;
1429 
1430       // The byte offset of the field's aligned storage unit inside the struct.
1431       OffsetInBytes = (Offset - StartBitOffset) / 8;
1432       addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, DwarfBitOffset);
1433     } else
1434       // This is not a bitfield.
1435       OffsetInBytes = DT->getOffsetInBits() / 8;
1436 
1437     if (DD->getDwarfVersion() <= 2) {
1438       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1439       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1440       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1441       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1442     } else
1443       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1444               OffsetInBytes);
1445   }
1446 
1447   if (DT->isProtected())
1448     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1449             dwarf::DW_ACCESS_protected);
1450   else if (DT->isPrivate())
1451     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1452             dwarf::DW_ACCESS_private);
1453   // Otherwise C++ member and base classes are considered public.
1454   else if (DT->isPublic())
1455     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1456             dwarf::DW_ACCESS_public);
1457   if (DT->isVirtual())
1458     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1459             dwarf::DW_VIRTUALITY_virtual);
1460 
1461   // Objective-C properties.
1462   if (DINode *PNode = DT->getObjCProperty())
1463     if (DIE *PDie = getDIE(PNode))
1464       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1465                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1466 
1467   if (DT->isArtificial())
1468     addFlag(MemberDie, dwarf::DW_AT_artificial);
1469 }
1470 
1471 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1472   if (!DT)
1473     return nullptr;
1474 
1475   // Construct the context before querying for the existence of the DIE in case
1476   // such construction creates the DIE.
1477   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1478   assert(dwarf::isType(ContextDIE->getTag()) &&
1479          "Static member should belong to a type.");
1480 
1481   if (DIE *StaticMemberDIE = getDIE(DT))
1482     return StaticMemberDIE;
1483 
1484   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1485 
1486   const DIType *Ty = resolve(DT->getBaseType());
1487 
1488   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1489   addType(StaticMemberDIE, Ty);
1490   addSourceLine(StaticMemberDIE, DT);
1491   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1492   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1493 
1494   // FIXME: We could omit private if the parent is a class_type, and
1495   // public if the parent is something else.
1496   if (DT->isProtected())
1497     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1498             dwarf::DW_ACCESS_protected);
1499   else if (DT->isPrivate())
1500     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1501             dwarf::DW_ACCESS_private);
1502   else if (DT->isPublic())
1503     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1504             dwarf::DW_ACCESS_public);
1505 
1506   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1507     addConstantValue(StaticMemberDIE, CI, Ty);
1508   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1509     addConstantFPValue(StaticMemberDIE, CFP);
1510 
1511   return &StaticMemberDIE;
1512 }
1513 
1514 void DwarfUnit::emitHeader(bool UseOffsets) {
1515   // Emit size of content not including length itself
1516   Asm->OutStreamer->AddComment("Length of Unit");
1517   Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1518 
1519   Asm->OutStreamer->AddComment("DWARF version number");
1520   Asm->EmitInt16(DD->getDwarfVersion());
1521   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1522 
1523   // We share one abbreviations table across all units so it's always at the
1524   // start of the section. Use a relocatable offset where needed to ensure
1525   // linking doesn't invalidate that offset.
1526   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1527   if (UseOffsets)
1528     Asm->EmitInt32(0);
1529   else
1530     Asm->emitDwarfSymbolReference(
1531         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1532 
1533   Asm->OutStreamer->AddComment("Address Size (in bytes)");
1534   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1535 }
1536 
1537 void DwarfUnit::initSection(MCSection *Section) {
1538   assert(!this->Section);
1539   this->Section = Section;
1540 }
1541 
1542 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1543   DwarfUnit::emitHeader(UseOffsets);
1544   Asm->OutStreamer->AddComment("Type Signature");
1545   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1546   Asm->OutStreamer->AddComment("Type DIE Offset");
1547   // In a skeleton type unit there is no type DIE so emit a zero offset.
1548   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1549                                  sizeof(Ty->getOffset()));
1550 }
1551 
1552 bool DwarfTypeUnit::isDwoUnit() const {
1553   // Since there are no skeleton type units, all type units are dwo type units
1554   // when split DWARF is being used.
1555   return DD->useSplitDwarf();
1556 }
1557