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