Use the 'count' attribute instead of the 'upper_bound' attribute.
[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 "DwarfAccelTable.h"
17 #include "DwarfCompileUnit.h"
18 #include "DwarfDebug.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DIBuilder.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Target/Mangler.h"
25 #include "llvm/DataLayout.h"
26 #include "llvm/Target/TargetFrameLowering.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/Support/ErrorHandling.h"
31
32 using namespace llvm;
33
34 /// CompileUnit - Compile unit constructor.
35 CompileUnit::CompileUnit(unsigned I, unsigned L, DIE *D, AsmPrinter *A,
36                          DwarfDebug *DW)
37   : ID(I), Language(L), CUDie(D), Asm(A), DD(DW), IndexTyDie(0) {
38   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
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 /// addFlag - Add a flag that is true.
55 void CompileUnit::addFlag(DIE *Die, unsigned Attribute) {
56   if (!DD->useDarwinGDBCompat())
57     Die->addValue(Attribute, dwarf::DW_FORM_flag_present,
58                   DIEIntegerOne);
59   else
60     addUInt(Die, Attribute, dwarf::DW_FORM_flag, 1);
61 }
62
63 /// addUInt - Add an unsigned integer attribute data and value.
64 ///
65 void CompileUnit::addUInt(DIE *Die, unsigned Attribute,
66                           unsigned Form, uint64_t Integer) {
67   if (!Form) Form = DIEInteger::BestForm(false, Integer);
68   DIEValue *Value = Integer == 1 ?
69     DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
70   Die->addValue(Attribute, Form, Value);
71 }
72
73 /// addSInt - Add an signed integer attribute data and value.
74 ///
75 void CompileUnit::addSInt(DIE *Die, unsigned Attribute,
76                           unsigned Form, int64_t Integer) {
77   if (!Form) Form = DIEInteger::BestForm(true, Integer);
78   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
79   Die->addValue(Attribute, Form, Value);
80 }
81
82 /// addString - Add a string attribute data and value. We always emit a
83 /// reference to the string pool instead of immediate strings so that DIEs have
84 /// more predictable sizes.
85 void CompileUnit::addString(DIE *Die, unsigned Attribute, StringRef String) {
86   MCSymbol *Symb = DD->getStringPoolEntry(String);
87   DIEValue *Value;
88   if (Asm->needsRelocationsForDwarfStringPool())
89     Value = new (DIEValueAllocator) DIELabel(Symb);
90   else {
91     MCSymbol *StringPool = DD->getStringPool();
92     Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
93   }
94   Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
95 }
96
97 /// addLabel - Add a Dwarf label attribute data and value.
98 ///
99 void CompileUnit::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
100                            const MCSymbol *Label) {
101   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
102   Die->addValue(Attribute, Form, Value);
103 }
104
105 /// addDelta - Add a label delta attribute data and value.
106 ///
107 void CompileUnit::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
108                            const MCSymbol *Hi, const MCSymbol *Lo) {
109   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
110   Die->addValue(Attribute, Form, Value);
111 }
112
113 /// addDIEEntry - Add a DIE attribute data and value.
114 ///
115 void CompileUnit::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
116                               DIE *Entry) {
117   Die->addValue(Attribute, Form, createDIEEntry(Entry));
118 }
119
120 /// addBlock - Add block data.
121 ///
122 void CompileUnit::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
123                            DIEBlock *Block) {
124   Block->ComputeSize(Asm);
125   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
126   Die->addValue(Attribute, Block->BestForm(), Block);
127 }
128
129 /// addSourceLine - Add location information to specified debug information
130 /// entry.
131 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
132   // Verify variable.
133   if (!V.Verify())
134     return;
135   
136   unsigned Line = V.getLineNumber();
137   if (Line == 0)
138     return;
139   unsigned FileID = DD->GetOrCreateSourceID(V.getContext().getFilename(),
140                                             V.getContext().getDirectory());
141   assert(FileID && "Invalid file id");
142   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
143   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
144 }
145
146 /// addSourceLine - Add location information to specified debug information
147 /// entry.
148 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
149   // Verify global variable.
150   if (!G.Verify())
151     return;
152
153   unsigned Line = G.getLineNumber();
154   if (Line == 0)
155     return;
156   unsigned FileID = DD->GetOrCreateSourceID(G.getFilename(), G.getDirectory());
157   assert(FileID && "Invalid file id");
158   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
159   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
160 }
161
162 /// addSourceLine - Add location information to specified debug information
163 /// entry.
164 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
165   // Verify subprogram.
166   if (!SP.Verify())
167     return;
168
169   // If the line number is 0, don't add it.
170   unsigned Line = SP.getLineNumber();
171   if (Line == 0)
172     return;
173
174   unsigned FileID = DD->GetOrCreateSourceID(SP.getFilename(),
175                                             SP.getDirectory());
176   assert(FileID && "Invalid file id");
177   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
178   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
179 }
180
181 /// addSourceLine - Add location information to specified debug information
182 /// entry.
183 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
184   // Verify type.
185   if (!Ty.Verify())
186     return;
187
188   unsigned Line = Ty.getLineNumber();
189   if (Line == 0)
190     return;
191   unsigned FileID = DD->GetOrCreateSourceID(Ty.getFilename(),
192                                             Ty.getDirectory());
193   assert(FileID && "Invalid file id");
194   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
195   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
196 }
197
198 /// addSourceLine - Add location information to specified debug information
199 /// entry.
200 void CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
201   // Verify type.
202   if (!Ty.Verify())
203     return;
204
205   unsigned Line = Ty.getLineNumber();
206   if (Line == 0)
207     return;
208   DIFile File = Ty.getFile();
209   unsigned FileID = DD->GetOrCreateSourceID(File.getFilename(),
210                                             File.getDirectory());
211   assert(FileID && "Invalid file id");
212   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
213   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
214 }
215
216 /// addSourceLine - Add location information to specified debug information
217 /// entry.
218 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
219   // Verify namespace.
220   if (!NS.Verify())
221     return;
222
223   unsigned Line = NS.getLineNumber();
224   if (Line == 0)
225     return;
226   StringRef FN = NS.getFilename();
227
228   unsigned FileID = DD->GetOrCreateSourceID(FN, NS.getDirectory());
229   assert(FileID && "Invalid file id");
230   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
231   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
232 }
233
234 /// addVariableAddress - Add DW_AT_location attribute for a 
235 /// DbgVariable based on provided MachineLocation.
236 void CompileUnit::addVariableAddress(DbgVariable *&DV, DIE *Die, 
237                                      MachineLocation Location) {
238   if (DV->variableHasComplexAddress())
239     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
240   else if (DV->isBlockByrefVariable())
241     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
242   else
243     addAddress(Die, dwarf::DW_AT_location, Location);
244 }
245
246 /// addRegisterOp - Add register operand.
247 void CompileUnit::addRegisterOp(DIE *TheDie, unsigned Reg) {
248   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
249   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
250   if (DWReg < 32)
251     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
252   else {
253     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
254     addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
255   }
256 }
257
258 /// addRegisterOffset - Add register offset.
259 void CompileUnit::addRegisterOffset(DIE *TheDie, unsigned Reg,
260                                     int64_t Offset) {
261   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
262   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
263   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
264   if (Reg == TRI->getFrameRegister(*Asm->MF))
265     // If variable offset is based in frame register then use fbreg.
266     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
267   else if (DWReg < 32)
268     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
269   else {
270     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
271     addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
272   }
273   addSInt(TheDie, 0, dwarf::DW_FORM_sdata, Offset);
274 }
275
276 /// addAddress - Add an address attribute to a die based on the location
277 /// provided.
278 void CompileUnit::addAddress(DIE *Die, unsigned Attribute,
279                              const MachineLocation &Location) {
280   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
281
282   if (Location.isReg())
283     addRegisterOp(Block, Location.getReg());
284   else
285     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
286
287   // Now attach the location information to the DIE.
288   addBlock(Die, Attribute, 0, Block);
289 }
290
291 /// addComplexAddress - Start with the address based on the location provided,
292 /// and generate the DWARF information necessary to find the actual variable
293 /// given the extra address information encoded in the DIVariable, starting from
294 /// the starting location.  Add the DWARF information to the die.
295 ///
296 void CompileUnit::addComplexAddress(DbgVariable *&DV, DIE *Die,
297                                     unsigned Attribute,
298                                     const MachineLocation &Location) {
299   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
300   unsigned N = DV->getNumAddrElements();
301   unsigned i = 0;
302   if (Location.isReg()) {
303     if (N >= 2 && DV->getAddrElement(0) == DIBuilder::OpPlus) {
304       // If first address element is OpPlus then emit
305       // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
306       addRegisterOffset(Block, Location.getReg(), DV->getAddrElement(1));
307       i = 2;
308     } else
309       addRegisterOp(Block, Location.getReg());
310   }
311   else
312     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
313
314   for (;i < N; ++i) {
315     uint64_t Element = DV->getAddrElement(i);
316     if (Element == DIBuilder::OpPlus) {
317       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
318       addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
319     } else if (Element == DIBuilder::OpDeref) {
320       if (!Location.isReg())
321         addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
322     } else llvm_unreachable("unknown DIBuilder Opcode");
323   }
324
325   // Now attach the location information to the DIE.
326   addBlock(Die, Attribute, 0, Block);
327 }
328
329 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
330    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
331    gives the variable VarName either the struct, or a pointer to the struct, as
332    its type.  This is necessary for various behind-the-scenes things the
333    compiler needs to do with by-reference variables in Blocks.
334
335    However, as far as the original *programmer* is concerned, the variable
336    should still have type 'SomeType', as originally declared.
337
338    The function getBlockByrefType dives into the __Block_byref_x_VarName
339    struct to find the original type of the variable, which is then assigned to
340    the variable's Debug Information Entry as its real type.  So far, so good.
341    However now the debugger will expect the variable VarName to have the type
342    SomeType.  So we need the location attribute for the variable to be an
343    expression that explains to the debugger how to navigate through the
344    pointers and struct to find the actual variable of type SomeType.
345
346    The following function does just that.  We start by getting
347    the "normal" location for the variable. This will be the location
348    of either the struct __Block_byref_x_VarName or the pointer to the
349    struct __Block_byref_x_VarName.
350
351    The struct will look something like:
352
353    struct __Block_byref_x_VarName {
354      ... <various fields>
355      struct __Block_byref_x_VarName *forwarding;
356      ... <various other fields>
357      SomeType VarName;
358      ... <maybe more fields>
359    };
360
361    If we are given the struct directly (as our starting point) we
362    need to tell the debugger to:
363
364    1).  Add the offset of the forwarding field.
365
366    2).  Follow that pointer to get the real __Block_byref_x_VarName
367    struct to use (the real one may have been copied onto the heap).
368
369    3).  Add the offset for the field VarName, to find the actual variable.
370
371    If we started with a pointer to the struct, then we need to
372    dereference that pointer first, before the other steps.
373    Translating this into DWARF ops, we will need to append the following
374    to the current location description for the variable:
375
376    DW_OP_deref                    -- optional, if we start with a pointer
377    DW_OP_plus_uconst <forward_fld_offset>
378    DW_OP_deref
379    DW_OP_plus_uconst <varName_fld_offset>
380
381    That is what this function does.  */
382
383 /// addBlockByrefAddress - Start with the address based on the location
384 /// provided, and generate the DWARF information necessary to find the
385 /// actual Block variable (navigating the Block struct) based on the
386 /// starting location.  Add the DWARF information to the die.  For
387 /// more information, read large comment just above here.
388 ///
389 void CompileUnit::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
390                                        unsigned Attribute,
391                                        const MachineLocation &Location) {
392   DIType Ty = DV->getType();
393   DIType TmpTy = Ty;
394   unsigned Tag = Ty.getTag();
395   bool isPointer = false;
396
397   StringRef varName = DV->getName();
398
399   if (Tag == dwarf::DW_TAG_pointer_type) {
400     DIDerivedType DTy = DIDerivedType(Ty);
401     TmpTy = DTy.getTypeDerivedFrom();
402     isPointer = true;
403   }
404
405   DICompositeType blockStruct = DICompositeType(TmpTy);
406
407   // Find the __forwarding field and the variable field in the __Block_byref
408   // struct.
409   DIArray Fields = blockStruct.getTypeArray();
410   DIDescriptor varField = DIDescriptor();
411   DIDescriptor forwardingField = DIDescriptor();
412
413   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
414     DIDescriptor Element = Fields.getElement(i);
415     DIDerivedType DT = DIDerivedType(Element);
416     StringRef fieldName = DT.getName();
417     if (fieldName == "__forwarding")
418       forwardingField = Element;
419     else if (fieldName == varName)
420       varField = Element;
421   }
422
423   // Get the offsets for the forwarding field and the variable field.
424   unsigned forwardingFieldOffset =
425     DIDerivedType(forwardingField).getOffsetInBits() >> 3;
426   unsigned varFieldOffset =
427     DIDerivedType(varField).getOffsetInBits() >> 3;
428
429   // Decode the original location, and use that as the start of the byref
430   // variable's location.
431   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
432
433   if (Location.isReg())
434     addRegisterOp(Block, Location.getReg());
435   else
436     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
437
438   // If we started with a pointer to the __Block_byref... struct, then
439   // the first thing we need to do is dereference the pointer (DW_OP_deref).
440   if (isPointer)
441     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
442
443   // Next add the offset for the '__forwarding' field:
444   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
445   // adding the offset if it's 0.
446   if (forwardingFieldOffset > 0) {
447     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
448     addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
449   }
450
451   // Now dereference the __forwarding field to get to the real __Block_byref
452   // struct:  DW_OP_deref.
453   addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
454
455   // Now that we've got the real __Block_byref... struct, add the offset
456   // for the variable's field to get to the location of the actual variable:
457   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
458   if (varFieldOffset > 0) {
459     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
460     addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
461   }
462
463   // Now attach the location information to the DIE.
464   addBlock(Die, Attribute, 0, Block);
465 }
466
467 /// isTypeSigned - Return true if the type is signed.
468 static bool isTypeSigned(DIType Ty, int *SizeInBits) {
469   if (Ty.isDerivedType())
470     return isTypeSigned(DIDerivedType(Ty).getTypeDerivedFrom(), SizeInBits);
471   if (Ty.isBasicType())
472     if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed
473         || DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
474       *SizeInBits = Ty.getSizeInBits();
475       return true;
476     }
477   return false;
478 }
479
480 /// addConstantValue - Add constant value entry in variable DIE.
481 bool CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
482                                    DIType Ty) {
483   assert(MO.isImm() && "Invalid machine operand!");
484   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
485   int SizeInBits = -1;
486   bool SignedConstant = isTypeSigned(Ty, &SizeInBits);
487   unsigned Form = SignedConstant ? dwarf::DW_FORM_sdata : dwarf::DW_FORM_udata;
488   switch (SizeInBits) {
489     case 8:  Form = dwarf::DW_FORM_data1; break;
490     case 16: Form = dwarf::DW_FORM_data2; break;
491     case 32: Form = dwarf::DW_FORM_data4; break;
492     case 64: Form = dwarf::DW_FORM_data8; break;
493     default: break;
494   }
495   SignedConstant ? addSInt(Block, 0, Form, MO.getImm()) 
496     : addUInt(Block, 0, Form, MO.getImm());
497
498   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
499   return true;
500 }
501
502 /// addConstantFPValue - Add constant value entry in variable DIE.
503 bool CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
504   assert (MO.isFPImm() && "Invalid machine operand!");
505   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
506   APFloat FPImm = MO.getFPImm()->getValueAPF();
507
508   // Get the raw data form of the floating point.
509   const APInt FltVal = FPImm.bitcastToAPInt();
510   const char *FltPtr = (const char*)FltVal.getRawData();
511
512   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
513   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
514   int Incr = (LittleEndian ? 1 : -1);
515   int Start = (LittleEndian ? 0 : NumBytes - 1);
516   int Stop = (LittleEndian ? NumBytes : -1);
517
518   // Output the constant to DWARF one byte at a time.
519   for (; Start != Stop; Start += Incr)
520     addUInt(Block, 0, dwarf::DW_FORM_data1,
521             (unsigned char)0xFF & FltPtr[Start]);
522
523   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
524   return true;
525 }
526
527 /// addConstantValue - Add constant value entry in variable DIE.
528 bool CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
529                                    bool Unsigned) {
530   unsigned CIBitWidth = CI->getBitWidth();
531   if (CIBitWidth <= 64) {
532     unsigned form = 0;
533     switch (CIBitWidth) {
534     case 8: form = dwarf::DW_FORM_data1; break;
535     case 16: form = dwarf::DW_FORM_data2; break;
536     case 32: form = dwarf::DW_FORM_data4; break;
537     case 64: form = dwarf::DW_FORM_data8; break;
538     default: 
539       form = Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata;
540     }
541     if (Unsigned)
542       addUInt(Die, dwarf::DW_AT_const_value, form, CI->getZExtValue());
543     else
544       addSInt(Die, dwarf::DW_AT_const_value, form, CI->getSExtValue());
545     return true;
546   }
547
548   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
549
550   // Get the raw data form of the large APInt.
551   const APInt Val = CI->getValue();
552   const uint64_t *Ptr64 = Val.getRawData();
553
554   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
555   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
556
557   // Output the constant to DWARF one byte at a time.
558   for (int i = 0; i < NumBytes; i++) {
559     uint8_t c;
560     if (LittleEndian)
561       c = Ptr64[i / 8] >> (8 * (i & 7));
562     else
563       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
564     addUInt(Block, 0, dwarf::DW_FORM_data1, c);
565   }
566
567   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
568   return true;
569 }
570
571 /// addTemplateParams - Add template parameters in buffer.
572 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
573   // Add template parameters.
574   for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
575     DIDescriptor Element = TParams.getElement(i);
576     if (Element.isTemplateTypeParameter())
577       Buffer.addChild(getOrCreateTemplateTypeParameterDIE(
578                         DITemplateTypeParameter(Element)));
579     else if (Element.isTemplateValueParameter())
580       Buffer.addChild(getOrCreateTemplateValueParameterDIE(
581                         DITemplateValueParameter(Element)));
582   }
583 }
584
585 /// addToContextOwner - Add Die into the list of its context owner's children.
586 void CompileUnit::addToContextOwner(DIE *Die, DIDescriptor Context) {
587   if (Context.isType()) {
588     DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
589     ContextDIE->addChild(Die);
590   } else if (Context.isNameSpace()) {
591     DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
592     ContextDIE->addChild(Die);
593   } else if (Context.isSubprogram()) {
594     DIE *ContextDIE = getOrCreateSubprogramDIE(DISubprogram(Context));
595     ContextDIE->addChild(Die);
596   } else if (DIE *ContextDIE = getDIE(Context))
597     ContextDIE->addChild(Die);
598   else
599     addDie(Die);
600 }
601
602 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
603 /// given DIType.
604 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
605   DIType Ty(TyNode);
606   if (!Ty.Verify())
607     return NULL;
608   DIE *TyDIE = getDIE(Ty);
609   if (TyDIE)
610     return TyDIE;
611
612   // Create new type.
613   TyDIE = new DIE(dwarf::DW_TAG_base_type);
614   insertDIE(Ty, TyDIE);
615   if (Ty.isBasicType())
616     constructTypeDIE(*TyDIE, DIBasicType(Ty));
617   else if (Ty.isCompositeType())
618     constructTypeDIE(*TyDIE, DICompositeType(Ty));
619   else {
620     assert(Ty.isDerivedType() && "Unknown kind of DIType");
621     constructTypeDIE(*TyDIE, DIDerivedType(Ty));
622   }
623   // If this is a named finished type then include it in the list of types
624   // for the accelerator tables.
625   if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
626     bool IsImplementation = 0;
627     if (Ty.isCompositeType()) {
628       DICompositeType CT(Ty);
629       // A runtime language of 0 actually means C/C++ and that any
630       // non-negative value is some version of Objective-C/C++.
631       IsImplementation = (CT.getRunTimeLang() == 0) ||
632         CT.isObjcClassComplete();
633     }
634     unsigned Flags = IsImplementation ?
635                      DwarfAccelTable::eTypeFlagClassIsImplementation : 0;
636     addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
637   }
638   
639   addToContextOwner(TyDIE, Ty.getContext());
640   return TyDIE;
641 }
642
643 /// addType - Add a new type attribute to the specified entity.
644 void CompileUnit::addType(DIE *Entity, DIType Ty, unsigned Attribute) {
645   if (!Ty.Verify())
646     return;
647
648   // Check for pre-existence.
649   DIEEntry *Entry = getDIEEntry(Ty);
650   // If it exists then use the existing value.
651   if (Entry) {
652     Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
653     return;
654   }
655
656   // Construct type.
657   DIE *Buffer = getOrCreateTypeDIE(Ty);
658
659   // Set up proxy.
660   Entry = createDIEEntry(Buffer);
661   insertDIEEntry(Ty, Entry);
662   Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
663
664   // If this is a complete composite type then include it in the
665   // list of global types.
666   addGlobalType(Ty);
667 }
668
669 /// addGlobalType - Add a new global type to the compile unit.
670 ///
671 void CompileUnit::addGlobalType(DIType Ty) {
672   DIDescriptor Context = Ty.getContext();
673   if (Ty.isCompositeType() && !Ty.getName().empty() && !Ty.isForwardDecl() 
674       && (!Context || Context.isCompileUnit() || Context.isFile() 
675           || Context.isNameSpace()))
676     if (DIEEntry *Entry = getDIEEntry(Ty))
677       GlobalTypes[Ty.getName()] = Entry->getEntry();
678 }
679
680 /// addPubTypes - Add type for pubtypes section.
681 void CompileUnit::addPubTypes(DISubprogram SP) {
682   DICompositeType SPTy = SP.getType();
683   unsigned SPTag = SPTy.getTag();
684   if (SPTag != dwarf::DW_TAG_subroutine_type)
685     return;
686
687   DIArray Args = SPTy.getTypeArray();
688   for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
689     DIType ATy(Args.getElement(i));
690     if (!ATy.Verify())
691       continue;
692     addGlobalType(ATy);
693   }
694 }
695
696 /// constructTypeDIE - Construct basic type die from DIBasicType.
697 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
698   // Get core information.
699   StringRef Name = BTy.getName();
700   // Add name if not anonymous or intermediate type.
701   if (!Name.empty())
702     addString(&Buffer, dwarf::DW_AT_name, Name);
703
704   if (BTy.getTag() == dwarf::DW_TAG_unspecified_type) {
705     Buffer.setTag(dwarf::DW_TAG_unspecified_type);
706     // Unspecified types has only name, nothing else.
707     return;
708   }
709
710   Buffer.setTag(dwarf::DW_TAG_base_type);
711   addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
712           BTy.getEncoding());
713
714   uint64_t Size = BTy.getSizeInBits() >> 3;
715   addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
716 }
717
718 /// constructTypeDIE - Construct derived type die from DIDerivedType.
719 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
720   // Get core information.
721   StringRef Name = DTy.getName();
722   uint64_t Size = DTy.getSizeInBits() >> 3;
723   unsigned Tag = DTy.getTag();
724
725   // FIXME - Workaround for templates.
726   if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
727
728   Buffer.setTag(Tag);
729
730   // Map to main type, void will not have a type.
731   DIType FromTy = DTy.getTypeDerivedFrom();
732   addType(&Buffer, FromTy);
733
734   // Add name if not anonymous or intermediate type.
735   if (!Name.empty())
736     addString(&Buffer, dwarf::DW_AT_name, Name);
737
738   // Add size if non-zero (derived types might be zero-sized.)
739   if (Size && Tag != dwarf::DW_TAG_pointer_type)
740     addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
741
742   // Add source line info if available and TyDesc is not a forward declaration.
743   if (!DTy.isForwardDecl())
744     addSourceLine(&Buffer, DTy);
745 }
746
747 /// constructTypeDIE - Construct type DIE from DICompositeType.
748 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
749   // Get core information.
750   StringRef Name = CTy.getName();
751
752   uint64_t Size = CTy.getSizeInBits() >> 3;
753   unsigned Tag = CTy.getTag();
754   Buffer.setTag(Tag);
755
756   switch (Tag) {
757   case dwarf::DW_TAG_vector_type:
758   case dwarf::DW_TAG_array_type:
759     constructArrayTypeDIE(Buffer, &CTy);
760     break;
761   case dwarf::DW_TAG_enumeration_type: {
762     DIArray Elements = CTy.getTypeArray();
763
764     // Add enumerators to enumeration type.
765     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
766       DIE *ElemDie = NULL;
767       DIDescriptor Enum(Elements.getElement(i));
768       if (Enum.isEnumerator()) {
769         ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
770         Buffer.addChild(ElemDie);
771       }
772     }
773     DIType DTy = CTy.getTypeDerivedFrom();
774     if (DTy.Verify()) {
775       addType(&Buffer, DTy);
776       addUInt(&Buffer, dwarf::DW_AT_enum_class, dwarf::DW_FORM_flag, 1);
777     }
778   }
779     break;
780   case dwarf::DW_TAG_subroutine_type: {
781     // Add return type.
782     DIArray Elements = CTy.getTypeArray();
783     DIDescriptor RTy = Elements.getElement(0);
784     addType(&Buffer, DIType(RTy));
785
786     bool isPrototyped = true;
787     // Add arguments.
788     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
789       DIDescriptor Ty = Elements.getElement(i);
790       if (Ty.isUnspecifiedParameter()) {
791         DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
792         Buffer.addChild(Arg);
793         isPrototyped = false;
794       } else {
795         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
796         addType(Arg, DIType(Ty));
797         Buffer.addChild(Arg);
798       }
799     }
800     // Add prototype flag if we're dealing with a C language and the
801     // function has been prototyped.
802     if (isPrototyped &&
803         (Language == dwarf::DW_LANG_C89 ||
804          Language == dwarf::DW_LANG_C99 ||
805          Language == dwarf::DW_LANG_ObjC))
806       addFlag(&Buffer, dwarf::DW_AT_prototyped);
807   }
808     break;
809   case dwarf::DW_TAG_structure_type:
810   case dwarf::DW_TAG_union_type:
811   case dwarf::DW_TAG_class_type: {
812     // Add elements to structure type.
813     DIArray Elements = CTy.getTypeArray();
814
815     // A forward struct declared type may not have elements available.
816     unsigned N = Elements.getNumElements();
817     if (N == 0)
818       break;
819
820     // Add elements to structure type.
821     for (unsigned i = 0; i < N; ++i) {
822       DIDescriptor Element = Elements.getElement(i);
823       DIE *ElemDie = NULL;
824       if (Element.isSubprogram()) {
825         DISubprogram SP(Element);
826         ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
827         if (SP.isProtected())
828           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
829                   dwarf::DW_ACCESS_protected);
830         else if (SP.isPrivate())
831           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
832                   dwarf::DW_ACCESS_private);
833         else 
834           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
835             dwarf::DW_ACCESS_public);
836         if (SP.isExplicit())
837           addFlag(ElemDie, dwarf::DW_AT_explicit);
838       }
839       else if (Element.isVariable()) {
840         DIVariable DV(Element);
841         ElemDie = new DIE(dwarf::DW_TAG_variable);
842         addString(ElemDie, dwarf::DW_AT_name, DV.getName());
843         addType(ElemDie, DV.getType());
844         addFlag(ElemDie, dwarf::DW_AT_declaration);
845         addFlag(ElemDie, dwarf::DW_AT_external);
846         addSourceLine(ElemDie, DV);
847       } else if (Element.isDerivedType()) {
848         DIDerivedType DDTy(Element);
849         if (DDTy.getTag() == dwarf::DW_TAG_friend) {
850           ElemDie = new DIE(dwarf::DW_TAG_friend);
851           addType(ElemDie, DDTy.getTypeDerivedFrom(), dwarf::DW_AT_friend);
852         } else
853           ElemDie = createMemberDIE(DIDerivedType(Element));
854       } else if (Element.isObjCProperty()) {
855         DIObjCProperty Property(Element);
856         ElemDie = new DIE(Property.getTag());
857         StringRef PropertyName = Property.getObjCPropertyName();
858         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
859         addType(ElemDie, Property.getType());
860         addSourceLine(ElemDie, Property);
861         StringRef GetterName = Property.getObjCPropertyGetterName();
862         if (!GetterName.empty())
863           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
864         StringRef SetterName = Property.getObjCPropertySetterName();
865         if (!SetterName.empty())
866           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
867         unsigned PropertyAttributes = 0;
868         if (Property.isReadOnlyObjCProperty())
869           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
870         if (Property.isReadWriteObjCProperty())
871           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
872         if (Property.isAssignObjCProperty())
873           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
874         if (Property.isRetainObjCProperty())
875           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
876         if (Property.isCopyObjCProperty())
877           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
878         if (Property.isNonAtomicObjCProperty())
879           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
880         if (PropertyAttributes)
881           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, 0, 
882                  PropertyAttributes);
883
884         DIEEntry *Entry = getDIEEntry(Element);
885         if (!Entry) {
886           Entry = createDIEEntry(ElemDie);
887           insertDIEEntry(Element, Entry);
888         }
889       } else
890         continue;
891       Buffer.addChild(ElemDie);
892     }
893
894     if (CTy.isAppleBlockExtension())
895       addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
896
897     DICompositeType ContainingType = CTy.getContainingType();
898     if (DIDescriptor(ContainingType).isCompositeType())
899       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
900                   getOrCreateTypeDIE(DIType(ContainingType)));
901     else {
902       DIDescriptor Context = CTy.getContext();
903       addToContextOwner(&Buffer, Context);
904     }
905
906     if (CTy.isObjcClassComplete())
907       addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
908
909     // Add template parameters to a class, structure or union types.
910     // FIXME: The support isn't in the metadata for this yet.
911     if (Tag == dwarf::DW_TAG_class_type ||
912         Tag == dwarf::DW_TAG_structure_type ||
913         Tag == dwarf::DW_TAG_union_type)
914       addTemplateParams(Buffer, CTy.getTemplateParams());
915
916     break;
917   }
918   default:
919     break;
920   }
921
922   // Add name if not anonymous or intermediate type.
923   if (!Name.empty())
924     addString(&Buffer, dwarf::DW_AT_name, Name);
925
926   if (Tag == dwarf::DW_TAG_enumeration_type ||
927       Tag == dwarf::DW_TAG_class_type ||
928       Tag == dwarf::DW_TAG_structure_type ||
929       Tag == dwarf::DW_TAG_union_type) {
930     // Add size if non-zero (derived types might be zero-sized.)
931     // TODO: Do we care about size for enum forward declarations?
932     if (Size)
933       addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
934     else if (!CTy.isForwardDecl())
935       // Add zero size if it is not a forward declaration.
936       addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
937
938     // If we're a forward decl, say so.
939     if (CTy.isForwardDecl())
940       addFlag(&Buffer, dwarf::DW_AT_declaration);
941
942     // Add source line info if available.
943     if (!CTy.isForwardDecl())
944       addSourceLine(&Buffer, CTy);
945
946     // No harm in adding the runtime language to the declaration.
947     unsigned RLang = CTy.getRunTimeLang();
948     if (RLang)
949       addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
950               dwarf::DW_FORM_data1, RLang);
951   }
952 }
953
954 /// getOrCreateTemplateTypeParameterDIE - Find existing DIE or create new DIE 
955 /// for the given DITemplateTypeParameter.
956 DIE *
957 CompileUnit::getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP) {
958   DIE *ParamDIE = getDIE(TP);
959   if (ParamDIE)
960     return ParamDIE;
961
962   ParamDIE = new DIE(dwarf::DW_TAG_template_type_parameter);
963   addType(ParamDIE, TP.getType());
964   addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
965   return ParamDIE;
966 }
967
968 /// getOrCreateTemplateValueParameterDIE - Find existing DIE or create new DIE 
969 /// for the given DITemplateValueParameter.
970 DIE *
971 CompileUnit::getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV){
972   DIE *ParamDIE = getDIE(TPV);
973   if (ParamDIE)
974     return ParamDIE;
975
976   ParamDIE = new DIE(dwarf::DW_TAG_template_value_parameter);
977   addType(ParamDIE, TPV.getType());
978   if (!TPV.getName().empty())
979     addString(ParamDIE, dwarf::DW_AT_name, TPV.getName());
980   addUInt(ParamDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata, 
981           TPV.getValue());
982   return ParamDIE;
983 }
984
985 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
986 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
987   DIE *NDie = getDIE(NS);
988   if (NDie)
989     return NDie;
990   NDie = new DIE(dwarf::DW_TAG_namespace);
991   insertDIE(NS, NDie);
992   if (!NS.getName().empty()) {
993     addString(NDie, dwarf::DW_AT_name, NS.getName());
994     addAccelNamespace(NS.getName(), NDie);
995   } else
996     addAccelNamespace("(anonymous namespace)", NDie);
997   addSourceLine(NDie, NS);
998   addToContextOwner(NDie, NS.getContext());
999   return NDie;
1000 }
1001
1002 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1003 /// printer to not emit usual symbol prefix before the symbol name is used then
1004 /// return linkage name after skipping this special LLVM prefix.
1005 static StringRef getRealLinkageName(StringRef LinkageName) {
1006   char One = '\1';
1007   if (LinkageName.startswith(StringRef(&One, 1)))
1008     return LinkageName.substr(1);
1009   return LinkageName;
1010 }
1011
1012 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1013 DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1014   DIE *SPDie = getDIE(SP);
1015   if (SPDie)
1016     return SPDie;
1017
1018   SPDie = new DIE(dwarf::DW_TAG_subprogram);
1019
1020   // DW_TAG_inlined_subroutine may refer to this DIE.
1021   insertDIE(SP, SPDie);
1022
1023   DISubprogram SPDecl = SP.getFunctionDeclaration();
1024   DIE *DeclDie = NULL;
1025   if (SPDecl.isSubprogram()) {
1026     DeclDie = getOrCreateSubprogramDIE(SPDecl);
1027   }
1028
1029   // Add to context owner.
1030   addToContextOwner(SPDie, SP.getContext());
1031
1032   // Add function template parameters.
1033   addTemplateParams(*SPDie, SP.getTemplateParams());
1034
1035   // Unfortunately this code needs to stay here instead of below the
1036   // AT_specification code in order to work around a bug in older
1037   // gdbs that requires the linkage name to resolve multiple template
1038   // functions.
1039   // TODO: Remove this set of code when we get rid of the old gdb
1040   // compatibility.
1041   StringRef LinkageName = SP.getLinkageName();
1042   if (!LinkageName.empty() && DD->useDarwinGDBCompat())
1043     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1044               getRealLinkageName(LinkageName));
1045
1046   // If this DIE is going to refer declaration info using AT_specification
1047   // then there is no need to add other attributes.
1048   if (DeclDie) {
1049     // Refer function declaration directly.
1050     addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1051                 DeclDie);
1052
1053     return SPDie;
1054   }
1055
1056   // Add the linkage name if we have one.
1057   if (!LinkageName.empty() && !DD->useDarwinGDBCompat())
1058     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1059               getRealLinkageName(LinkageName));
1060
1061   // Constructors and operators for anonymous aggregates do not have names.
1062   if (!SP.getName().empty())
1063     addString(SPDie, dwarf::DW_AT_name, SP.getName());
1064
1065   addSourceLine(SPDie, SP);
1066
1067   // Add the prototype if we have a prototype and we have a C like
1068   // language.
1069   if (SP.isPrototyped() &&
1070       (Language == dwarf::DW_LANG_C89 ||
1071        Language == dwarf::DW_LANG_C99 ||
1072        Language == dwarf::DW_LANG_ObjC))
1073     addFlag(SPDie, dwarf::DW_AT_prototyped);
1074
1075   // Add Return Type.
1076   DICompositeType SPTy = SP.getType();
1077   DIArray Args = SPTy.getTypeArray();
1078   unsigned SPTag = SPTy.getTag();
1079
1080   if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1081     addType(SPDie, SPTy);
1082   else
1083     addType(SPDie, DIType(Args.getElement(0)));
1084
1085   unsigned VK = SP.getVirtuality();
1086   if (VK) {
1087     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1088     DIEBlock *Block = getDIEBlock();
1089     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1090     addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1091     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1092     ContainingTypeMap.insert(std::make_pair(SPDie,
1093                                             SP.getContainingType()));
1094   }
1095
1096   if (!SP.isDefinition()) {
1097     addFlag(SPDie, dwarf::DW_AT_declaration);
1098     
1099     // Add arguments. Do not add arguments for subprogram definition. They will
1100     // be handled while processing variables.
1101     DICompositeType SPTy = SP.getType();
1102     DIArray Args = SPTy.getTypeArray();
1103     unsigned SPTag = SPTy.getTag();
1104
1105     if (SPTag == dwarf::DW_TAG_subroutine_type)
1106       for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1107         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1108         DIType ATy = DIType(Args.getElement(i));
1109         addType(Arg, ATy);
1110         if (ATy.isArtificial())
1111           addFlag(Arg, dwarf::DW_AT_artificial);
1112         SPDie->addChild(Arg);
1113       }
1114   }
1115
1116   if (SP.isArtificial())
1117     addFlag(SPDie, dwarf::DW_AT_artificial);
1118
1119   if (!SP.isLocalToUnit())
1120     addFlag(SPDie, dwarf::DW_AT_external);
1121
1122   if (SP.isOptimized())
1123     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1124
1125   if (unsigned isa = Asm->getISAEncoding()) {
1126     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1127   }
1128
1129   return SPDie;
1130 }
1131
1132 // Return const expression if value is a GEP to access merged global
1133 // constant. e.g.
1134 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1135 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1136   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1137   if (!CE || CE->getNumOperands() != 3 ||
1138       CE->getOpcode() != Instruction::GetElementPtr)
1139     return NULL;
1140
1141   // First operand points to a global struct.
1142   Value *Ptr = CE->getOperand(0);
1143   if (!isa<GlobalValue>(Ptr) ||
1144       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1145     return NULL;
1146
1147   // Second operand is zero.
1148   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1149   if (!CI || !CI->isZero())
1150     return NULL;
1151
1152   // Third operand is offset.
1153   if (!isa<ConstantInt>(CE->getOperand(2)))
1154     return NULL;
1155
1156   return CE;
1157 }
1158
1159 /// createGlobalVariableDIE - create global variable DIE.
1160 void CompileUnit::createGlobalVariableDIE(const MDNode *N) {
1161   // Check for pre-existence.
1162   if (getDIE(N))
1163     return;
1164
1165   DIGlobalVariable GV(N);
1166   if (!GV.Verify())
1167     return;
1168
1169   DIE *VariableDIE = new DIE(GV.getTag());
1170   // Add to map.
1171   insertDIE(N, VariableDIE);
1172
1173   // Add name.
1174   addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1175   StringRef LinkageName = GV.getLinkageName();
1176   bool isGlobalVariable = GV.getGlobal() != NULL;
1177   if (!LinkageName.empty() && isGlobalVariable)
1178     addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1179               getRealLinkageName(LinkageName));
1180   // Add type.
1181   DIType GTy = GV.getType();
1182   addType(VariableDIE, GTy);
1183
1184   // Add scoping info.
1185   if (!GV.isLocalToUnit())
1186     addFlag(VariableDIE, dwarf::DW_AT_external);
1187
1188   // Add line number info.
1189   addSourceLine(VariableDIE, GV);
1190   // Add to context owner.
1191   DIDescriptor GVContext = GV.getContext();
1192   addToContextOwner(VariableDIE, GVContext);
1193   // Add location.
1194   bool addToAccelTable = false;
1195   DIE *VariableSpecDIE = NULL;
1196   if (isGlobalVariable) {
1197     addToAccelTable = true;
1198     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1199     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1200     addLabel(Block, 0, dwarf::DW_FORM_udata,
1201              Asm->Mang->getSymbol(GV.getGlobal()));
1202     // Do not create specification DIE if context is either compile unit
1203     // or a subprogram.
1204     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1205         !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1206       // Create specification DIE.
1207       VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1208       addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1209                   dwarf::DW_FORM_ref4, VariableDIE);
1210       addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1211       addFlag(VariableDIE, dwarf::DW_AT_declaration);
1212       addDie(VariableSpecDIE);
1213     } else {
1214       addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1215     }
1216   } else if (const ConstantInt *CI = 
1217              dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1218     addConstantValue(VariableDIE, CI, GTy.isUnsignedDIType());
1219   else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1220     addToAccelTable = true;
1221     // GV is a merged global.
1222     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1223     Value *Ptr = CE->getOperand(0);
1224     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1225     addLabel(Block, 0, dwarf::DW_FORM_udata,
1226                     Asm->Mang->getSymbol(cast<GlobalValue>(Ptr)));
1227     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1228     SmallVector<Value*, 3> Idx(CE->op_begin()+1, CE->op_end());
1229     addUInt(Block, 0, dwarf::DW_FORM_udata, 
1230                    Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1231     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1232     addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1233   }
1234
1235   if (addToAccelTable) {
1236     DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1237     addAccelName(GV.getName(), AddrDIE);
1238
1239     // If the linkage name is different than the name, go ahead and output
1240     // that as well into the name table.
1241     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1242       addAccelName(GV.getLinkageName(), AddrDIE);
1243   }
1244
1245   return;
1246 }
1247
1248 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1249 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1250                                        DIE *IndexTy) {
1251   DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1252   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1253   uint64_t L = SR.getLo();
1254   uint64_t H = SR.getHi();
1255   uint64_t C = SR.getCount();
1256
1257   // The L value defines the lower bounds which is typically zero for C/C++. The
1258   // H value is the upper bounds.  Values are 64 bit.  H - L + 1 is the size
1259   // of the array. If L > H then do not emit DW_AT_lower_bound and 
1260   // DW_AT_upper_bound attributes. If L is zero and H is also zero then the
1261   // array has one element and in such case do not emit lower bound.
1262
1263   if (L > H) {
1264     Buffer.addChild(DW_Subrange);
1265     return;
1266   }
1267   if (L)
1268     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1269   addUInt(DW_Subrange, dwarf::DW_AT_count, 0, C);
1270   Buffer.addChild(DW_Subrange);
1271 }
1272
1273 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1274 void CompileUnit::constructArrayTypeDIE(DIE &Buffer,
1275                                         DICompositeType *CTy) {
1276   Buffer.setTag(dwarf::DW_TAG_array_type);
1277   if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1278     addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1279
1280   // Emit derived type.
1281   addType(&Buffer, CTy->getTypeDerivedFrom());
1282   DIArray Elements = CTy->getTypeArray();
1283
1284   // Get an anonymous type for index type.
1285   DIE *IdxTy = getIndexTyDie();
1286   if (!IdxTy) {
1287     // Construct an anonymous type for index type.
1288     IdxTy = new DIE(dwarf::DW_TAG_base_type);
1289     addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1290     addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1291             dwarf::DW_ATE_signed);
1292     addDie(IdxTy);
1293     setIndexTyDie(IdxTy);
1294   }
1295
1296   // Add subranges to array type.
1297   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1298     DIDescriptor Element = Elements.getElement(i);
1299     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1300       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1301   }
1302 }
1303
1304 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1305 DIE *CompileUnit::constructEnumTypeDIE(DIEnumerator ETy) {
1306   DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1307   StringRef Name = ETy.getName();
1308   addString(Enumerator, dwarf::DW_AT_name, Name);
1309   int64_t Value = ETy.getEnumValue();
1310   addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1311   return Enumerator;
1312 }
1313
1314 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1315 /// vtables.
1316 void CompileUnit::constructContainingTypeDIEs() {
1317   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1318          CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1319     DIE *SPDie = CI->first;
1320     const MDNode *N = CI->second;
1321     if (!N) continue;
1322     DIE *NDie = getDIE(N);
1323     if (!NDie) continue;
1324     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1325   }
1326 }
1327
1328 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1329 DIE *CompileUnit::constructVariableDIE(DbgVariable *DV, bool isScopeAbstract) {
1330   StringRef Name = DV->getName();
1331   if (Name.empty())
1332     return NULL;
1333
1334   // Translate tag to proper Dwarf tag.
1335   unsigned Tag = DV->getTag();
1336
1337   // Define variable debug information entry.
1338   DIE *VariableDie = new DIE(Tag);
1339   DbgVariable *AbsVar = DV->getAbstractVariable();
1340   DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1341   if (AbsDIE)
1342     addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1343                             dwarf::DW_FORM_ref4, AbsDIE);
1344   else {
1345     addString(VariableDie, dwarf::DW_AT_name, Name);
1346     addSourceLine(VariableDie, DV->getVariable());
1347     addType(VariableDie, DV->getType());
1348   }
1349
1350   if (DV->isArtificial())
1351     addFlag(VariableDie, dwarf::DW_AT_artificial);
1352
1353   if (isScopeAbstract) {
1354     DV->setDIE(VariableDie);
1355     return VariableDie;
1356   }
1357
1358   // Add variable address.
1359
1360   unsigned Offset = DV->getDotDebugLocOffset();
1361   if (Offset != ~0U) {
1362     addLabel(VariableDie, dwarf::DW_AT_location,
1363                          dwarf::DW_FORM_data4,
1364                          Asm->GetTempSymbol("debug_loc", Offset));
1365     DV->setDIE(VariableDie);
1366     return VariableDie;
1367   }
1368
1369   // Check if variable is described by a DBG_VALUE instruction.
1370   if (const MachineInstr *DVInsn = DV->getMInsn()) {
1371     bool updated = false;
1372     if (DVInsn->getNumOperands() == 3) {
1373       if (DVInsn->getOperand(0).isReg()) {
1374         const MachineOperand RegOp = DVInsn->getOperand(0);
1375         const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1376         if (DVInsn->getOperand(1).isImm() &&
1377             TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1378           unsigned FrameReg = 0;
1379           const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1380           int Offset = 
1381             TFI->getFrameIndexReference(*Asm->MF, 
1382                                         DVInsn->getOperand(1).getImm(), 
1383                                         FrameReg);
1384           MachineLocation Location(FrameReg, Offset);
1385           addVariableAddress(DV, VariableDie, Location);
1386           
1387         } else if (RegOp.getReg())
1388           addVariableAddress(DV, VariableDie, 
1389                                          MachineLocation(RegOp.getReg()));
1390         updated = true;
1391       }
1392       else if (DVInsn->getOperand(0).isImm())
1393         updated = 
1394           addConstantValue(VariableDie, DVInsn->getOperand(0),
1395                                        DV->getType());
1396       else if (DVInsn->getOperand(0).isFPImm())
1397         updated =
1398           addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1399       else if (DVInsn->getOperand(0).isCImm())
1400         updated =
1401           addConstantValue(VariableDie, 
1402                                        DVInsn->getOperand(0).getCImm(),
1403                                        DV->getType().isUnsignedDIType());
1404     } else {
1405       addVariableAddress(DV, VariableDie, 
1406                                      Asm->getDebugValueLocation(DVInsn));
1407       updated = true;
1408     }
1409     if (!updated) {
1410       // If variableDie is not updated then DBG_VALUE instruction does not
1411       // have valid variable info.
1412       delete VariableDie;
1413       return NULL;
1414     }
1415     DV->setDIE(VariableDie);
1416     return VariableDie;
1417   } else {
1418     // .. else use frame index.
1419     int FI = DV->getFrameIndex();
1420     if (FI != ~0) {
1421       unsigned FrameReg = 0;
1422       const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1423       int Offset = 
1424         TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1425       MachineLocation Location(FrameReg, Offset);
1426       addVariableAddress(DV, VariableDie, Location);
1427     }
1428   }
1429
1430   DV->setDIE(VariableDie);
1431   return VariableDie;
1432 }
1433
1434 /// createMemberDIE - Create new member DIE.
1435 DIE *CompileUnit::createMemberDIE(DIDerivedType DT) {
1436   DIE *MemberDie = new DIE(DT.getTag());
1437   StringRef Name = DT.getName();
1438   if (!Name.empty())
1439     addString(MemberDie, dwarf::DW_AT_name, Name);
1440
1441   addType(MemberDie, DT.getTypeDerivedFrom());
1442
1443   addSourceLine(MemberDie, DT);
1444
1445   DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1446   addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1447
1448   uint64_t Size = DT.getSizeInBits();
1449   uint64_t FieldSize = DT.getOriginalTypeSize();
1450
1451   if (Size != FieldSize) {
1452     // Handle bitfield.
1453     addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1454     addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1455
1456     uint64_t Offset = DT.getOffsetInBits();
1457     uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1458     uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1459     uint64_t FieldOffset = (HiMark - FieldSize);
1460     Offset -= FieldOffset;
1461
1462     // Maybe we need to work from the other end.
1463     if (Asm->getDataLayout().isLittleEndian())
1464       Offset = FieldSize - (Offset + Size);
1465     addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1466
1467     // Here WD_AT_data_member_location points to the anonymous
1468     // field that includes this bit field.
1469     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1470
1471   } else
1472     // This is not a bitfield.
1473     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1474
1475   if (DT.getTag() == dwarf::DW_TAG_inheritance
1476       && DT.isVirtual()) {
1477
1478     // For C++, virtual base classes are not at fixed offset. Use following
1479     // expression to extract appropriate offset from vtable.
1480     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1481
1482     DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1483     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1484     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1485     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1486     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1487     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1488     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1489     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1490
1491     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1492              VBaseLocationDie);
1493   } else
1494     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1495
1496   if (DT.isProtected())
1497     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1498             dwarf::DW_ACCESS_protected);
1499   else if (DT.isPrivate())
1500     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1501             dwarf::DW_ACCESS_private);
1502   // Otherwise C++ member and base classes are considered public.
1503   else 
1504     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1505             dwarf::DW_ACCESS_public);
1506   if (DT.isVirtual())
1507     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1508             dwarf::DW_VIRTUALITY_virtual);
1509
1510   // Objective-C properties.
1511   if (MDNode *PNode = DT.getObjCProperty())
1512     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1513       MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4, 
1514                           PropertyDie);
1515
1516   // This is only for backward compatibility.
1517   StringRef PropertyName = DT.getObjCPropertyName();
1518   if (!PropertyName.empty()) {
1519     addString(MemberDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1520     StringRef GetterName = DT.getObjCPropertyGetterName();
1521     if (!GetterName.empty())
1522       addString(MemberDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1523     StringRef SetterName = DT.getObjCPropertySetterName();
1524     if (!SetterName.empty())
1525       addString(MemberDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1526     unsigned PropertyAttributes = 0;
1527     if (DT.isReadOnlyObjCProperty())
1528       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1529     if (DT.isReadWriteObjCProperty())
1530       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1531     if (DT.isAssignObjCProperty())
1532       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1533     if (DT.isRetainObjCProperty())
1534       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1535     if (DT.isCopyObjCProperty())
1536       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1537     if (DT.isNonAtomicObjCProperty())
1538       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1539     if (PropertyAttributes)
1540       addUInt(MemberDie, dwarf::DW_AT_APPLE_property_attribute, 0, 
1541               PropertyAttributes);
1542   }
1543   return MemberDie;
1544 }