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