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