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