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