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