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