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