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