Debug Info: use createAndAddDIE for newly-created Subprogram DIEs.
[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 /// addToContextOwner - Add Die into the list of its context owner's children.
830 void CompileUnit::addToContextOwner(DIE *Die, DIScope Context) {
831   assert(!Die->getParent());
832   if (DIE *ContextDIE = getOrCreateContextDIE(Context)) {
833     if (Die->getParent()) {
834       // While creating the context, if this is a type member, we will have
835       // added the child to the context already.
836       assert(Die->getParent() == ContextDIE);
837       return;
838     }
839     ContextDIE->addChild(Die);
840   } else
841     addDie(Die);
842 }
843
844 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
845 /// given DIType.
846 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
847   DIType Ty(TyNode);
848   if (!Ty.isType())
849     return NULL;
850   DIE *TyDIE = getDIE(Ty);
851   if (TyDIE)
852     return TyDIE;
853
854   // Create new type.
855   TyDIE = new DIE(Ty.getTag());
856   insertDIE(Ty, TyDIE);
857   if (Ty.isBasicType())
858     constructTypeDIE(*TyDIE, DIBasicType(Ty));
859   else if (Ty.isCompositeType())
860     constructTypeDIE(*TyDIE, DICompositeType(Ty));
861   else {
862     assert(Ty.isDerivedType() && "Unknown kind of DIType");
863     constructTypeDIE(*TyDIE, DIDerivedType(Ty));
864   }
865   // If this is a named finished type then include it in the list of types
866   // for the accelerator tables.
867   if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
868     bool IsImplementation = 0;
869     if (Ty.isCompositeType()) {
870       DICompositeType CT(Ty);
871       // A runtime language of 0 actually means C/C++ and that any
872       // non-negative value is some version of Objective-C/C++.
873       IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
874     }
875     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
876     addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
877   }
878
879   addToContextOwner(TyDIE, resolve(Ty.getContext()));
880   return TyDIE;
881 }
882
883 /// addType - Add a new type attribute to the specified entity.
884 void CompileUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
885   assert(Ty && "Trying to add a type that doesn't exist?");
886
887   // Check for pre-existence.
888   DIEEntry *Entry = getDIEEntry(Ty);
889   // If it exists then use the existing value.
890   if (Entry) {
891     Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
892     return;
893   }
894
895   // Construct type.
896   DIE *Buffer = getOrCreateTypeDIE(Ty);
897
898   // Set up proxy.
899   Entry = createDIEEntry(Buffer);
900   insertDIEEntry(Ty, Entry);
901   Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
902
903   // If this is a complete composite type then include it in the
904   // list of global types.
905   addGlobalType(Ty);
906 }
907
908 // Accelerator table mutators - add each name along with its companion
909 // DIE to the proper table while ensuring that the name that we're going
910 // to reference is in the string table. We do this since the names we
911 // add may not only be identical to the names in the DIE.
912 void CompileUnit::addAccelName(StringRef Name, DIE *Die) {
913   DU->getStringPoolEntry(Name);
914   std::vector<DIE *> &DIEs = AccelNames[Name];
915   DIEs.push_back(Die);
916 }
917
918 void CompileUnit::addAccelObjC(StringRef Name, DIE *Die) {
919   DU->getStringPoolEntry(Name);
920   std::vector<DIE *> &DIEs = AccelObjC[Name];
921   DIEs.push_back(Die);
922 }
923
924 void CompileUnit::addAccelNamespace(StringRef Name, DIE *Die) {
925   DU->getStringPoolEntry(Name);
926   std::vector<DIE *> &DIEs = AccelNamespace[Name];
927   DIEs.push_back(Die);
928 }
929
930 void CompileUnit::addAccelType(StringRef Name, std::pair<DIE *, unsigned> Die) {
931   DU->getStringPoolEntry(Name);
932   std::vector<std::pair<DIE *, unsigned> > &DIEs = AccelTypes[Name];
933   DIEs.push_back(Die);
934 }
935
936 /// addGlobalName - Add a new global name to the compile unit.
937 void CompileUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
938   std::string FullName = getParentContextString(Context) + Name.str();
939   GlobalNames[FullName] = Die;
940 }
941
942 /// addGlobalType - Add a new global type to the compile unit.
943 ///
944 void CompileUnit::addGlobalType(DIType Ty) {
945   DIScope Context = resolve(Ty.getContext());
946   if (!Ty.getName().empty() && !Ty.isForwardDecl() &&
947       (!Context || Context.isCompileUnit() || Context.isFile() ||
948        Context.isNameSpace()))
949     if (DIEEntry *Entry = getDIEEntry(Ty)) {
950       std::string FullName =
951           getParentContextString(Context) + Ty.getName().str();
952       GlobalTypes[FullName] = Entry->getEntry();
953     }
954 }
955
956 /// getParentContextString - Walks the metadata parent chain in a language
957 /// specific manner (using the compile unit language) and returns
958 /// it as a string. This is done at the metadata level because DIEs may
959 /// not currently have been added to the parent context and walking the
960 /// DIEs looking for names is more expensive than walking the metadata.
961 std::string CompileUnit::getParentContextString(DIScope Context) const {
962   if (!Context)
963     return "";
964
965   // FIXME: Decide whether to implement this for non-C++ languages.
966   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
967     return "";
968
969   std::string CS;
970   SmallVector<DIScope, 1> Parents;
971   while (!Context.isCompileUnit()) {
972     Parents.push_back(Context);
973     if (Context.getContext())
974       Context = resolve(Context.getContext());
975     else
976       // Structure, etc types will have a NULL context if they're at the top
977       // level.
978       break;
979   }
980
981   // Reverse iterate over our list to go from the outermost construct to the
982   // innermost.
983   for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
984                                                   E = Parents.rend();
985        I != E; ++I) {
986     DIScope Ctx = *I;
987     StringRef Name = Ctx.getName();
988     if (!Name.empty()) {
989       CS += Name;
990       CS += "::";
991     }
992   }
993   return CS;
994 }
995
996 /// addPubTypes - Add subprogram argument types for pubtypes section.
997 void CompileUnit::addPubTypes(DISubprogram SP) {
998   DICompositeType SPTy = SP.getType();
999   uint16_t SPTag = SPTy.getTag();
1000   if (SPTag != dwarf::DW_TAG_subroutine_type)
1001     return;
1002
1003   DIArray Args = SPTy.getTypeArray();
1004   for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1005     DIType ATy(Args.getElement(i));
1006     if (!ATy.isType())
1007       continue;
1008     addGlobalType(ATy);
1009   }
1010 }
1011
1012 /// constructTypeDIE - Construct basic type die from DIBasicType.
1013 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1014   // Get core information.
1015   StringRef Name = BTy.getName();
1016   // Add name if not anonymous or intermediate type.
1017   if (!Name.empty())
1018     addString(&Buffer, dwarf::DW_AT_name, Name);
1019
1020   // An unspecified type only has a name attribute.
1021   if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1022     return;
1023
1024   addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1025           BTy.getEncoding());
1026
1027   uint64_t Size = BTy.getSizeInBits() >> 3;
1028   addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1029 }
1030
1031 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1032 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1033   // Get core information.
1034   StringRef Name = DTy.getName();
1035   uint64_t Size = DTy.getSizeInBits() >> 3;
1036   uint16_t Tag = Buffer.getTag();
1037
1038   // Map to main type, void will not have a type.
1039   DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1040   if (FromTy)
1041     addType(&Buffer, FromTy);
1042
1043   // Add name if not anonymous or intermediate type.
1044   if (!Name.empty())
1045     addString(&Buffer, dwarf::DW_AT_name, Name);
1046
1047   // Add size if non-zero (derived types might be zero-sized.)
1048   if (Size && Tag != dwarf::DW_TAG_pointer_type)
1049     addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1050
1051   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1052     addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1053                 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1054   // Add source line info if available and TyDesc is not a forward declaration.
1055   if (!DTy.isForwardDecl())
1056     addSourceLine(&Buffer, DTy);
1057 }
1058
1059 /// Return true if the type is appropriately scoped to be contained inside
1060 /// its own type unit.
1061 static bool isTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
1062   DIScope Parent = DD->resolve(Ty.getContext());
1063   while (Parent) {
1064     // Don't generate a hash for anything scoped inside a function.
1065     if (Parent.isSubprogram())
1066       return false;
1067     Parent = DD->resolve(Parent.getContext());
1068   }
1069   return true;
1070 }
1071
1072 /// Return true if the type should be split out into a type unit.
1073 static bool shouldCreateTypeUnit(DICompositeType CTy, const DwarfDebug *DD) {
1074   uint16_t Tag = CTy.getTag();
1075
1076   switch (Tag) {
1077   case dwarf::DW_TAG_structure_type:
1078   case dwarf::DW_TAG_union_type:
1079   case dwarf::DW_TAG_enumeration_type:
1080   case dwarf::DW_TAG_class_type:
1081     // If this is a class, structure, union, or enumeration type
1082     // that is a definition (not a declaration), and not scoped
1083     // inside a function then separate this out as a type unit.
1084     return !CTy.isForwardDecl() && isTypeUnitScoped(CTy, DD);
1085   default:
1086     return false;
1087   }
1088 }
1089
1090 /// constructTypeDIE - Construct type DIE from DICompositeType.
1091 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1092   // Get core information.
1093   StringRef Name = CTy.getName();
1094
1095   uint64_t Size = CTy.getSizeInBits() >> 3;
1096   uint16_t Tag = Buffer.getTag();
1097
1098   switch (Tag) {
1099   case dwarf::DW_TAG_array_type:
1100     constructArrayTypeDIE(Buffer, &CTy);
1101     break;
1102   case dwarf::DW_TAG_enumeration_type: {
1103     DIArray Elements = CTy.getTypeArray();
1104
1105     // Add enumerators to enumeration type.
1106     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1107       DIDescriptor Enum(Elements.getElement(i));
1108       if (Enum.isEnumerator())
1109         constructEnumTypeDIE(Buffer, DIEnumerator(Enum));
1110     }
1111     DIType DTy = resolve(CTy.getTypeDerivedFrom());
1112     if (DTy) {
1113       addType(&Buffer, DTy);
1114       addFlag(&Buffer, dwarf::DW_AT_enum_class);
1115     }
1116   } break;
1117   case dwarf::DW_TAG_subroutine_type: {
1118     // Add return type. A void return won't have a type.
1119     DIArray Elements = CTy.getTypeArray();
1120     DIDescriptor RTy = Elements.getElement(0);
1121     if (RTy)
1122       addType(&Buffer, DIType(RTy));
1123
1124     bool isPrototyped = true;
1125     // Add arguments.
1126     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1127       DIDescriptor Ty = Elements.getElement(i);
1128       if (Ty.isUnspecifiedParameter()) {
1129         createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1130         isPrototyped = false;
1131       } else {
1132         DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1133         addType(Arg, DIType(Ty));
1134         if (DIType(Ty).isArtificial())
1135           addFlag(Arg, dwarf::DW_AT_artificial);
1136       }
1137     }
1138     // Add prototype flag if we're dealing with a C language and the
1139     // function has been prototyped.
1140     uint16_t Language = DICompileUnit(Node).getLanguage();
1141     if (isPrototyped &&
1142         (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1143          Language == dwarf::DW_LANG_ObjC))
1144       addFlag(&Buffer, dwarf::DW_AT_prototyped);
1145   } break;
1146   case dwarf::DW_TAG_structure_type:
1147   case dwarf::DW_TAG_union_type:
1148   case dwarf::DW_TAG_class_type: {
1149     // Add elements to structure type.
1150     DIArray Elements = CTy.getTypeArray();
1151     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1152       DIDescriptor Element = Elements.getElement(i);
1153       DIE *ElemDie = NULL;
1154       if (Element.isSubprogram()) {
1155         DISubprogram SP(Element);
1156         ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1157         if (SP.isProtected())
1158           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1159                   dwarf::DW_ACCESS_protected);
1160         else if (SP.isPrivate())
1161           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1162                   dwarf::DW_ACCESS_private);
1163         else
1164           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1165                   dwarf::DW_ACCESS_public);
1166         if (SP.isExplicit())
1167           addFlag(ElemDie, dwarf::DW_AT_explicit);
1168       } else if (Element.isDerivedType()) {
1169         DIDerivedType DDTy(Element);
1170         if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1171           ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1172           addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1173                   dwarf::DW_AT_friend);
1174         } else if (DDTy.isStaticMember()) {
1175           getOrCreateStaticMemberDIE(DDTy);
1176         } else {
1177           constructMemberDIE(Buffer, DDTy);
1178         }
1179       } else if (Element.isObjCProperty()) {
1180         DIObjCProperty Property(Element);
1181         ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1182         StringRef PropertyName = Property.getObjCPropertyName();
1183         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1184         addType(ElemDie, Property.getType());
1185         addSourceLine(ElemDie, Property);
1186         StringRef GetterName = Property.getObjCPropertyGetterName();
1187         if (!GetterName.empty())
1188           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1189         StringRef SetterName = Property.getObjCPropertySetterName();
1190         if (!SetterName.empty())
1191           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1192         unsigned PropertyAttributes = 0;
1193         if (Property.isReadOnlyObjCProperty())
1194           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1195         if (Property.isReadWriteObjCProperty())
1196           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1197         if (Property.isAssignObjCProperty())
1198           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1199         if (Property.isRetainObjCProperty())
1200           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1201         if (Property.isCopyObjCProperty())
1202           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1203         if (Property.isNonAtomicObjCProperty())
1204           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1205         if (PropertyAttributes)
1206           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1207                   PropertyAttributes);
1208
1209         DIEEntry *Entry = getDIEEntry(Element);
1210         if (!Entry) {
1211           Entry = createDIEEntry(ElemDie);
1212           insertDIEEntry(Element, Entry);
1213         }
1214       } else
1215         continue;
1216     }
1217
1218     if (CTy.isAppleBlockExtension())
1219       addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1220
1221     DICompositeType ContainingType(resolve(CTy.getContainingType()));
1222     if (DIDescriptor(ContainingType).isCompositeType())
1223       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1224                   getOrCreateTypeDIE(DIType(ContainingType)));
1225
1226     if (CTy.isObjcClassComplete())
1227       addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1228
1229     // Add template parameters to a class, structure or union types.
1230     // FIXME: The support isn't in the metadata for this yet.
1231     if (Tag == dwarf::DW_TAG_class_type ||
1232         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1233       addTemplateParams(Buffer, CTy.getTemplateParams());
1234
1235     break;
1236   }
1237   default:
1238     break;
1239   }
1240
1241   // Add name if not anonymous or intermediate type.
1242   if (!Name.empty())
1243     addString(&Buffer, dwarf::DW_AT_name, Name);
1244
1245   if (Tag == dwarf::DW_TAG_enumeration_type ||
1246       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1247       Tag == dwarf::DW_TAG_union_type) {
1248     // Add size if non-zero (derived types might be zero-sized.)
1249     // TODO: Do we care about size for enum forward declarations?
1250     if (Size)
1251       addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1252     else if (!CTy.isForwardDecl())
1253       // Add zero size if it is not a forward declaration.
1254       addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1255
1256     // If we're a forward decl, say so.
1257     if (CTy.isForwardDecl())
1258       addFlag(&Buffer, dwarf::DW_AT_declaration);
1259
1260     // Add source line info if available.
1261     if (!CTy.isForwardDecl())
1262       addSourceLine(&Buffer, CTy);
1263
1264     // No harm in adding the runtime language to the declaration.
1265     unsigned RLang = CTy.getRunTimeLang();
1266     if (RLang)
1267       addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1268               RLang);
1269   }
1270   // If this is a type applicable to a type unit it then add it to the
1271   // list of types we'll compute a hash for later.
1272   if (shouldCreateTypeUnit(CTy, DD))
1273     DD->addTypeUnitType(&Buffer);
1274 }
1275
1276 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1277 /// DITemplateTypeParameter.
1278 void
1279 CompileUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1280                                                DITemplateTypeParameter TP) {
1281   DIE *ParamDIE =
1282       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1283   // Add the type if it exists, it could be void and therefore no type.
1284   if (TP.getType())
1285     addType(ParamDIE, resolve(TP.getType()));
1286   if (!TP.getName().empty())
1287     addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1288 }
1289
1290 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1291 /// DITemplateValueParameter.
1292 void
1293 CompileUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1294                                                 DITemplateValueParameter VP) {
1295   DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1296
1297   // Add the type if there is one, template template and template parameter
1298   // packs will not have a type.
1299   if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1300     addType(ParamDIE, resolve(VP.getType()));
1301   if (!VP.getName().empty())
1302     addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1303   if (Value *Val = VP.getValue()) {
1304     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1305       addConstantValue(ParamDIE, CI,
1306                        isUnsignedDIType(DD, resolve(VP.getType())));
1307     else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1308       // For declaration non-type template parameters (such as global values and
1309       // functions)
1310       DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1311       addOpAddress(Block, Asm->Mang->getSymbol(GV));
1312       // Emit DW_OP_stack_value to use the address as the immediate value of the
1313       // parameter, rather than a pointer to it.
1314       addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1315       addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1316     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1317       assert(isa<MDString>(Val));
1318       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1319                 cast<MDString>(Val)->getString());
1320     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1321       assert(isa<MDNode>(Val));
1322       DIArray A(cast<MDNode>(Val));
1323       addTemplateParams(*ParamDIE, A);
1324     }
1325   }
1326 }
1327
1328 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1329 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
1330   DIE *NDie = getDIE(NS);
1331   if (NDie)
1332     return NDie;
1333   NDie = new DIE(dwarf::DW_TAG_namespace);
1334   insertDIE(NS, NDie);
1335   if (!NS.getName().empty()) {
1336     addString(NDie, dwarf::DW_AT_name, NS.getName());
1337     addAccelNamespace(NS.getName(), NDie);
1338     addGlobalName(NS.getName(), NDie, NS.getContext());
1339   } else
1340     addAccelNamespace("(anonymous namespace)", NDie);
1341   addSourceLine(NDie, NS);
1342   addToContextOwner(NDie, NS.getContext());
1343   return NDie;
1344 }
1345
1346 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1347 DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1348   // Construct the context before querying for the existence of the DIE in case
1349   // such construction creates the DIE (as is the case for member function
1350   // declarations).
1351   DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1352   if (!ContextDIE)
1353     ContextDIE = CUDie.get();
1354
1355   DIE *SPDie = getDIE(SP);
1356   if (SPDie)
1357     return SPDie;
1358
1359   DISubprogram SPDecl = SP.getFunctionDeclaration();
1360   if (SPDecl.isSubprogram())
1361     // Add subprogram definitions to the CU die directly.
1362     ContextDIE = CUDie.get();
1363
1364   // DW_TAG_inlined_subroutine may refer to this DIE.
1365   SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1366
1367   DIE *DeclDie = NULL;
1368   if (SPDecl.isSubprogram())
1369     DeclDie = getOrCreateSubprogramDIE(SPDecl);
1370
1371   // Add function template parameters.
1372   addTemplateParams(*SPDie, SP.getTemplateParams());
1373
1374   // If this DIE is going to refer declaration info using AT_specification
1375   // then there is no need to add other attributes.
1376   if (DeclDie) {
1377     // Refer function declaration directly.
1378     addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1379
1380     return SPDie;
1381   }
1382
1383   // Add the linkage name if we have one.
1384   StringRef LinkageName = SP.getLinkageName();
1385   if (!LinkageName.empty())
1386     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1387               GlobalValue::getRealLinkageName(LinkageName));
1388
1389   // Constructors and operators for anonymous aggregates do not have names.
1390   if (!SP.getName().empty())
1391     addString(SPDie, dwarf::DW_AT_name, SP.getName());
1392
1393   addSourceLine(SPDie, SP);
1394
1395   // Add the prototype if we have a prototype and we have a C like
1396   // language.
1397   uint16_t Language = DICompileUnit(Node).getLanguage();
1398   if (SP.isPrototyped() &&
1399       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1400        Language == dwarf::DW_LANG_ObjC))
1401     addFlag(SPDie, dwarf::DW_AT_prototyped);
1402
1403   DICompositeType SPTy = SP.getType();
1404   assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1405          "the type of a subprogram should be a subroutine");
1406
1407   DIArray Args = SPTy.getTypeArray();
1408   // Add a return type. If this is a type like a C/C++ void type we don't add a
1409   // return type.
1410   if (Args.getElement(0))
1411     addType(SPDie, DIType(Args.getElement(0)));
1412
1413   unsigned VK = SP.getVirtuality();
1414   if (VK) {
1415     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1416     DIEBlock *Block = getDIEBlock();
1417     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1418     addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1419     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1420     ContainingTypeMap.insert(std::make_pair(SPDie,
1421                                             resolve(SP.getContainingType())));
1422   }
1423
1424   if (!SP.isDefinition()) {
1425     addFlag(SPDie, dwarf::DW_AT_declaration);
1426
1427     // Add arguments. Do not add arguments for subprogram definition. They will
1428     // be handled while processing variables.
1429     for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1430       DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1431       DIType ATy = DIType(Args.getElement(i));
1432       addType(Arg, ATy);
1433       if (ATy.isArtificial())
1434         addFlag(Arg, dwarf::DW_AT_artificial);
1435     }
1436   }
1437
1438   if (SP.isArtificial())
1439     addFlag(SPDie, dwarf::DW_AT_artificial);
1440
1441   if (!SP.isLocalToUnit())
1442     addFlag(SPDie, dwarf::DW_AT_external);
1443
1444   if (SP.isOptimized())
1445     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1446
1447   if (unsigned isa = Asm->getISAEncoding()) {
1448     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1449   }
1450
1451   return SPDie;
1452 }
1453
1454 // Return const expression if value is a GEP to access merged global
1455 // constant. e.g.
1456 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1457 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1458   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1459   if (!CE || CE->getNumOperands() != 3 ||
1460       CE->getOpcode() != Instruction::GetElementPtr)
1461     return NULL;
1462
1463   // First operand points to a global struct.
1464   Value *Ptr = CE->getOperand(0);
1465   if (!isa<GlobalValue>(Ptr) ||
1466       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1467     return NULL;
1468
1469   // Second operand is zero.
1470   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1471   if (!CI || !CI->isZero())
1472     return NULL;
1473
1474   // Third operand is offset.
1475   if (!isa<ConstantInt>(CE->getOperand(2)))
1476     return NULL;
1477
1478   return CE;
1479 }
1480
1481 /// createGlobalVariableDIE - create global variable DIE.
1482 void CompileUnit::createGlobalVariableDIE(const MDNode *N) {
1483   // Check for pre-existence.
1484   if (getDIE(N))
1485     return;
1486
1487   DIGlobalVariable GV(N);
1488   if (!GV.isGlobalVariable())
1489     return;
1490
1491   DIScope GVContext = GV.getContext();
1492   DIType GTy = GV.getType();
1493
1494   // If this is a static data member definition, some attributes belong
1495   // to the declaration DIE.
1496   DIE *VariableDIE = NULL;
1497   bool IsStaticMember = false;
1498   DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1499   if (SDMDecl.Verify()) {
1500     assert(SDMDecl.isStaticMember() && "Expected static member decl");
1501     // We need the declaration DIE that is in the static member's class.
1502     VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1503     IsStaticMember = true;
1504   }
1505
1506   // If this is not a static data member definition, create the variable
1507   // DIE and add the initial set of attributes to it.
1508   if (!VariableDIE) {
1509     VariableDIE = new DIE(GV.getTag());
1510     // Add to map.
1511     insertDIE(N, VariableDIE);
1512
1513     // Add name and type.
1514     addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1515     addType(VariableDIE, GTy);
1516
1517     // Add scoping info.
1518     if (!GV.isLocalToUnit())
1519       addFlag(VariableDIE, dwarf::DW_AT_external);
1520
1521     // Add line number info.
1522     addSourceLine(VariableDIE, GV);
1523     // Add to context owner.
1524     addToContextOwner(VariableDIE, GVContext);
1525   }
1526
1527   // Add location.
1528   bool addToAccelTable = false;
1529   DIE *VariableSpecDIE = NULL;
1530   bool isGlobalVariable = GV.getGlobal() != NULL;
1531   if (isGlobalVariable) {
1532     addToAccelTable = true;
1533     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1534     const MCSymbol *Sym = Asm->Mang->getSymbol(GV.getGlobal());
1535     if (GV.getGlobal()->isThreadLocal()) {
1536       // FIXME: Make this work with -gsplit-dwarf.
1537       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1538       assert((PointerSize == 4 || PointerSize == 8) &&
1539              "Add support for other sizes if necessary");
1540       const MCExpr *Expr =
1541           Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1542       // Based on GCC's support for TLS:
1543       if (!DD->useSplitDwarf()) {
1544         // 1) Start with a constNu of the appropriate pointer size
1545         addUInt(Block, dwarf::DW_FORM_data1,
1546                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1547         // 2) containing the (relocated) offset of the TLS variable
1548         //    within the module's TLS block.
1549         addExpr(Block, dwarf::DW_FORM_udata, Expr);
1550       } else {
1551         addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1552         addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1553       }
1554       // 3) followed by a custom OP to make the debugger do a TLS lookup.
1555       addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1556     } else
1557       addOpAddress(Block, Sym);
1558     // Do not create specification DIE if context is either compile unit
1559     // or a subprogram.
1560     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1561         !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1562       // Create specification DIE.
1563       VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *CUDie.get());
1564       addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1565       addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1566       // A static member's declaration is already flagged as such.
1567       if (!SDMDecl.Verify())
1568         addFlag(VariableDIE, dwarf::DW_AT_declaration);
1569     } else {
1570       addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1571     }
1572     // Add the linkage name.
1573     StringRef LinkageName = GV.getLinkageName();
1574     if (!LinkageName.empty())
1575       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1576       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1577       // TAG_variable.
1578       addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1579                                                   : VariableDIE,
1580                 dwarf::DW_AT_MIPS_linkage_name,
1581                 GlobalValue::getRealLinkageName(LinkageName));
1582   } else if (const ConstantInt *CI =
1583                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1584     // AT_const_value was added when the static member was created. To avoid
1585     // emitting AT_const_value multiple times, we only add AT_const_value when
1586     // it is not a static member.
1587     if (!IsStaticMember)
1588       addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1589   } else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1590     addToAccelTable = true;
1591     // GV is a merged global.
1592     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1593     Value *Ptr = CE->getOperand(0);
1594     addOpAddress(Block, Asm->Mang->getSymbol(cast<GlobalValue>(Ptr)));
1595     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1596     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1597     addUInt(Block, dwarf::DW_FORM_udata,
1598             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1599     addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1600     addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1601   }
1602
1603   if (addToAccelTable) {
1604     DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1605     addAccelName(GV.getName(), AddrDIE);
1606
1607     // If the linkage name is different than the name, go ahead and output
1608     // that as well into the name table.
1609     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1610       addAccelName(GV.getLinkageName(), AddrDIE);
1611   }
1612
1613   if (!GV.isLocalToUnit())
1614     addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1615                   GV.getContext());
1616 }
1617
1618 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1619 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1620                                        DIE *IndexTy) {
1621   DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1622   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1623
1624   // The LowerBound value defines the lower bounds which is typically zero for
1625   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1626   // Count == -1 then the array is unbounded and we do not emit
1627   // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1628   // Count == 0, then the array has zero elements in which case we do not emit
1629   // an upper bound.
1630   int64_t LowerBound = SR.getLo();
1631   int64_t DefaultLowerBound = getDefaultLowerBound();
1632   int64_t Count = SR.getCount();
1633
1634   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1635     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1636
1637   if (Count != -1 && Count != 0)
1638     // FIXME: An unbounded array should reference the expression that defines
1639     // the array.
1640     addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None, LowerBound + Count - 1);
1641 }
1642
1643 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1644 void CompileUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType *CTy) {
1645   if (CTy->isVector())
1646     addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1647
1648   // Emit the element type.
1649   addType(&Buffer, resolve(CTy->getTypeDerivedFrom()));
1650
1651   // Get an anonymous type for index type.
1652   // FIXME: This type should be passed down from the front end
1653   // as different languages may have different sizes for indexes.
1654   DIE *IdxTy = getIndexTyDie();
1655   if (!IdxTy) {
1656     // Construct an anonymous type for index type.
1657     IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *CUDie.get());
1658     addString(IdxTy, dwarf::DW_AT_name, "int");
1659     addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1660     addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1661             dwarf::DW_ATE_signed);
1662     setIndexTyDie(IdxTy);
1663   }
1664
1665   // Add subranges to array type.
1666   DIArray Elements = CTy->getTypeArray();
1667   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1668     DIDescriptor Element = Elements.getElement(i);
1669     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1670       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1671   }
1672 }
1673
1674 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1675 void CompileUnit::constructEnumTypeDIE(DIE &Buffer, DIEnumerator ETy) {
1676   DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1677   StringRef Name = ETy.getName();
1678   addString(Enumerator, dwarf::DW_AT_name, Name);
1679   int64_t Value = ETy.getEnumValue();
1680   addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1681 }
1682
1683 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1684 /// vtables.
1685 void CompileUnit::constructContainingTypeDIEs() {
1686   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1687                                                  CE = ContainingTypeMap.end();
1688        CI != CE; ++CI) {
1689     DIE *SPDie = CI->first;
1690     const MDNode *N = CI->second;
1691     if (!N)
1692       continue;
1693     DIE *NDie = getDIE(N);
1694     if (!NDie)
1695       continue;
1696     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1697   }
1698 }
1699
1700 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1701 DIE *CompileUnit::constructVariableDIE(DbgVariable *DV, bool isScopeAbstract) {
1702   StringRef Name = DV->getName();
1703
1704   // Define variable debug information entry.
1705   DIE *VariableDie = new DIE(DV->getTag());
1706   DbgVariable *AbsVar = DV->getAbstractVariable();
1707   DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1708   if (AbsDIE)
1709     addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1710   else {
1711     if (!Name.empty())
1712       addString(VariableDie, dwarf::DW_AT_name, Name);
1713     addSourceLine(VariableDie, DV->getVariable());
1714     addType(VariableDie, DV->getType());
1715   }
1716
1717   if (DV->isArtificial())
1718     addFlag(VariableDie, dwarf::DW_AT_artificial);
1719
1720   if (isScopeAbstract) {
1721     DV->setDIE(VariableDie);
1722     return VariableDie;
1723   }
1724
1725   // Add variable address.
1726
1727   unsigned Offset = DV->getDotDebugLocOffset();
1728   if (Offset != ~0U) {
1729     addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1730              Asm->GetTempSymbol("debug_loc", Offset));
1731     DV->setDIE(VariableDie);
1732     return VariableDie;
1733   }
1734
1735   // Check if variable is described by a DBG_VALUE instruction.
1736   if (const MachineInstr *DVInsn = DV->getMInsn()) {
1737     assert(DVInsn->getNumOperands() == 3);
1738     if (DVInsn->getOperand(0).isReg()) {
1739       const MachineOperand RegOp = DVInsn->getOperand(0);
1740       // If the second operand is an immediate, this is an indirect value.
1741       if (DVInsn->getOperand(1).isImm()) {
1742         MachineLocation Location(RegOp.getReg(),
1743                                  DVInsn->getOperand(1).getImm());
1744         addVariableAddress(*DV, VariableDie, Location);
1745       } else if (RegOp.getReg())
1746         addVariableAddress(*DV, VariableDie, MachineLocation(RegOp.getReg()));
1747     } else if (DVInsn->getOperand(0).isImm())
1748       addConstantValue(VariableDie, DVInsn->getOperand(0), DV->getType());
1749     else if (DVInsn->getOperand(0).isFPImm())
1750       addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1751     else if (DVInsn->getOperand(0).isCImm())
1752       addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1753                        isUnsignedDIType(DD, DV->getType()));
1754
1755     DV->setDIE(VariableDie);
1756     return VariableDie;
1757   } else {
1758     // .. else use frame index.
1759     int FI = DV->getFrameIndex();
1760     if (FI != ~0) {
1761       unsigned FrameReg = 0;
1762       const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1763       int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1764       MachineLocation Location(FrameReg, Offset);
1765       addVariableAddress(*DV, VariableDie, Location);
1766     }
1767   }
1768
1769   DV->setDIE(VariableDie);
1770   return VariableDie;
1771 }
1772
1773 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1774 void CompileUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1775   DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1776   StringRef Name = DT.getName();
1777   if (!Name.empty())
1778     addString(MemberDie, dwarf::DW_AT_name, Name);
1779
1780   addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1781
1782   addSourceLine(MemberDie, DT);
1783
1784   DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1785   addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1786
1787   uint64_t Size = DT.getSizeInBits();
1788   uint64_t FieldSize = getBaseTypeSize(DD, DT);
1789
1790   if (Size != FieldSize) {
1791     // Handle bitfield.
1792     addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1793             getBaseTypeSize(DD, DT) >> 3);
1794     addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1795
1796     uint64_t Offset = DT.getOffsetInBits();
1797     uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1798     uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1799     uint64_t FieldOffset = (HiMark - FieldSize);
1800     Offset -= FieldOffset;
1801
1802     // Maybe we need to work from the other end.
1803     if (Asm->getDataLayout().isLittleEndian())
1804       Offset = FieldSize - (Offset + Size);
1805     addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1806
1807     // Here WD_AT_data_member_location points to the anonymous
1808     // field that includes this bit field.
1809     addUInt(MemLocationDie, dwarf::DW_FORM_udata, FieldOffset >> 3);
1810
1811   } else
1812     // This is not a bitfield.
1813     addUInt(MemLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1814
1815   if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1816
1817     // For C++, virtual base classes are not at fixed offset. Use following
1818     // expression to extract appropriate offset from vtable.
1819     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1820
1821     DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1822     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1823     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1824     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1825     addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1826     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1827     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1828     addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1829
1830     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1831   } else
1832     addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1833
1834   if (DT.isProtected())
1835     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1836             dwarf::DW_ACCESS_protected);
1837   else if (DT.isPrivate())
1838     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1839             dwarf::DW_ACCESS_private);
1840   // Otherwise C++ member and base classes are considered public.
1841   else
1842     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1843             dwarf::DW_ACCESS_public);
1844   if (DT.isVirtual())
1845     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1846             dwarf::DW_VIRTUALITY_virtual);
1847
1848   // Objective-C properties.
1849   if (MDNode *PNode = DT.getObjCProperty())
1850     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1851       MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1852                           PropertyDie);
1853
1854   if (DT.isArtificial())
1855     addFlag(MemberDie, dwarf::DW_AT_artificial);
1856 }
1857
1858 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1859 DIE *CompileUnit::getOrCreateStaticMemberDIE(const DIDerivedType DT) {
1860   if (!DT.Verify())
1861     return NULL;
1862
1863   // Construct the context before querying for the existence of the DIE in case
1864   // such construction creates the DIE.
1865   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1866   assert(ContextDIE && "Static member should belong to a non-CU context.");
1867
1868   DIE *StaticMemberDIE = getDIE(DT);
1869   if (StaticMemberDIE)
1870     return StaticMemberDIE;
1871
1872   StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1873
1874   DIType Ty = resolve(DT.getTypeDerivedFrom());
1875
1876   addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1877   addType(StaticMemberDIE, Ty);
1878   addSourceLine(StaticMemberDIE, DT);
1879   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1880   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1881
1882   // FIXME: We could omit private if the parent is a class_type, and
1883   // public if the parent is something else.
1884   if (DT.isProtected())
1885     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1886             dwarf::DW_ACCESS_protected);
1887   else if (DT.isPrivate())
1888     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1889             dwarf::DW_ACCESS_private);
1890   else
1891     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1892             dwarf::DW_ACCESS_public);
1893
1894   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1895     addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1896   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1897     addConstantFPValue(StaticMemberDIE, CFP);
1898
1899   return StaticMemberDIE;
1900 }