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