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