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