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