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