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