]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/AsmPrinter/DwarfUnit.cpp
Move the AddressPool from DwarfFile to DwarfDebug.
[opencl/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 //===----------------------------------------------------------------------===//
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"
34 using namespace llvm;
36 #define DEBUG_TYPE "dwarfdebug"
38 static cl::opt<bool>
39 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
40                        cl::desc("Generate DWARF4 type units."),
41                        cl::init(false));
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 }
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 }
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 }
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 }
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 }
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;
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;
97   case dwarf::DW_LANG_Fortran77:
98   case dwarf::DW_LANG_Fortran90:
99   case dwarf::DW_LANG_Fortran95:
100     return 1;
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;
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   }
123   return -1;
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;
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);
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));
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);
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);
180 void DwarfUnit::addUInt(DIE *Block, dwarf::Form Form, uint64_t Integer) {
181   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
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);
194 void DwarfUnit::addSInt(DIELoc *Die, Optional<dwarf::Form> Form,
195                         int64_t Integer) {
196   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
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) {
207   if (!DD->useSplitDwarf())
208     return addLocalString(Die, Attribute, String);
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);
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);
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);
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);
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);
257 void DwarfUnit::addLabel(DIELoc *Die, dwarf::Form Form, const MCSymbol *Label) {
258   addLabel(Die, (dwarf::Attribute)0, Form, Label);
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);
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);
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) {
287   if (!DD->useSplitDwarf())
288     return addLocalLabelAddress(Die, Attribute, Label);
290   if (Label)
291     DD->addArangeLabel(SymbolCU(this, Label));
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);
298 void DwarfCompileUnit::addLocalLabelAddress(DIE *Die,
299                                             dwarf::Attribute Attribute,
300                                             const MCSymbol *Label) {
301   if (Label)
302     DD->addArangeLabel(SymbolCU(this, Label));
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   }
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.
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());
324 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
325   return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
326                         : getCU().getOrCreateSourceID(FileName, DirName);
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   }
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);
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);
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));
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));
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);
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;
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);
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);
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;
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);
425 /// addSourceLine - Add location information to specified debug information
426 /// entry.
427 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
428   assert(V.isVariable());
430   addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
431                 V.getContext().getDirectory());
434 /// addSourceLine - Add location information to specified debug information
435 /// entry.
436 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
437   assert(G.isGlobalVariable());
439   addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
442 /// addSourceLine - Add location information to specified debug information
443 /// entry.
444 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
445   assert(SP.isSubprogram());
447   addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
450 /// addSourceLine - Add location information to specified debug information
451 /// entry.
452 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
453   assert(Ty.isType());
455   addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
458 /// addSourceLine - Add location information to specified debug information
459 /// entry.
460 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
461   assert(Ty.isObjCProperty());
463   DIFile File = Ty.getFile();
464   addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
465                 File.getDirectory());
468 /// addSourceLine - Add location information to specified debug information
469 /// entry.
470 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
471   assert(NS.Verify());
473   addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
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());
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;
495   unsigned Idx = 0;
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   }
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   }
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   }
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   }
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);
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();
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   }
567   // Now attach the location information to the DIE.
568   addBlock(Die, Attribute, Loc);
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());
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   }
605   // Now attach the location information to the DIE.
606   addBlock(Die, Attribute, Loc);
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.
615    However, as far as the original *programmer* is concerned, the variable
616    should still have type 'SomeType', as originally declared.
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.
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.
631    The struct will look something like:
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    };
641    If we are given the struct directly (as our starting point) we
642    need to tell the debugger to:
644    1).  Add the offset of the forwarding field.
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).
649    3).  Add the offset for the field VarName, to find the actual variable.
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:
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>
661    That is what this function does.  */
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;
677   StringRef varName = DV.getName();
679   if (Tag == dwarf::DW_TAG_pointer_type) {
680     DIDerivedType DTy(Ty);
681     TmpTy = resolve(DTy.getTypeDerivedFrom());
682     isPointer = true;
683   }
685   DICompositeType blockStruct(TmpTy);
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;
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   }
702   // Get the offsets for the forwarding field and the variable field.
703   unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
704   unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
706   // Decode the original location, and use that as the start of the byref
707   // variable's location.
708   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
710   if (Location.isReg())
711     addRegisterOp(Loc, Location.getReg());
712   else
713     addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
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);
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   }
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);
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   }
740   // Now attach the location information to the DIE.
741   addBlock(Die, Attribute, Loc);
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;
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()));
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;
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();
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();
784   DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
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();
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();
798   if (BaseType.isDerivedType())
799     return getBaseTypeSize(DD, DIDerivedType(BaseType));
801   return BaseType.getSizeInBits();
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;
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   }
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());
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();
849   // Get the raw data form of the floating point.
850   const APInt FltVal = FPImm.bitcastToAPInt();
851   const char *FltPtr = (const char *)FltVal.getRawData();
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);
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]);
863   addBlock(Die, dwarf::DW_AT_const_value, Block);
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);
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);
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     }
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   }
913   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
915   // Get the raw data form of the large APInt.
916   const uint64_t *Ptr64 = Val.getRawData();
918   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
919   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
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   }
931   addBlock(Die, dwarf::DW_AT_const_value, Block);
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   }
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);
961 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
962   DIScope Context = resolve(Ty.getContext());
963   DIE *ContextDIE = getOrCreateContextDIE(Context);
965   DIE *TyDIE = getDIE(Ty);
966   if (TyDIE)
967     return TyDIE;
969   // Create new type.
970   TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
972   constructTypeDIE(*TyDIE, Ty);
974   updateAcceleratorTables(Context, Ty, TyDIE);
975   return TyDIE;
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;
984   DIType Ty(TyNode);
985   assert(Ty.isType());
986   assert(Ty == resolve(Ty.getRef()) &&
987          "type was not uniqued, possible ODR violation.");
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()));
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);
999   DIE *TyDIE = getDIE(Ty);
1000   if (TyDIE)
1001     return TyDIE;
1003   // Create new type.
1004   TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1006   updateAcceleratorTables(Context, Ty, TyDIE);
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   }
1024   return TyDIE;
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));
1040     if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1041          Context.isNameSpace()) &&
1042         getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1043       GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1044   }
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?");
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   }
1059   // Construct type.
1060   DIE *Buffer = getOrCreateTypeDIE(Ty);
1062   // Set up proxy.
1063   Entry = createDIEEntry(Buffer);
1064   insertDIEEntry(Ty, Entry);
1065   addDIEEntry(Entity, Attribute, Entry);
1068 // Accelerator table mutators - add each name along with its companion
1069 // DIE to the proper table while ensuring that the name that we're going
1070 // to reference is in the string table. We do this since the names we
1071 // add may not only be identical to the names in the DIE.
1072 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1073   if (!DD->useDwarfAccelTables())
1074     return;
1075   DU->getStringPoolEntry(Name);
1076   std::vector<const DIE *> &DIEs = AccelNames[Name];
1077   DIEs.push_back(Die);
1080 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1081   if (!DD->useDwarfAccelTables())
1082     return;
1083   DU->getStringPoolEntry(Name);
1084   std::vector<const DIE *> &DIEs = AccelObjC[Name];
1085   DIEs.push_back(Die);
1088 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1089   if (!DD->useDwarfAccelTables())
1090     return;
1091   DU->getStringPoolEntry(Name);
1092   std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1093   DIEs.push_back(Die);
1096 void DwarfUnit::addAccelType(StringRef Name,
1097                              std::pair<const DIE *, unsigned> Die) {
1098   if (!DD->useDwarfAccelTables())
1099     return;
1100   DU->getStringPoolEntry(Name);
1101   std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1102   DIEs.push_back(Die);
1105 /// addGlobalName - Add a new global name to the compile unit.
1106 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1107   if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1108     return;
1109   std::string FullName = getParentContextString(Context) + Name.str();
1110   GlobalNames[FullName] = Die;
1113 /// getParentContextString - Walks the metadata parent chain in a language
1114 /// specific manner (using the compile unit language) and returns
1115 /// it as a string. This is done at the metadata level because DIEs may
1116 /// not currently have been added to the parent context and walking the
1117 /// DIEs looking for names is more expensive than walking the metadata.
1118 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1119   if (!Context)
1120     return "";
1122   // FIXME: Decide whether to implement this for non-C++ languages.
1123   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1124     return "";
1126   std::string CS;
1127   SmallVector<DIScope, 1> Parents;
1128   while (!Context.isCompileUnit()) {
1129     Parents.push_back(Context);
1130     if (Context.getContext())
1131       Context = resolve(Context.getContext());
1132     else
1133       // Structure, etc types will have a NULL context if they're at the top
1134       // level.
1135       break;
1136   }
1138   // Reverse iterate over our list to go from the outermost construct to the
1139   // innermost.
1140   for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1141                                                   E = Parents.rend();
1142        I != E; ++I) {
1143     DIScope Ctx = *I;
1144     StringRef Name = Ctx.getName();
1145     if (!Name.empty()) {
1146       CS += Name;
1147       CS += "::";
1148     }
1149   }
1150   return CS;
1153 /// constructTypeDIE - Construct basic type die from DIBasicType.
1154 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1155   // Get core information.
1156   StringRef Name = BTy.getName();
1157   // Add name if not anonymous or intermediate type.
1158   if (!Name.empty())
1159     addString(&Buffer, dwarf::DW_AT_name, Name);
1161   // An unspecified type only has a name attribute.
1162   if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1163     return;
1165   addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1166           BTy.getEncoding());
1168   uint64_t Size = BTy.getSizeInBits() >> 3;
1169   addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1172 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1173 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1174   // Get core information.
1175   StringRef Name = DTy.getName();
1176   uint64_t Size = DTy.getSizeInBits() >> 3;
1177   uint16_t Tag = Buffer.getTag();
1179   // Map to main type, void will not have a type.
1180   DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1181   if (FromTy)
1182     addType(&Buffer, FromTy);
1184   // Add name if not anonymous or intermediate type.
1185   if (!Name.empty())
1186     addString(&Buffer, dwarf::DW_AT_name, Name);
1188   // Add size if non-zero (derived types might be zero-sized.)
1189   if (Size && Tag != dwarf::DW_TAG_pointer_type)
1190     addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1192   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1193     addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1194                 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1195   // Add source line info if available and TyDesc is not a forward declaration.
1196   if (!DTy.isForwardDecl())
1197     addSourceLine(&Buffer, DTy);
1200 /// constructSubprogramArguments - Construct function argument DIEs.
1201 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DIArray Args) {
1202   for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1203     DIDescriptor Ty = Args.getElement(i);
1204     if (Ty.isUnspecifiedParameter()) {
1205       assert(i == N-1 && "Unspecified parameter must be the last argument");
1206       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1207     } else {
1208       DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1209       addType(Arg, DIType(Ty));
1210       if (DIType(Ty).isArtificial())
1211         addFlag(Arg, dwarf::DW_AT_artificial);
1212     }
1213   }
1216 /// constructTypeDIE - Construct type DIE from DICompositeType.
1217 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1218   // Add name if not anonymous or intermediate type.
1219   StringRef Name = CTy.getName();
1221   uint64_t Size = CTy.getSizeInBits() >> 3;
1222   uint16_t Tag = Buffer.getTag();
1224   switch (Tag) {
1225   case dwarf::DW_TAG_array_type:
1226     constructArrayTypeDIE(Buffer, CTy);
1227     break;
1228   case dwarf::DW_TAG_enumeration_type:
1229     constructEnumTypeDIE(Buffer, CTy);
1230     break;
1231   case dwarf::DW_TAG_subroutine_type: {
1232     // Add return type. A void return won't have a type.
1233     DIArray Elements = CTy.getTypeArray();
1234     DIType RTy(Elements.getElement(0));
1235     if (RTy)
1236       addType(&Buffer, RTy);
1238     bool isPrototyped = true;
1239     if (Elements.getNumElements() == 2 &&
1240         Elements.getElement(1).isUnspecifiedParameter())
1241       isPrototyped = false;
1243     constructSubprogramArguments(Buffer, Elements);
1245     // Add prototype flag if we're dealing with a C language and the
1246     // function has been prototyped.
1247     uint16_t Language = getLanguage();
1248     if (isPrototyped &&
1249         (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1250          Language == dwarf::DW_LANG_ObjC))
1251       addFlag(&Buffer, dwarf::DW_AT_prototyped);
1253     if (CTy.isLValueReference())
1254       addFlag(&Buffer, dwarf::DW_AT_reference);
1256     if (CTy.isRValueReference())
1257       addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1258   } break;
1259   case dwarf::DW_TAG_structure_type:
1260   case dwarf::DW_TAG_union_type:
1261   case dwarf::DW_TAG_class_type: {
1262     // Add elements to structure type.
1263     DIArray Elements = CTy.getTypeArray();
1264     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1265       DIDescriptor Element = Elements.getElement(i);
1266       DIE *ElemDie = NULL;
1267       if (Element.isSubprogram())
1268         ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1269       else if (Element.isDerivedType()) {
1270         DIDerivedType DDTy(Element);
1271         if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1272           ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1273           addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1274                   dwarf::DW_AT_friend);
1275         } else if (DDTy.isStaticMember()) {
1276           getOrCreateStaticMemberDIE(DDTy);
1277         } else {
1278           constructMemberDIE(Buffer, DDTy);
1279         }
1280       } else if (Element.isObjCProperty()) {
1281         DIObjCProperty Property(Element);
1282         ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1283         StringRef PropertyName = Property.getObjCPropertyName();
1284         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1285         if (Property.getType())
1286           addType(ElemDie, Property.getType());
1287         addSourceLine(ElemDie, Property);
1288         StringRef GetterName = Property.getObjCPropertyGetterName();
1289         if (!GetterName.empty())
1290           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1291         StringRef SetterName = Property.getObjCPropertySetterName();
1292         if (!SetterName.empty())
1293           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1294         unsigned PropertyAttributes = 0;
1295         if (Property.isReadOnlyObjCProperty())
1296           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1297         if (Property.isReadWriteObjCProperty())
1298           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1299         if (Property.isAssignObjCProperty())
1300           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1301         if (Property.isRetainObjCProperty())
1302           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1303         if (Property.isCopyObjCProperty())
1304           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1305         if (Property.isNonAtomicObjCProperty())
1306           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1307         if (PropertyAttributes)
1308           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1309                   PropertyAttributes);
1311         DIEEntry *Entry = getDIEEntry(Element);
1312         if (!Entry) {
1313           Entry = createDIEEntry(ElemDie);
1314           insertDIEEntry(Element, Entry);
1315         }
1316       } else
1317         continue;
1318     }
1320     if (CTy.isAppleBlockExtension())
1321       addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1323     DICompositeType ContainingType(resolve(CTy.getContainingType()));
1324     if (ContainingType)
1325       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1326                   getOrCreateTypeDIE(ContainingType));
1328     if (CTy.isObjcClassComplete())
1329       addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1331     // Add template parameters to a class, structure or union types.
1332     // FIXME: The support isn't in the metadata for this yet.
1333     if (Tag == dwarf::DW_TAG_class_type ||
1334         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1335       addTemplateParams(Buffer, CTy.getTemplateParams());
1337     break;
1338   }
1339   default:
1340     break;
1341   }
1343   // Add name if not anonymous or intermediate type.
1344   if (!Name.empty())
1345     addString(&Buffer, dwarf::DW_AT_name, Name);
1347   if (Tag == dwarf::DW_TAG_enumeration_type ||
1348       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1349       Tag == dwarf::DW_TAG_union_type) {
1350     // Add size if non-zero (derived types might be zero-sized.)
1351     // TODO: Do we care about size for enum forward declarations?
1352     if (Size)
1353       addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1354     else if (!CTy.isForwardDecl())
1355       // Add zero size if it is not a forward declaration.
1356       addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1358     // If we're a forward decl, say so.
1359     if (CTy.isForwardDecl())
1360       addFlag(&Buffer, dwarf::DW_AT_declaration);
1362     // Add source line info if available.
1363     if (!CTy.isForwardDecl())
1364       addSourceLine(&Buffer, CTy);
1366     // No harm in adding the runtime language to the declaration.
1367     unsigned RLang = CTy.getRunTimeLang();
1368     if (RLang)
1369       addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1370               RLang);
1371   }
1374 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1375 /// DITemplateTypeParameter.
1376 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1377                                                   DITemplateTypeParameter TP) {
1378   DIE *ParamDIE =
1379       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1380   // Add the type if it exists, it could be void and therefore no type.
1381   if (TP.getType())
1382     addType(ParamDIE, resolve(TP.getType()));
1383   if (!TP.getName().empty())
1384     addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1387 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1388 /// DITemplateValueParameter.
1389 void
1390 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1391                                               DITemplateValueParameter VP) {
1392   DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1394   // Add the type if there is one, template template and template parameter
1395   // packs will not have a type.
1396   if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1397     addType(ParamDIE, resolve(VP.getType()));
1398   if (!VP.getName().empty())
1399     addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1400   if (Value *Val = VP.getValue()) {
1401     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1402       addConstantValue(ParamDIE, CI,
1403                        isUnsignedDIType(DD, resolve(VP.getType())));
1404     else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1405       // For declaration non-type template parameters (such as global values and
1406       // functions)
1407       DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1408       addOpAddress(Loc, Asm->getSymbol(GV));
1409       // Emit DW_OP_stack_value to use the address as the immediate value of the
1410       // parameter, rather than a pointer to it.
1411       addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1412       addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1413     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1414       assert(isa<MDString>(Val));
1415       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1416                 cast<MDString>(Val)->getString());
1417     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1418       assert(isa<MDNode>(Val));
1419       DIArray A(cast<MDNode>(Val));
1420       addTemplateParams(*ParamDIE, A);
1421     }
1422   }
1425 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1426 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1427   // Construct the context before querying for the existence of the DIE in case
1428   // such construction creates the DIE.
1429   DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1431   DIE *NDie = getDIE(NS);
1432   if (NDie)
1433     return NDie;
1434   NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1436   if (!NS.getName().empty()) {
1437     addString(NDie, dwarf::DW_AT_name, NS.getName());
1438     addAccelNamespace(NS.getName(), NDie);
1439     addGlobalName(NS.getName(), NDie, NS.getContext());
1440   } else
1441     addAccelNamespace("(anonymous namespace)", NDie);
1442   addSourceLine(NDie, NS);
1443   return NDie;
1446 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1447 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1448   // Construct the context before querying for the existence of the DIE in case
1449   // such construction creates the DIE (as is the case for member function
1450   // declarations).
1451   DIScope Context = resolve(SP.getContext());
1452   DIE *ContextDIE = getOrCreateContextDIE(Context);
1454   // Unique declarations based on the ODR, where applicable.
1455   SP = DISubprogram(DD->resolve(SP.getRef()));
1456   assert(SP.Verify());
1458   DIE *SPDie = getDIE(SP);
1459   if (SPDie)
1460     return SPDie;
1462   DISubprogram SPDecl = SP.getFunctionDeclaration();
1463   if (SPDecl.isSubprogram())
1464     // Add subprogram definitions to the CU die directly.
1465     ContextDIE = UnitDie.get();
1467   // DW_TAG_inlined_subroutine may refer to this DIE.
1468   SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1470   DIE *DeclDie = NULL;
1471   if (SPDecl.isSubprogram())
1472     DeclDie = getOrCreateSubprogramDIE(SPDecl);
1474   // Add function template parameters.
1475   addTemplateParams(*SPDie, SP.getTemplateParams());
1477   if (DeclDie)
1478     // Refer function declaration directly.
1479     addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1481   // Add the linkage name if we have one and it isn't in the Decl.
1482   StringRef LinkageName = SP.getLinkageName();
1483   if (!LinkageName.empty()) {
1484     if (SPDecl.isSubprogram() && !SPDecl.getLinkageName().empty())
1485       assert(SPDecl.getLinkageName() == SP.getLinkageName() &&
1486              "decl has a linkage name and it is different");
1487     else
1488       addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1489                 GlobalValue::getRealLinkageName(LinkageName));
1490   }
1492   // If this DIE is going to refer declaration info using AT_specification
1493   // then there is no need to add other attributes.
1494   if (DeclDie)
1495     return SPDie;
1497   // Constructors and operators for anonymous aggregates do not have names.
1498   if (!SP.getName().empty())
1499     addString(SPDie, dwarf::DW_AT_name, SP.getName());
1501   addSourceLine(SPDie, SP);
1503   // Add the prototype if we have a prototype and we have a C like
1504   // language.
1505   uint16_t Language = getLanguage();
1506   if (SP.isPrototyped() &&
1507       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1508        Language == dwarf::DW_LANG_ObjC))
1509     addFlag(SPDie, dwarf::DW_AT_prototyped);
1511   DICompositeType SPTy = SP.getType();
1512   assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1513          "the type of a subprogram should be a subroutine");
1515   DIArray Args = SPTy.getTypeArray();
1516   // Add a return type. If this is a type like a C/C++ void type we don't add a
1517   // return type.
1518   if (Args.getElement(0))
1519     addType(SPDie, DIType(Args.getElement(0)));
1521   unsigned VK = SP.getVirtuality();
1522   if (VK) {
1523     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1524     DIELoc *Block = getDIELoc();
1525     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1526     addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1527     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1528     ContainingTypeMap.insert(
1529         std::make_pair(SPDie, resolve(SP.getContainingType())));
1530   }
1532   if (!SP.isDefinition()) {
1533     addFlag(SPDie, dwarf::DW_AT_declaration);
1535     // Add arguments. Do not add arguments for subprogram definition. They will
1536     // be handled while processing variables.
1537     constructSubprogramArguments(*SPDie, Args);
1538   }
1540   if (SP.isArtificial())
1541     addFlag(SPDie, dwarf::DW_AT_artificial);
1543   if (!SP.isLocalToUnit())
1544     addFlag(SPDie, dwarf::DW_AT_external);
1546   if (SP.isOptimized())
1547     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1549   if (unsigned isa = Asm->getISAEncoding()) {
1550     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1551   }
1553   if (SP.isLValueReference())
1554     addFlag(SPDie, dwarf::DW_AT_reference);
1556   if (SP.isRValueReference())
1557     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1559   if (SP.isProtected())
1560     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1561             dwarf::DW_ACCESS_protected);
1562   else if (SP.isPrivate())
1563     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1564             dwarf::DW_ACCESS_private);
1565   else
1566     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1567             dwarf::DW_ACCESS_public);
1569   if (SP.isExplicit())
1570     addFlag(SPDie, dwarf::DW_AT_explicit);
1572   return SPDie;
1575 // Return const expression if value is a GEP to access merged global
1576 // constant. e.g.
1577 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1578 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1579   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1580   if (!CE || CE->getNumOperands() != 3 ||
1581       CE->getOpcode() != Instruction::GetElementPtr)
1582     return NULL;
1584   // First operand points to a global struct.
1585   Value *Ptr = CE->getOperand(0);
1586   if (!isa<GlobalValue>(Ptr) ||
1587       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1588     return NULL;
1590   // Second operand is zero.
1591   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1592   if (!CI || !CI->isZero())
1593     return NULL;
1595   // Third operand is offset.
1596   if (!isa<ConstantInt>(CE->getOperand(2)))
1597     return NULL;
1599   return CE;
1602 /// createGlobalVariableDIE - create global variable DIE.
1603 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1604   // Check for pre-existence.
1605   if (getDIE(GV))
1606     return;
1608   assert(GV.isGlobalVariable());
1610   DIScope GVContext = GV.getContext();
1611   DIType GTy = DD->resolve(GV.getType());
1613   // If this is a static data member definition, some attributes belong
1614   // to the declaration DIE.
1615   DIE *VariableDIE = NULL;
1616   bool IsStaticMember = false;
1617   DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1618   if (SDMDecl.Verify()) {
1619     assert(SDMDecl.isStaticMember() && "Expected static member decl");
1620     // We need the declaration DIE that is in the static member's class.
1621     VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1622     IsStaticMember = true;
1623   }
1625   // If this is not a static data member definition, create the variable
1626   // DIE and add the initial set of attributes to it.
1627   if (!VariableDIE) {
1628     // Construct the context before querying for the existence of the DIE in
1629     // case such construction creates the DIE.
1630     DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1632     // Add to map.
1633     VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1635     // Add name and type.
1636     addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1637     addType(VariableDIE, GTy);
1639     // Add scoping info.
1640     if (!GV.isLocalToUnit())
1641       addFlag(VariableDIE, dwarf::DW_AT_external);
1643     // Add line number info.
1644     addSourceLine(VariableDIE, GV);
1645   }
1647   // Add location.
1648   bool addToAccelTable = false;
1649   DIE *VariableSpecDIE = NULL;
1650   bool isGlobalVariable = GV.getGlobal() != NULL;
1651   if (isGlobalVariable) {
1652     addToAccelTable = true;
1653     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1654     const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1655     if (GV.getGlobal()->isThreadLocal()) {
1656       // FIXME: Make this work with -gsplit-dwarf.
1657       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1658       assert((PointerSize == 4 || PointerSize == 8) &&
1659              "Add support for other sizes if necessary");
1660       // Based on GCC's support for TLS:
1661       if (!DD->useSplitDwarf()) {
1662         // 1) Start with a constNu of the appropriate pointer size
1663         addUInt(Loc, dwarf::DW_FORM_data1,
1664                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1665         // 2) containing the (relocated) offset of the TLS variable
1666         //    within the module's TLS block.
1667         addExpr(Loc, dwarf::DW_FORM_udata,
1668                 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1669       } else {
1670         addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1671         addUInt(Loc, dwarf::DW_FORM_udata,
1672                 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1673       }
1674       // 3) followed by a custom OP to make the debugger do a TLS lookup.
1675       addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1676     } else {
1677       DD->addArangeLabel(SymbolCU(this, Sym));
1678       addOpAddress(Loc, Sym);
1679     }
1680     // Do not create specification DIE if context is either compile unit
1681     // or a subprogram.
1682     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1683         !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1684       // Create specification DIE.
1685       VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1686       addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1687       addBlock(VariableSpecDIE, dwarf::DW_AT_location, Loc);
1688       // A static member's declaration is already flagged as such.
1689       if (!SDMDecl.Verify())
1690         addFlag(VariableDIE, dwarf::DW_AT_declaration);
1691     } else {
1692       addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1693     }
1694     // Add the linkage name.
1695     StringRef LinkageName = GV.getLinkageName();
1696     if (!LinkageName.empty())
1697       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1698       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1699       // TAG_variable.
1700       addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1701                                                   : VariableDIE,
1702                 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1703                                            : dwarf::DW_AT_MIPS_linkage_name,
1704                 GlobalValue::getRealLinkageName(LinkageName));
1705   } else if (const ConstantInt *CI =
1706                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1707     // AT_const_value was added when the static member was created. To avoid
1708     // emitting AT_const_value multiple times, we only add AT_const_value when
1709     // it is not a static member.
1710     if (!IsStaticMember)
1711       addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1712   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1713     addToAccelTable = true;
1714     // GV is a merged global.
1715     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1716     Value *Ptr = CE->getOperand(0);
1717     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1718     DD->addArangeLabel(SymbolCU(this, Sym));
1719     addOpAddress(Loc, Sym);
1720     addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1721     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1722     addUInt(Loc, dwarf::DW_FORM_udata,
1723             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1724     addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1725     addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1726   }
1728   if (addToAccelTable) {
1729     DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1730     addAccelName(GV.getName(), AddrDIE);
1732     // If the linkage name is different than the name, go ahead and output
1733     // that as well into the name table.
1734     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1735       addAccelName(GV.getLinkageName(), AddrDIE);
1736   }
1738   if (!GV.isLocalToUnit())
1739     addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1740                   GV.getContext());
1743 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1744 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1745   DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1746   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1748   // The LowerBound value defines the lower bounds which is typically zero for
1749   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1750   // Count == -1 then the array is unbounded and we do not emit
1751   // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1752   // Count == 0, then the array has zero elements in which case we do not emit
1753   // an upper bound.
1754   int64_t LowerBound = SR.getLo();
1755   int64_t DefaultLowerBound = getDefaultLowerBound();
1756   int64_t Count = SR.getCount();
1758   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1759     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1761   if (Count != -1 && Count != 0)
1762     // FIXME: An unbounded array should reference the expression that defines
1763     // the array.
1764     addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1765             LowerBound + Count - 1);
1768 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1769 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1770   if (CTy.isVector())
1771     addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1773   // Emit the element type.
1774   addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1776   // Get an anonymous type for index type.
1777   // FIXME: This type should be passed down from the front end
1778   // as different languages may have different sizes for indexes.
1779   DIE *IdxTy = getIndexTyDie();
1780   if (!IdxTy) {
1781     // Construct an integer type to use for indexes.
1782     IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1783     addString(IdxTy, dwarf::DW_AT_name, "sizetype");
1784     addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1785     addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1786             dwarf::DW_ATE_unsigned);
1787     setIndexTyDie(IdxTy);
1788   }
1790   // Add subranges to array type.
1791   DIArray Elements = CTy.getTypeArray();
1792   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1793     DIDescriptor Element = Elements.getElement(i);
1794     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1795       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1796   }
1799 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1800 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1801   DIArray Elements = CTy.getTypeArray();
1803   // Add enumerators to enumeration type.
1804   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1805     DIEnumerator Enum(Elements.getElement(i));
1806     if (Enum.isEnumerator()) {
1807       DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1808       StringRef Name = Enum.getName();
1809       addString(Enumerator, dwarf::DW_AT_name, Name);
1810       int64_t Value = Enum.getEnumValue();
1811       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1812               Value);
1813     }
1814   }
1815   DIType DTy = resolve(CTy.getTypeDerivedFrom());
1816   if (DTy) {
1817     addType(&Buffer, DTy);
1818     addFlag(&Buffer, dwarf::DW_AT_enum_class);
1819   }
1822 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1823 /// vtables.
1824 void DwarfUnit::constructContainingTypeDIEs() {
1825   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1826                                                  CE = ContainingTypeMap.end();
1827        CI != CE; ++CI) {
1828     DIE *SPDie = CI->first;
1829     DIDescriptor D(CI->second);
1830     if (!D)
1831       continue;
1832     DIE *NDie = getDIE(D);
1833     if (!NDie)
1834       continue;
1835     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1836   }
1839 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1840 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1841   StringRef Name = DV.getName();
1843   // Define variable debug information entry.
1844   DIE *VariableDie = new DIE(DV.getTag());
1845   DbgVariable *AbsVar = DV.getAbstractVariable();
1846   DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1847   if (AbsDIE)
1848     addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1849   else {
1850     if (!Name.empty())
1851       addString(VariableDie, dwarf::DW_AT_name, Name);
1852     addSourceLine(VariableDie, DV.getVariable());
1853     addType(VariableDie, DV.getType());
1854   }
1856   if (DV.isArtificial())
1857     addFlag(VariableDie, dwarf::DW_AT_artificial);
1859   if (isScopeAbstract) {
1860     DV.setDIE(VariableDie);
1861     return VariableDie;
1862   }
1864   // Add variable address.
1866   unsigned Offset = DV.getDotDebugLocOffset();
1867   if (Offset != ~0U) {
1868     addLocationList(VariableDie, dwarf::DW_AT_location, Offset);
1869     DV.setDIE(VariableDie);
1870     return VariableDie;
1871   }
1873   // Check if variable is described by a DBG_VALUE instruction.
1874   if (const MachineInstr *DVInsn = DV.getMInsn()) {
1875     assert(DVInsn->getNumOperands() == 3);
1876     if (DVInsn->getOperand(0).isReg()) {
1877       const MachineOperand RegOp = DVInsn->getOperand(0);
1878       // If the second operand is an immediate, this is an indirect value.
1879       if (DVInsn->getOperand(1).isImm()) {
1880         MachineLocation Location(RegOp.getReg(),
1881                                  DVInsn->getOperand(1).getImm());
1882         addVariableAddress(DV, VariableDie, Location);
1883       } else if (RegOp.getReg())
1884         addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1885     } else if (DVInsn->getOperand(0).isImm())
1886       addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1887     else if (DVInsn->getOperand(0).isFPImm())
1888       addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1889     else if (DVInsn->getOperand(0).isCImm())
1890       addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1891                        isUnsignedDIType(DD, DV.getType()));
1893     DV.setDIE(VariableDie);
1894     return VariableDie;
1895   } else {
1896     // .. else use frame index.
1897     int FI = DV.getFrameIndex();
1898     if (FI != ~0) {
1899       unsigned FrameReg = 0;
1900       const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1901       int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1902       MachineLocation Location(FrameReg, Offset);
1903       addVariableAddress(DV, VariableDie, Location);
1904     }
1905   }
1907   DV.setDIE(VariableDie);
1908   return VariableDie;
1911 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1912 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1913   DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1914   StringRef Name = DT.getName();
1915   if (!Name.empty())
1916     addString(MemberDie, dwarf::DW_AT_name, Name);
1918   addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1920   addSourceLine(MemberDie, DT);
1922   if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1924     // For C++, virtual base classes are not at fixed offset. Use following
1925     // expression to extract appropriate offset from vtable.
1926     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1928     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1929     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1930     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1931     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1932     addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1933     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1934     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1935     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1937     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1938   } else {
1939     uint64_t Size = DT.getSizeInBits();
1940     uint64_t FieldSize = getBaseTypeSize(DD, DT);
1941     uint64_t OffsetInBytes;
1943     if (Size != FieldSize) {
1944       // Handle bitfield, assume bytes are 8 bits.
1945       addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1946       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1948       uint64_t Offset = DT.getOffsetInBits();
1949       uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1950       uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1951       uint64_t FieldOffset = (HiMark - FieldSize);
1952       Offset -= FieldOffset;
1954       // Maybe we need to work from the other end.
1955       if (Asm->getDataLayout().isLittleEndian())
1956         Offset = FieldSize - (Offset + Size);
1957       addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1959       // Here DW_AT_data_member_location points to the anonymous
1960       // field that includes this bit field.
1961       OffsetInBytes = FieldOffset >> 3;
1962     } else
1963       // This is not a bitfield.
1964       OffsetInBytes = DT.getOffsetInBits() >> 3;
1966     if (DD->getDwarfVersion() <= 2) {
1967       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1968       addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1969       addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1970       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1971     } else
1972       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1973               OffsetInBytes);
1974   }
1976   if (DT.isProtected())
1977     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1978             dwarf::DW_ACCESS_protected);
1979   else if (DT.isPrivate())
1980     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1981             dwarf::DW_ACCESS_private);
1982   // Otherwise C++ member and base classes are considered public.
1983   else
1984     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1985             dwarf::DW_ACCESS_public);
1986   if (DT.isVirtual())
1987     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1988             dwarf::DW_VIRTUALITY_virtual);
1990   // Objective-C properties.
1991   if (MDNode *PNode = DT.getObjCProperty())
1992     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1993       MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1994                           PropertyDie);
1996   if (DT.isArtificial())
1997     addFlag(MemberDie, dwarf::DW_AT_artificial);
2000 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
2001 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
2002   if (!DT.Verify())
2003     return NULL;
2005   // Construct the context before querying for the existence of the DIE in case
2006   // such construction creates the DIE.
2007   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
2008   assert(dwarf::isType(ContextDIE->getTag()) &&
2009          "Static member should belong to a type.");
2011   DIE *StaticMemberDIE = getDIE(DT);
2012   if (StaticMemberDIE)
2013     return StaticMemberDIE;
2015   StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
2017   DIType Ty = resolve(DT.getTypeDerivedFrom());
2019   addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
2020   addType(StaticMemberDIE, Ty);
2021   addSourceLine(StaticMemberDIE, DT);
2022   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2023   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2025   // FIXME: We could omit private if the parent is a class_type, and
2026   // public if the parent is something else.
2027   if (DT.isProtected())
2028     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2029             dwarf::DW_ACCESS_protected);
2030   else if (DT.isPrivate())
2031     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2032             dwarf::DW_ACCESS_private);
2033   else
2034     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2035             dwarf::DW_ACCESS_public);
2037   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2038     addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
2039   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2040     addConstantFPValue(StaticMemberDIE, CFP);
2042   return StaticMemberDIE;
2045 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2046   Asm->OutStreamer.AddComment("DWARF version number");
2047   Asm->EmitInt16(DD->getDwarfVersion());
2048   Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2049   // We share one abbreviations table across all units so it's always at the
2050   // start of the section. Use a relocatable offset where needed to ensure
2051   // linking doesn't invalidate that offset.
2052   if (ASectionSym)
2053     Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2054   else
2055     // Use a constant value when no symbol is provided.
2056     Asm->EmitInt32(0);
2057   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2058   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2061 void DwarfUnit::addRange(RangeSpan Range) {
2062   // Only add a range for this unit if we're emitting full debug.
2063   if (getCUNode().getEmissionKind() == DIBuilder::FullDebug) {
2064     // If we have no current ranges just add the range and return, otherwise,
2065     // check the current section and CU against the previous section and CU we
2066     // emitted into and the subprogram was contained within. If these are the
2067     // same then extend our current range, otherwise add this as a new range.
2068     if (CURanges.size() == 0 ||
2069         this != DD->getPrevCU() ||
2070         Asm->getCurrentSection() != DD->getPrevSection()) {
2071       CURanges.push_back(Range);
2072       return;
2073     }
2075     assert(&(CURanges.back().getEnd()->getSection()) ==
2076                &(Range.getEnd()->getSection()) &&
2077            "We can only append to a range in the same section!");
2078     CURanges.back().setEnd(Range.getEnd());
2079   }
2082 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2083   // Define start line table label for each Compile Unit.
2084   MCSymbol *LineTableStartSym =
2085       Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2087   stmtListIndex = UnitDie->getValues().size();
2089   // DW_AT_stmt_list is a offset of line number information for this
2090   // compile unit in debug_line section. For split dwarf this is
2091   // left in the skeleton CU and so not included.
2092   // The line table entries are not always emitted in assembly, so it
2093   // is not okay to use line_table_start here.
2094   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2095     addSectionLabel(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym);
2096   else
2097     addSectionDelta(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym,
2098                     DwarfLineSectionSym);
2101 void DwarfCompileUnit::applyStmtList(DIE &D) {
2102   D.addValue(dwarf::DW_AT_stmt_list,
2103              UnitDie->getAbbrev().getData()[stmtListIndex].getForm(),
2104              UnitDie->getValues()[stmtListIndex]);
2107 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2108   DwarfUnit::emitHeader(ASectionSym);
2109   Asm->OutStreamer.AddComment("Type Signature");
2110   Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2111   Asm->OutStreamer.AddComment("Type DIE Offset");
2112   // In a skeleton type unit there is no type DIE so emit a zero offset.
2113   Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2114                                 sizeof(Ty->getOffset()));
2117 void DwarfTypeUnit::initSection(const MCSection *Section) {
2118   assert(!this->Section);
2119   this->Section = Section;
2120   // Since each type unit is contained in its own COMDAT section, the begin
2121   // label and the section label are the same. Using the begin label emission in
2122   // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2123   // the only other alternative of lazily constructing start-of-section labels
2124   // and storing a mapping in DwarfDebug (or AsmPrinter).
2125   this->SectionSym = this->LabelBegin =
2126       Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2127   this->LabelEnd =
2128       Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2129   this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());