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