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