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