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