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