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