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