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