Rename a method to match what it really does.
[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 writing dwarf compile unit.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "dwarfdebug"
15
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Analysis/DIBuilder.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Target/TargetFrameLowering.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/Support/ErrorHandling.h"
26
27 using namespace llvm;
28
29 /// CompileUnit - Compile unit constructor.
30 CompileUnit::CompileUnit(unsigned I, DIE *D, AsmPrinter *A, DwarfDebug *DW)
31   : ID(I), CUDie(D), Asm(A), DD(DW), IndexTyDie(0) {
32   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
33 }
34
35 /// ~CompileUnit - Destructor for compile unit.
36 CompileUnit::~CompileUnit() {
37   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
38     DIEBlocks[j]->~DIEBlock();
39 }
40
41 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
42 /// information entry.
43 DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
44   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
45   return Value;
46 }
47
48 /// addUInt - Add an unsigned integer attribute data and value.
49 ///
50 void CompileUnit::addUInt(DIE *Die, unsigned Attribute,
51                           unsigned Form, uint64_t Integer) {
52   if (!Form) Form = DIEInteger::BestForm(false, Integer);
53   DIEValue *Value = Integer == 1 ?
54     DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
55   Die->addValue(Attribute, Form, Value);
56 }
57
58 /// addSInt - Add an signed integer attribute data and value.
59 ///
60 void CompileUnit::addSInt(DIE *Die, unsigned Attribute,
61                           unsigned Form, int64_t Integer) {
62   if (!Form) Form = DIEInteger::BestForm(true, Integer);
63   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
64   Die->addValue(Attribute, Form, Value);
65 }
66
67 /// addString - Add a string attribute data and value. DIEString only
68 /// keeps string reference.
69 void CompileUnit::addString(DIE *Die, unsigned Attribute, unsigned Form,
70                             StringRef String) {
71   DIEValue *Value = new (DIEValueAllocator) DIEString(String);
72   Die->addValue(Attribute, Form, Value);
73 }
74
75 /// addLabel - Add a Dwarf label attribute data and value.
76 ///
77 void CompileUnit::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
78                            const MCSymbol *Label) {
79   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
80   Die->addValue(Attribute, Form, Value);
81 }
82
83 /// addDelta - Add a label delta attribute data and value.
84 ///
85 void CompileUnit::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
86                            const MCSymbol *Hi, const MCSymbol *Lo) {
87   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
88   Die->addValue(Attribute, Form, Value);
89 }
90
91 /// addDIEEntry - Add a DIE attribute data and value.
92 ///
93 void CompileUnit::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
94                               DIE *Entry) {
95   Die->addValue(Attribute, Form, createDIEEntry(Entry));
96 }
97
98
99 /// addBlock - Add block data.
100 ///
101 void CompileUnit::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
102                            DIEBlock *Block) {
103   Block->ComputeSize(Asm);
104   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
105   Die->addValue(Attribute, Block->BestForm(), Block);
106 }
107
108 /// addSourceLine - Add location information to specified debug information
109 /// entry.
110 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
111   // Verify variable.
112   if (!V.Verify())
113     return;
114   
115   unsigned Line = V.getLineNumber();
116   if (Line == 0)
117     return;
118   unsigned FileID = DD->GetOrCreateSourceID(V.getContext().getFilename(),
119                                             V.getContext().getDirectory());
120   assert(FileID && "Invalid file id");
121   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
122   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
123 }
124
125 /// addSourceLine - Add location information to specified debug information
126 /// entry.
127 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
128   // Verify global variable.
129   if (!G.Verify())
130     return;
131
132   unsigned Line = G.getLineNumber();
133   if (Line == 0)
134     return;
135   unsigned FileID = DD->GetOrCreateSourceID(G.getContext().getFilename(),
136                                             G.getContext().getDirectory());
137   assert(FileID && "Invalid file id");
138   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
139   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
140 }
141
142 /// addSourceLine - Add location information to specified debug information
143 /// entry.
144 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
145   // Verify subprogram.
146   if (!SP.Verify())
147     return;
148   // If the line number is 0, don't add it.
149   if (SP.getLineNumber() == 0)
150     return;
151
152   unsigned Line = SP.getLineNumber();
153   if (!SP.getContext().Verify())
154     return;
155   unsigned FileID = DD->GetOrCreateSourceID(SP.getFilename(), SP.getDirectory());
156   assert(FileID && "Invalid file id");
157   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
158   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
159 }
160
161 /// addSourceLine - Add location information to specified debug information
162 /// entry.
163 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
164   // Verify type.
165   if (!Ty.Verify())
166     return;
167
168   unsigned Line = Ty.getLineNumber();
169   if (Line == 0 || !Ty.getContext().Verify())
170     return;
171   unsigned FileID = DD->GetOrCreateSourceID(Ty.getFilename(), Ty.getDirectory());
172   assert(FileID && "Invalid file id");
173   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
174   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
175 }
176
177 /// addSourceLine - Add location information to specified debug information
178 /// entry.
179 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
180   // Verify namespace.
181   if (!NS.Verify())
182     return;
183
184   unsigned Line = NS.getLineNumber();
185   if (Line == 0)
186     return;
187   StringRef FN = NS.getFilename();
188
189   unsigned FileID = DD->GetOrCreateSourceID(FN, NS.getDirectory());
190   assert(FileID && "Invalid file id");
191   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
192   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
193 }
194
195 /// addFrameVariableAddress - Add DW_AT_location attribute for a 
196 /// DbgVariable based on provided frame index.
197 void CompileUnit::addFrameVariableAddress(DbgVariable *&DV, DIE *Die, 
198                                           int64_t FI) {
199   MachineLocation Location;
200   unsigned FrameReg;
201   const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
202   int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
203   Location.set(FrameReg, Offset);
204
205   if (DV->variableHasComplexAddress())
206     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
207   else if (DV->isBlockByrefVariable())
208     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
209   else
210     addAddress(Die, dwarf::DW_AT_location, Location);
211 }
212
213 /// addComplexAddress - Start with the address based on the location provided,
214 /// and generate the DWARF information necessary to find the actual variable
215 /// given the extra address information encoded in the DIVariable, starting from
216 /// the starting location.  Add the DWARF information to the die.
217 ///
218 void CompileUnit::addComplexAddress(DbgVariable *&DV, DIE *Die,
219                                     unsigned Attribute,
220                                     const MachineLocation &Location) {
221   DIType Ty = DV->getType();
222
223   // Decode the original location, and use that as the start of the byref
224   // variable's location.
225   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
226   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
227   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
228
229   if (Location.isReg()) {
230     if (Reg < 32) {
231       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
232     } else {
233       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
234       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
235     }
236   } else {
237     if (Reg < 32)
238       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
239     else {
240       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
241       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
242     }
243
244     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
245   }
246
247   for (unsigned i = 0, N = DV->getNumAddrElements(); i < N; ++i) {
248     uint64_t Element = DV->getAddrElement(i);
249
250     if (Element == DIBuilder::OpPlus) {
251       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
252       addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
253     } else if (Element == DIBuilder::OpDeref) {
254       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
255     } else llvm_unreachable("unknown DIBuilder Opcode");
256   }
257
258   // Now attach the location information to the DIE.
259   addBlock(Die, Attribute, 0, Block);
260 }
261
262 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
263    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
264    gives the variable VarName either the struct, or a pointer to the struct, as
265    its type.  This is necessary for various behind-the-scenes things the
266    compiler needs to do with by-reference variables in Blocks.
267
268    However, as far as the original *programmer* is concerned, the variable
269    should still have type 'SomeType', as originally declared.
270
271    The function getBlockByrefType dives into the __Block_byref_x_VarName
272    struct to find the original type of the variable, which is then assigned to
273    the variable's Debug Information Entry as its real type.  So far, so good.
274    However now the debugger will expect the variable VarName to have the type
275    SomeType.  So we need the location attribute for the variable to be an
276    expression that explains to the debugger how to navigate through the
277    pointers and struct to find the actual variable of type SomeType.
278
279    The following function does just that.  We start by getting
280    the "normal" location for the variable. This will be the location
281    of either the struct __Block_byref_x_VarName or the pointer to the
282    struct __Block_byref_x_VarName.
283
284    The struct will look something like:
285
286    struct __Block_byref_x_VarName {
287      ... <various fields>
288      struct __Block_byref_x_VarName *forwarding;
289      ... <various other fields>
290      SomeType VarName;
291      ... <maybe more fields>
292    };
293
294    If we are given the struct directly (as our starting point) we
295    need to tell the debugger to:
296
297    1).  Add the offset of the forwarding field.
298
299    2).  Follow that pointer to get the real __Block_byref_x_VarName
300    struct to use (the real one may have been copied onto the heap).
301
302    3).  Add the offset for the field VarName, to find the actual variable.
303
304    If we started with a pointer to the struct, then we need to
305    dereference that pointer first, before the other steps.
306    Translating this into DWARF ops, we will need to append the following
307    to the current location description for the variable:
308
309    DW_OP_deref                    -- optional, if we start with a pointer
310    DW_OP_plus_uconst <forward_fld_offset>
311    DW_OP_deref
312    DW_OP_plus_uconst <varName_fld_offset>
313
314    That is what this function does.  */
315
316 /// addBlockByrefAddress - Start with the address based on the location
317 /// provided, and generate the DWARF information necessary to find the
318 /// actual Block variable (navigating the Block struct) based on the
319 /// starting location.  Add the DWARF information to the die.  For
320 /// more information, read large comment just above here.
321 ///
322 void CompileUnit::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
323                                        unsigned Attribute,
324                                        const MachineLocation &Location) {
325   DIType Ty = DV->getType();
326   DIType TmpTy = Ty;
327   unsigned Tag = Ty.getTag();
328   bool isPointer = false;
329
330   StringRef varName = DV->getName();
331
332   if (Tag == dwarf::DW_TAG_pointer_type) {
333     DIDerivedType DTy = DIDerivedType(Ty);
334     TmpTy = DTy.getTypeDerivedFrom();
335     isPointer = true;
336   }
337
338   DICompositeType blockStruct = DICompositeType(TmpTy);
339
340   // Find the __forwarding field and the variable field in the __Block_byref
341   // struct.
342   DIArray Fields = blockStruct.getTypeArray();
343   DIDescriptor varField = DIDescriptor();
344   DIDescriptor forwardingField = DIDescriptor();
345
346   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
347     DIDescriptor Element = Fields.getElement(i);
348     DIDerivedType DT = DIDerivedType(Element);
349     StringRef fieldName = DT.getName();
350     if (fieldName == "__forwarding")
351       forwardingField = Element;
352     else if (fieldName == varName)
353       varField = Element;
354   }
355
356   // Get the offsets for the forwarding field and the variable field.
357   unsigned forwardingFieldOffset =
358     DIDerivedType(forwardingField).getOffsetInBits() >> 3;
359   unsigned varFieldOffset =
360     DIDerivedType(varField).getOffsetInBits() >> 3;
361
362   // Decode the original location, and use that as the start of the byref
363   // variable's location.
364   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
365   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
366   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
367
368   if (Location.isReg()) {
369     if (Reg < 32)
370       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
371     else {
372       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
373       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
374     }
375   } else {
376     if (Reg < 32)
377       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
378     else {
379       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
380       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
381     }
382
383     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
384   }
385
386   // If we started with a pointer to the __Block_byref... struct, then
387   // the first thing we need to do is dereference the pointer (DW_OP_deref).
388   if (isPointer)
389     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
390
391   // Next add the offset for the '__forwarding' field:
392   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
393   // adding the offset if it's 0.
394   if (forwardingFieldOffset > 0) {
395     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
396     addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
397   }
398
399   // Now dereference the __forwarding field to get to the real __Block_byref
400   // struct:  DW_OP_deref.
401   addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
402
403   // Now that we've got the real __Block_byref... struct, add the offset
404   // for the variable's field to get to the location of the actual variable:
405   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
406   if (varFieldOffset > 0) {
407     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
408     addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
409   }
410
411   // Now attach the location information to the DIE.
412   addBlock(Die, Attribute, 0, Block);
413 }
414
415 /// addAddress - Add an address attribute to a die based on the location
416 /// provided.
417 void CompileUnit::addAddress(DIE *Die, unsigned Attribute,
418                              const MachineLocation &Location) {
419   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
420   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
421   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
422
423   if (RI->getFrameRegister(*Asm->MF) == Location.getReg()
424       && Location.getOffset()) {
425     // If variable offset is based in frame register then use fbreg.
426     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
427     addSInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
428     addBlock(Die, Attribute, 0, Block);
429     return;
430   }
431
432   if (Location.isReg()) {
433     if (Reg < 32) {
434       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
435     } else {
436       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
437       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
438     }
439   } else {
440     if (Reg < 32) {
441       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
442     } else {
443       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
444       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
445     }
446
447     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
448   }
449
450   addBlock(Die, Attribute, 0, Block);
451 }
452
453 /// addRegisterAddress - Add register location entry in variable DIE.
454 bool CompileUnit::addRegisterAddress(DIE *Die, const MachineOperand &MO) {
455   assert (MO.isReg() && "Invalid machine operand!");
456   if (!MO.getReg())
457     return false;
458   MachineLocation Location;
459   Location.set(MO.getReg());
460   addAddress(Die, dwarf::DW_AT_location, Location);
461   return true;
462 }
463
464 /// addConstantValue - Add constant value entry in variable DIE.
465 bool CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO) {
466   assert (MO.isImm() && "Invalid machine operand!");
467   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
468   unsigned Imm = MO.getImm();
469   addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
470   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
471   return true;
472 }
473
474 /// addConstantFPValue - Add constant value entry in variable DIE.
475 bool CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
476   assert (MO.isFPImm() && "Invalid machine operand!");
477   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
478   APFloat FPImm = MO.getFPImm()->getValueAPF();
479
480   // Get the raw data form of the floating point.
481   const APInt FltVal = FPImm.bitcastToAPInt();
482   const char *FltPtr = (const char*)FltVal.getRawData();
483
484   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
485   bool LittleEndian = Asm->getTargetData().isLittleEndian();
486   int Incr = (LittleEndian ? 1 : -1);
487   int Start = (LittleEndian ? 0 : NumBytes - 1);
488   int Stop = (LittleEndian ? NumBytes : -1);
489
490   // Output the constant to DWARF one byte at a time.
491   for (; Start != Stop; Start += Incr)
492     addUInt(Block, 0, dwarf::DW_FORM_data1,
493             (unsigned char)0xFF & FltPtr[Start]);
494
495   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
496   return true;
497 }
498
499 /// addConstantValue - Add constant value entry in variable DIE.
500 bool CompileUnit::addConstantValue(DIE *Die, ConstantInt *CI,
501                                    bool Unsigned) {
502   if (CI->getBitWidth() <= 64) {
503     if (Unsigned)
504       addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
505               CI->getZExtValue());
506     else
507       addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
508               CI->getSExtValue());
509     return true;
510   }
511
512   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
513
514   // Get the raw data form of the large APInt.
515   const APInt Val = CI->getValue();
516   const char *Ptr = (const char*)Val.getRawData();
517
518   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
519   bool LittleEndian = Asm->getTargetData().isLittleEndian();
520   int Incr = (LittleEndian ? 1 : -1);
521   int Start = (LittleEndian ? 0 : NumBytes - 1);
522   int Stop = (LittleEndian ? NumBytes : -1);
523
524   // Output the constant to DWARF one byte at a time.
525   for (; Start != Stop; Start += Incr)
526     addUInt(Block, 0, dwarf::DW_FORM_data1,
527             (unsigned char)0xFF & Ptr[Start]);
528
529   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
530   return true;
531 }
532
533 /// addTemplateParams - Add template parameters in buffer.
534 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
535   // Add template parameters.
536   for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
537     DIDescriptor Element = TParams.getElement(i);
538     if (Element.isTemplateTypeParameter())
539       Buffer.addChild(getOrCreateTemplateTypeParameterDIE(
540                         DITemplateTypeParameter(Element)));
541     else if (Element.isTemplateValueParameter())
542       Buffer.addChild(getOrCreateTemplateValueParameterDIE(
543                         DITemplateValueParameter(Element)));
544   }
545
546 }
547 /// addToContextOwner - Add Die into the list of its context owner's children.
548 void CompileUnit::addToContextOwner(DIE *Die, DIDescriptor Context) {
549   if (Context.isType()) {
550     DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
551     ContextDIE->addChild(Die);
552   } else if (Context.isNameSpace()) {
553     DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
554     ContextDIE->addChild(Die);
555   } else if (Context.isSubprogram()) {
556     DIE *ContextDIE = DD->createSubprogramDIE(DISubprogram(Context));
557     ContextDIE->addChild(Die);
558   } else if (DIE *ContextDIE = getDIE(Context))
559     ContextDIE->addChild(Die);
560   else
561     addDie(Die);
562 }
563
564 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
565 /// given DIType.
566 DIE *CompileUnit::getOrCreateTypeDIE(DIType Ty) {
567   DIE *TyDIE = getDIE(Ty);
568   if (TyDIE)
569     return TyDIE;
570
571   // Create new type.
572   TyDIE = new DIE(dwarf::DW_TAG_base_type);
573   insertDIE(Ty, TyDIE);
574   if (Ty.isBasicType())
575     constructTypeDIE(*TyDIE, DIBasicType(Ty));
576   else if (Ty.isCompositeType())
577     constructTypeDIE(*TyDIE, DICompositeType(Ty));
578   else {
579     assert(Ty.isDerivedType() && "Unknown kind of DIType");
580     constructTypeDIE(*TyDIE, DIDerivedType(Ty));
581   }
582
583   addToContextOwner(TyDIE, Ty.getContext());
584   return TyDIE;
585 }
586
587 /// addType - Add a new type attribute to the specified entity.
588 void CompileUnit::addType(DIE *Entity, DIType Ty) {
589   if (!Ty.Verify())
590     return;
591
592   // Check for pre-existence.
593   DIEEntry *Entry = getDIEEntry(Ty);
594   // If it exists then use the existing value.
595   if (Entry) {
596     Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
597     return;
598   }
599
600   // Construct type.
601   DIE *Buffer = getOrCreateTypeDIE(Ty);
602
603   // Set up proxy.
604   Entry = createDIEEntry(Buffer);
605   insertDIEEntry(Ty, Entry);
606
607   Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
608 }
609
610 /// constructTypeDIE - Construct basic type die from DIBasicType.
611 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
612   // Get core information.
613   StringRef Name = BTy.getName();
614   Buffer.setTag(dwarf::DW_TAG_base_type);
615   addUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
616           BTy.getEncoding());
617
618   // Add name if not anonymous or intermediate type.
619   if (!Name.empty())
620     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
621   uint64_t Size = BTy.getSizeInBits() >> 3;
622   addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
623 }
624
625 /// constructTypeDIE - Construct derived type die from DIDerivedType.
626 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
627   // Get core information.
628   StringRef Name = DTy.getName();
629   uint64_t Size = DTy.getSizeInBits() >> 3;
630   unsigned Tag = DTy.getTag();
631
632   // FIXME - Workaround for templates.
633   if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
634
635   Buffer.setTag(Tag);
636
637   // Map to main type, void will not have a type.
638   DIType FromTy = DTy.getTypeDerivedFrom();
639   addType(&Buffer, FromTy);
640
641   // Add name if not anonymous or intermediate type.
642   if (!Name.empty())
643     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
644
645   // Add size if non-zero (derived types might be zero-sized.)
646   if (Size)
647     addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
648
649   // Add source line info if available and TyDesc is not a forward declaration.
650   if (!DTy.isForwardDecl())
651     addSourceLine(&Buffer, DTy);
652 }
653
654 /// constructTypeDIE - Construct type DIE from DICompositeType.
655 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
656   // Get core information.
657   StringRef Name = CTy.getName();
658
659   uint64_t Size = CTy.getSizeInBits() >> 3;
660   unsigned Tag = CTy.getTag();
661   Buffer.setTag(Tag);
662
663   switch (Tag) {
664   case dwarf::DW_TAG_vector_type:
665   case dwarf::DW_TAG_array_type:
666     constructArrayTypeDIE(Buffer, &CTy);
667     break;
668   case dwarf::DW_TAG_enumeration_type: {
669     DIArray Elements = CTy.getTypeArray();
670
671     // Add enumerators to enumeration type.
672     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
673       DIE *ElemDie = NULL;
674       DIDescriptor Enum(Elements.getElement(i));
675       if (Enum.isEnumerator()) {
676         ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
677         Buffer.addChild(ElemDie);
678       }
679     }
680   }
681     break;
682   case dwarf::DW_TAG_subroutine_type: {
683     // Add return type.
684     DIArray Elements = CTy.getTypeArray();
685     DIDescriptor RTy = Elements.getElement(0);
686     addType(&Buffer, DIType(RTy));
687
688     bool isPrototyped = true;
689     // Add arguments.
690     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
691       DIDescriptor Ty = Elements.getElement(i);
692       if (Ty.isUnspecifiedParameter()) {
693         DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
694         Buffer.addChild(Arg);
695         isPrototyped = false;
696       } else {
697         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
698         addType(Arg, DIType(Ty));
699         Buffer.addChild(Arg);
700       }
701     }
702     // Add prototype flag.
703     if (isPrototyped)
704       addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
705   }
706     break;
707   case dwarf::DW_TAG_structure_type:
708   case dwarf::DW_TAG_union_type:
709   case dwarf::DW_TAG_class_type: {
710     // Add elements to structure type.
711     DIArray Elements = CTy.getTypeArray();
712
713     // A forward struct declared type may not have elements available.
714     unsigned N = Elements.getNumElements();
715     if (N == 0)
716       break;
717
718     // Add elements to structure type.
719     for (unsigned i = 0; i < N; ++i) {
720       DIDescriptor Element = Elements.getElement(i);
721       DIE *ElemDie = NULL;
722       if (Element.isSubprogram()) {
723         DISubprogram SP(Element);
724         ElemDie = DD->createSubprogramDIE(DISubprogram(Element));
725         if (SP.isProtected())
726           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
727                   dwarf::DW_ACCESS_protected);
728         else if (SP.isPrivate())
729           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
730                   dwarf::DW_ACCESS_private);
731         else 
732           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
733             dwarf::DW_ACCESS_public);
734         if (SP.isExplicit())
735           addUInt(ElemDie, dwarf::DW_AT_explicit, dwarf::DW_FORM_flag, 1);
736       }
737       else if (Element.isVariable()) {
738         DIVariable DV(Element);
739         ElemDie = new DIE(dwarf::DW_TAG_variable);
740         addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
741                   DV.getName());
742         addType(ElemDie, DV.getType());
743         addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
744         addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
745         addSourceLine(ElemDie, DV);
746       } else if (Element.isDerivedType())
747         ElemDie = createMemberDIE(DIDerivedType(Element));
748       else
749         continue;
750       Buffer.addChild(ElemDie);
751     }
752
753     if (CTy.isAppleBlockExtension())
754       addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
755
756     unsigned RLang = CTy.getRunTimeLang();
757     if (RLang)
758       addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
759               dwarf::DW_FORM_data1, RLang);
760
761     DICompositeType ContainingType = CTy.getContainingType();
762     if (DIDescriptor(ContainingType).isCompositeType())
763       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
764                   getOrCreateTypeDIE(DIType(ContainingType)));
765     else {
766       DIDescriptor Context = CTy.getContext();
767       addToContextOwner(&Buffer, Context);
768     }
769
770     if (Tag == dwarf::DW_TAG_class_type) 
771       addTemplateParams(Buffer, CTy.getTemplateParams());
772
773     break;
774   }
775   default:
776     break;
777   }
778
779   // Add name if not anonymous or intermediate type.
780   if (!Name.empty())
781     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
782
783   if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
784       || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
785     {
786     // Add size if non-zero (derived types might be zero-sized.)
787     if (Size)
788       addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
789     else {
790       // Add zero size if it is not a forward declaration.
791       if (CTy.isForwardDecl())
792         addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
793       else
794         addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
795     }
796
797     // Add source line info if available.
798     if (!CTy.isForwardDecl())
799       addSourceLine(&Buffer, CTy);
800   }
801 }
802
803 /// getOrCreateTemplateTypeParameterDIE - Find existing DIE or create new DIE 
804 /// for the given DITemplateTypeParameter.
805 DIE *
806 CompileUnit::getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP) {
807   DIE *ParamDIE = getDIE(TP);
808   if (ParamDIE)
809     return ParamDIE;
810
811   ParamDIE = new DIE(dwarf::DW_TAG_template_type_parameter);
812   addType(ParamDIE, TP.getType());
813   addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TP.getName());
814   return ParamDIE;
815 }
816
817 /// getOrCreateTemplateValueParameterDIE - Find existing DIE or create new DIE 
818 /// for the given DITemplateValueParameter.
819 DIE *
820 CompileUnit::getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV) {
821   DIE *ParamDIE = getDIE(TPV);
822   if (ParamDIE)
823     return ParamDIE;
824
825   ParamDIE = new DIE(dwarf::DW_TAG_template_value_parameter);
826   addType(ParamDIE, TPV.getType());
827   if (!TPV.getName().empty())
828     addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TPV.getName());
829   addUInt(ParamDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata, 
830           TPV.getValue());
831   return ParamDIE;
832 }
833
834 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
835 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
836   DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
837   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
838   int64_t L = SR.getLo();
839   int64_t H = SR.getHi();
840
841   // The L value defines the lower bounds which is typically zero for C/C++. The
842   // H value is the upper bounds.  Values are 64 bit.  H - L + 1 is the size
843   // of the array. If L > H then do not emit DW_AT_lower_bound and 
844   // DW_AT_upper_bound attributes. If L is zero and H is also zero then the
845   // array has one element and in such case do not emit lower bound.
846
847   if (L > H) {
848     Buffer.addChild(DW_Subrange);
849     return;
850   }
851   if (L)
852     addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
853   addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
854   Buffer.addChild(DW_Subrange);
855 }
856
857 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
858 void CompileUnit::constructArrayTypeDIE(DIE &Buffer,
859                                         DICompositeType *CTy) {
860   Buffer.setTag(dwarf::DW_TAG_array_type);
861   if (CTy->getTag() == dwarf::DW_TAG_vector_type)
862     addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
863
864   // Emit derived type.
865   addType(&Buffer, CTy->getTypeDerivedFrom());
866   DIArray Elements = CTy->getTypeArray();
867
868   // Get an anonymous type for index type.
869   DIE *IdxTy = getIndexTyDie();
870   if (!IdxTy) {
871     // Construct an anonymous type for index type.
872     IdxTy = new DIE(dwarf::DW_TAG_base_type);
873     addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
874     addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
875             dwarf::DW_ATE_signed);
876     addDie(IdxTy);
877     setIndexTyDie(IdxTy);
878   }
879
880   // Add subranges to array type.
881   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
882     DIDescriptor Element = Elements.getElement(i);
883     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
884       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
885   }
886 }
887
888 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
889 DIE *CompileUnit::constructEnumTypeDIE(DIEnumerator ETy) {
890   DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
891   StringRef Name = ETy.getName();
892   addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
893   int64_t Value = ETy.getEnumValue();
894   addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
895   return Enumerator;
896 }
897
898 /// createMemberDIE - Create new member DIE.
899 DIE *CompileUnit::createMemberDIE(DIDerivedType DT) {
900   DIE *MemberDie = new DIE(DT.getTag());
901   StringRef Name = DT.getName();
902   if (!Name.empty())
903     addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
904
905   addType(MemberDie, DT.getTypeDerivedFrom());
906
907   addSourceLine(MemberDie, DT);
908
909   DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
910   addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
911
912   uint64_t Size = DT.getSizeInBits();
913   uint64_t FieldSize = DT.getOriginalTypeSize();
914
915   if (Size != FieldSize) {
916     // Handle bitfield.
917     addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
918     addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
919
920     uint64_t Offset = DT.getOffsetInBits();
921     uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
922     uint64_t HiMark = (Offset + FieldSize) & AlignMask;
923     uint64_t FieldOffset = (HiMark - FieldSize);
924     Offset -= FieldOffset;
925
926     // Maybe we need to work from the other end.
927     if (Asm->getTargetData().isLittleEndian())
928       Offset = FieldSize - (Offset + Size);
929     addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
930
931     // Here WD_AT_data_member_location points to the anonymous
932     // field that includes this bit field.
933     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
934
935   } else
936     // This is not a bitfield.
937     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
938
939   if (DT.getTag() == dwarf::DW_TAG_inheritance
940       && DT.isVirtual()) {
941
942     // For C++, virtual base classes are not at fixed offset. Use following
943     // expression to extract appropriate offset from vtable.
944     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
945
946     DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
947     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
948     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
949     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
950     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
951     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
952     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
953     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
954
955     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
956              VBaseLocationDie);
957   } else
958     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
959
960   if (DT.isProtected())
961     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
962             dwarf::DW_ACCESS_protected);
963   else if (DT.isPrivate())
964     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
965             dwarf::DW_ACCESS_private);
966   // Otherwise C++ member and base classes are considered public.
967   else if (DT.getCompileUnit().getLanguage() == dwarf::DW_LANG_C_plus_plus)
968     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
969             dwarf::DW_ACCESS_public);
970   if (DT.isVirtual())
971     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
972             dwarf::DW_VIRTUALITY_virtual);
973
974   // Objective-C properties.
975   StringRef PropertyName = DT.getObjCPropertyName();
976   if (!PropertyName.empty()) {
977     addString(MemberDie, dwarf::DW_AT_APPLE_property_name, dwarf::DW_FORM_string,
978               PropertyName);
979     StringRef GetterName = DT.getObjCPropertyGetterName();
980     if (!GetterName.empty())
981       addString(MemberDie, dwarf::DW_AT_APPLE_property_getter,
982                 dwarf::DW_FORM_string, GetterName);
983     StringRef SetterName = DT.getObjCPropertySetterName();
984     if (!SetterName.empty())
985       addString(MemberDie, dwarf::DW_AT_APPLE_property_setter,
986                 dwarf::DW_FORM_string, SetterName);
987     unsigned PropertyAttributes = 0;
988     if (DT.isReadOnlyObjCProperty())
989       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
990     if (DT.isReadWriteObjCProperty())
991       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
992     if (DT.isAssignObjCProperty())
993       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
994     if (DT.isRetainObjCProperty())
995       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
996     if (DT.isCopyObjCProperty())
997       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
998     if (DT.isNonAtomicObjCProperty())
999       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1000     if (PropertyAttributes)
1001       addUInt(MemberDie, dwarf::DW_AT_APPLE_property_attribute, 0, 
1002               PropertyAttributes);
1003   }
1004   return MemberDie;
1005 }