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