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