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