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