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