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