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