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