Sink DwarfUnit::addVariableAddress into DwarfCompileUnit since type units don't have...
[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 #include "DwarfUnit.h"
15
16 #include "DwarfAccelTable.h"
17 #include "DwarfCompileUnit.h"
18 #include "DwarfDebug.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DIBuilder.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 #include "llvm/Target/TargetSubtargetInfo.h"
36
37 using namespace llvm;
38
39 #define DEBUG_TYPE "dwarfdebug"
40
41 static cl::opt<bool>
42 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
43                        cl::desc("Generate DWARF4 type units."),
44                        cl::init(false));
45
46 /// Unit - Unit constructor.
47 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node,
48                      AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
49     : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
50       DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
51   assert(UnitTag == dwarf::DW_TAG_compile_unit ||
52          UnitTag == dwarf::DW_TAG_type_unit);
53   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
54 }
55
56 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
57                              DwarfDebug *DW, DwarfFile *DWU,
58                              MCDwarfDwoLineTable *SplitLineTable)
59     : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
60       CU(CU), SplitLineTable(SplitLineTable) {
61   if (SplitLineTable)
62     addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
63 }
64
65 /// ~Unit - Destructor for compile unit.
66 DwarfUnit::~DwarfUnit() {
67   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
68     DIEBlocks[j]->~DIEBlock();
69   for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
70     DIELocs[j]->~DIELoc();
71 }
72
73 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
74 /// information entry.
75 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
76   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
77   return Value;
78 }
79
80 /// getDefaultLowerBound - Return the default lower bound for an array. If the
81 /// DWARF version doesn't handle the language, return -1.
82 int64_t DwarfUnit::getDefaultLowerBound() const {
83   switch (getLanguage()) {
84   default:
85     break;
86
87   case dwarf::DW_LANG_C89:
88   case dwarf::DW_LANG_C99:
89   case dwarf::DW_LANG_C:
90   case dwarf::DW_LANG_C_plus_plus:
91   case dwarf::DW_LANG_ObjC:
92   case dwarf::DW_LANG_ObjC_plus_plus:
93     return 0;
94
95   case dwarf::DW_LANG_Fortran77:
96   case dwarf::DW_LANG_Fortran90:
97   case dwarf::DW_LANG_Fortran95:
98     return 1;
99
100   // The languages below have valid values only if the DWARF version >= 4.
101   case dwarf::DW_LANG_Java:
102   case dwarf::DW_LANG_Python:
103   case dwarf::DW_LANG_UPC:
104   case dwarf::DW_LANG_D:
105     if (dwarf::DWARF_VERSION >= 4)
106       return 0;
107     break;
108
109   case dwarf::DW_LANG_Ada83:
110   case dwarf::DW_LANG_Ada95:
111   case dwarf::DW_LANG_Cobol74:
112   case dwarf::DW_LANG_Cobol85:
113   case dwarf::DW_LANG_Modula2:
114   case dwarf::DW_LANG_Pascal83:
115   case dwarf::DW_LANG_PLI:
116     if (dwarf::DWARF_VERSION >= 4)
117       return 1;
118     break;
119   }
120
121   return -1;
122 }
123
124 /// Check whether the DIE for this MDNode can be shared across CUs.
125 static bool isShareableAcrossCUs(DIDescriptor D) {
126   // When the MDNode can be part of the type system, the DIE can be shared
127   // across CUs.
128   // Combining type units and cross-CU DIE sharing is lower value (since
129   // cross-CU DIE sharing is used in LTO and removes type redundancy at that
130   // level already) but may be implementable for some value in projects
131   // building multiple independent libraries with LTO and then linking those
132   // together.
133   return (D.isType() ||
134           (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
135          !GenerateDwarfTypeUnits;
136 }
137
138 /// getDIE - Returns the debug information entry map slot for the
139 /// specified debug variable. We delegate the request to DwarfDebug
140 /// when the DIE for this MDNode can be shared across CUs. The mappings
141 /// will be kept in DwarfDebug for shareable DIEs.
142 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
143   if (isShareableAcrossCUs(D))
144     return DD->getDIE(D);
145   return MDNodeToDieMap.lookup(D);
146 }
147
148 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
149 /// when the DIE for this MDNode can be shared across CUs. The mappings
150 /// will be kept in DwarfDebug for shareable DIEs.
151 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
152   if (isShareableAcrossCUs(Desc)) {
153     DD->insertDIE(Desc, D);
154     return;
155   }
156   MDNodeToDieMap.insert(std::make_pair(Desc, D));
157 }
158
159 /// addFlag - Add a flag that is true.
160 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
161   if (DD->getDwarfVersion() >= 4)
162     Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
163   else
164     Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
165 }
166
167 /// addUInt - Add an unsigned integer attribute data and value.
168 ///
169 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
170                         Optional<dwarf::Form> Form, uint64_t Integer) {
171   if (!Form)
172     Form = DIEInteger::BestForm(false, Integer);
173   DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
174                         DIEInteger(Integer);
175   Die.addValue(Attribute, *Form, Value);
176 }
177
178 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
179   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
180 }
181
182 /// addSInt - Add an signed integer attribute data and value.
183 ///
184 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
185                         Optional<dwarf::Form> Form, int64_t Integer) {
186   if (!Form)
187     Form = DIEInteger::BestForm(true, Integer);
188   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
189   Die.addValue(Attribute, *Form, Value);
190 }
191
192 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
193                         int64_t Integer) {
194   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
195 }
196
197 /// addString - Add a string attribute data and value. We always emit a
198 /// reference to the string pool instead of immediate strings so that DIEs have
199 /// more predictable sizes. In the case of split dwarf we emit an index
200 /// into another table which gets us the static offset into the string
201 /// table.
202 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
203                           StringRef String) {
204
205   if (!DD->useSplitDwarf())
206     return addLocalString(Die, Attribute, String);
207
208   unsigned idx = DU->getStringPool().getIndex(*Asm, String);
209   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
210   DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
211   Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
212 }
213
214 /// addLocalString - Add a string attribute data and value. This is guaranteed
215 /// to be in the local string pool instead of indirected.
216 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
217                                StringRef String) {
218   MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
219   DIEValue *Value;
220   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
221     Value = new (DIEValueAllocator) DIELabel(Symb);
222   else
223     Value = new (DIEValueAllocator) DIEDelta(Symb, DD->getDebugStrSym());
224   DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
225   Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
226 }
227
228 /// addExpr - Add a Dwarf expression attribute data and value.
229 ///
230 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
231   DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
232   Die.addValue((dwarf::Attribute)0, Form, Value);
233 }
234
235 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
236 ///
237 void DwarfUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
238                                 unsigned Index) {
239   DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
240   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
241                                                 : dwarf::DW_FORM_data4;
242   Die.addValue(Attribute, Form, Value);
243 }
244
245 /// addLabel - Add a Dwarf label attribute data and value.
246 ///
247 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
248                          const MCSymbol *Label) {
249   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
250   Die.addValue(Attribute, Form, Value);
251 }
252
253 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
254   addLabel(Die, (dwarf::Attribute)0, Form, 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 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
268   return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
269                         : getCU().getOrCreateSourceID(FileName, DirName);
270 }
271
272 /// addOpAddress - Add a dwarf op address data and value using the
273 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
274 ///
275 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
276   if (!DD->useSplitDwarf()) {
277     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
278     addLabel(Die, dwarf::DW_FORM_udata, Sym);
279   } else {
280     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
281     addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
282             DD->getAddressPool().getIndex(Sym));
283   }
284 }
285
286 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
287                               const MCSymbol *Hi, const MCSymbol *Lo) {
288   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
289   Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
290 }
291
292 /// addDIEEntry - Add a DIE attribute data and value.
293 ///
294 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
295   addDIEEntry(Die, Attribute, createDIEEntry(Entry));
296 }
297
298 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
299   // Flag the type unit reference as a declaration so that if it contains
300   // members (implicit special members, static data member definitions, member
301   // declarations for definitions in this CU, etc) consumers don't get confused
302   // and think this is a full definition.
303   addFlag(Die, dwarf::DW_AT_declaration);
304
305   Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
306                new (DIEValueAllocator) DIETypeSignature(Type));
307 }
308
309 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
310                             DIEEntry *Entry) {
311   const DIE *DieCU = Die.getUnitOrNull();
312   const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
313   if (!DieCU)
314     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
315     DieCU = &getUnitDie();
316   if (!EntryCU)
317     EntryCU = &getUnitDie();
318   Die.addValue(Attribute,
319                EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
320                Entry);
321 }
322
323 /// Create a DIE with the given Tag, add the DIE to its parent, and
324 /// call insertDIE if MD is not null.
325 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
326   assert(Tag != dwarf::DW_TAG_auto_variable &&
327          Tag != dwarf::DW_TAG_arg_variable);
328   Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
329   DIE &Die = *Parent.getChildren().back();
330   if (N)
331     insertDIE(N, &Die);
332   return Die;
333 }
334
335 /// addBlock - Add block data.
336 ///
337 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
338   Loc->ComputeSize(Asm);
339   DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
340   Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
341 }
342
343 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
344                          DIEBlock *Block) {
345   Block->ComputeSize(Asm);
346   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
347   Die.addValue(Attribute, Block->BestForm(), Block);
348 }
349
350 /// addSourceLine - Add location information to specified debug information
351 /// entry.
352 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
353                               StringRef Directory) {
354   if (Line == 0)
355     return;
356
357   unsigned FileID = getOrCreateSourceID(File, Directory);
358   assert(FileID && "Invalid file id");
359   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
360   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
361 }
362
363 /// addSourceLine - Add location information to specified debug information
364 /// entry.
365 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
366   assert(V.isVariable());
367
368   addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
369                 V.getContext().getDirectory());
370 }
371
372 /// addSourceLine - Add location information to specified debug information
373 /// entry.
374 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
375   assert(G.isGlobalVariable());
376
377   addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
378 }
379
380 /// addSourceLine - Add location information to specified debug information
381 /// entry.
382 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
383   assert(SP.isSubprogram());
384
385   addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
386 }
387
388 /// addSourceLine - Add location information to specified debug information
389 /// entry.
390 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
391   assert(Ty.isType());
392
393   addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
394 }
395
396 /// addSourceLine - Add location information to specified debug information
397 /// entry.
398 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
399   assert(Ty.isObjCProperty());
400
401   DIFile File = Ty.getFile();
402   addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
403                 File.getDirectory());
404 }
405
406 /// addSourceLine - Add location information to specified debug information
407 /// entry.
408 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
409   assert(NS.Verify());
410
411   addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
412 }
413
414 /// addRegisterOp - Add register operand.
415 // FIXME: Ideally, this would share the implementation with
416 // AsmPrinter::EmitDwarfRegOpPiece.
417 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
418                                    unsigned SizeInBits, unsigned OffsetInBits) {
419   const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
420   int DWReg = RI->getDwarfRegNum(Reg, false);
421   bool isSubRegister = DWReg < 0;
422
423   unsigned Idx = 0;
424
425   // Go up the super-register chain until we hit a valid dwarf register number.
426   for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
427     DWReg = RI->getDwarfRegNum(*SR, false);
428     if (DWReg >= 0)
429       Idx = RI->getSubRegIndex(*SR, Reg);
430   }
431
432   if (DWReg < 0) {
433     DEBUG(dbgs() << "Invalid Dwarf register number.\n");
434     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
435     return;
436   }
437
438   // Emit register.
439   if (DWReg < 32)
440     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
441   else {
442     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
443     addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
444   }
445
446   // Emit mask.
447   bool isPiece = SizeInBits > 0;
448   if (isSubRegister || isPiece) {
449     const unsigned SizeOfByte = 8;
450     unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
451     unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
452     unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
453     unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
454     assert(RegSizeInBits >= SizeInBits && "register smaller than value");
455
456     if (RegOffsetInBits != PieceOffsetInBits) {
457       // Manually shift the value into place, since the DW_OP_piece
458       // describes the part of the variable, not the position of the
459       // subregister.
460       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
461       addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
462       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
463     }
464
465     if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
466       assert(PieceSizeInBits > 0 && "piece has zero size");
467       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
468       addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
469       addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
470      } else {
471       assert(PieceSizeInBits > 0 && "piece has zero size");
472       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
473       addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
474     }
475   }
476 }
477
478 /// addRegisterOffset - Add register offset.
479 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
480                                   int64_t Offset) {
481   const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
482   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
483   const TargetRegisterInfo *TRI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
484   if (Reg == TRI->getFrameRegister(*Asm->MF))
485     // If variable offset is based in frame register then use fbreg.
486     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
487   else if (DWReg < 32)
488     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
489   else {
490     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
491     addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
492   }
493   addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
494 }
495
496 /// addAddress - Add an address attribute to a die based on the location
497 /// provided.
498 void DwarfUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
499                            const MachineLocation &Location, bool Indirect) {
500   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
501
502   if (Location.isReg() && !Indirect)
503     addRegisterOpPiece(*Loc, Location.getReg());
504   else {
505     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
506     if (Indirect && !Location.isReg()) {
507       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
508     }
509   }
510
511   // Now attach the location information to the DIE.
512   addBlock(Die, Attribute, Loc);
513 }
514
515 /// addComplexAddress - Start with the address based on the location provided,
516 /// and generate the DWARF information necessary to find the actual variable
517 /// given the extra address information encoded in the DbgVariable, starting
518 /// from the starting location.  Add the DWARF information to the die.
519 ///
520 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
521                                   dwarf::Attribute Attribute,
522                                   const MachineLocation &Location) {
523   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
524   unsigned N = DV.getNumAddrElements();
525   unsigned i = 0;
526   if (Location.isReg()) {
527     if (N >= 2 && DV.getAddrElement(0) == dwarf::DW_OP_plus) {
528       assert(!DV.getVariable().isIndirect() &&
529              "double indirection not handled");
530       // If first address element is OpPlus then emit
531       // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
532       addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
533       i = 2;
534     } else if (N >= 2 && DV.getAddrElement(0) == dwarf::DW_OP_deref) {
535       assert(!DV.getVariable().isIndirect() &&
536              "double indirection not handled");
537       addRegisterOpPiece(*Loc, Location.getReg(),
538                          DV.getExpression().getPieceSize(),
539                          DV.getExpression().getPieceOffset());
540       i = 3;
541     } else
542       addRegisterOpPiece(*Loc, Location.getReg());
543   } else
544     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
545
546   for (; i < N; ++i) {
547     uint64_t Element = DV.getAddrElement(i);
548     if (Element == dwarf::DW_OP_plus) {
549       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
550       addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
551
552     } else if (Element == dwarf::DW_OP_deref) {
553       if (!Location.isReg())
554         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
555
556     } else if (Element == dwarf::DW_OP_piece) {
557       const unsigned SizeOfByte = 8;
558       unsigned PieceOffsetInBits = DV.getAddrElement(++i)*SizeOfByte;
559       unsigned PieceSizeInBits = DV.getAddrElement(++i)*SizeOfByte;
560       // Emit DW_OP_bit_piece Size Offset.
561       assert(PieceSizeInBits > 0 && "piece has zero size");
562       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
563       addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
564       addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
565
566     } else
567       llvm_unreachable("unknown DIBuilder Opcode");
568   }
569
570   // Now attach the location information to the DIE.
571   addBlock(Die, Attribute, Loc);
572 }
573
574 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
575    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
576    gives the variable VarName either the struct, or a pointer to the struct, as
577    its type.  This is necessary for various behind-the-scenes things the
578    compiler needs to do with by-reference variables in Blocks.
579
580    However, as far as the original *programmer* is concerned, the variable
581    should still have type 'SomeType', as originally declared.
582
583    The function getBlockByrefType dives into the __Block_byref_x_VarName
584    struct to find the original type of the variable, which is then assigned to
585    the variable's Debug Information Entry as its real type.  So far, so good.
586    However now the debugger will expect the variable VarName to have the type
587    SomeType.  So we need the location attribute for the variable to be an
588    expression that explains to the debugger how to navigate through the
589    pointers and struct to find the actual variable of type SomeType.
590
591    The following function does just that.  We start by getting
592    the "normal" location for the variable. This will be the location
593    of either the struct __Block_byref_x_VarName or the pointer to the
594    struct __Block_byref_x_VarName.
595
596    The struct will look something like:
597
598    struct __Block_byref_x_VarName {
599      ... <various fields>
600      struct __Block_byref_x_VarName *forwarding;
601      ... <various other fields>
602      SomeType VarName;
603      ... <maybe more fields>
604    };
605
606    If we are given the struct directly (as our starting point) we
607    need to tell the debugger to:
608
609    1).  Add the offset of the forwarding field.
610
611    2).  Follow that pointer to get the real __Block_byref_x_VarName
612    struct to use (the real one may have been copied onto the heap).
613
614    3).  Add the offset for the field VarName, to find the actual variable.
615
616    If we started with a pointer to the struct, then we need to
617    dereference that pointer first, before the other steps.
618    Translating this into DWARF ops, we will need to append the following
619    to the current location description for the variable:
620
621    DW_OP_deref                    -- optional, if we start with a pointer
622    DW_OP_plus_uconst <forward_fld_offset>
623    DW_OP_deref
624    DW_OP_plus_uconst <varName_fld_offset>
625
626    That is what this function does.  */
627
628 /// addBlockByrefAddress - Start with the address based on the location
629 /// provided, and generate the DWARF information necessary to find the
630 /// actual Block variable (navigating the Block struct) based on the
631 /// starting location.  Add the DWARF information to the die.  For
632 /// more information, read large comment just above here.
633 ///
634 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
635                                      dwarf::Attribute Attribute,
636                                      const MachineLocation &Location) {
637   DIType Ty = DV.getType();
638   DIType TmpTy = Ty;
639   uint16_t Tag = Ty.getTag();
640   bool isPointer = false;
641
642   StringRef varName = DV.getName();
643
644   if (Tag == dwarf::DW_TAG_pointer_type) {
645     DIDerivedType DTy(Ty);
646     TmpTy = resolve(DTy.getTypeDerivedFrom());
647     isPointer = true;
648   }
649
650   DICompositeType blockStruct(TmpTy);
651
652   // Find the __forwarding field and the variable field in the __Block_byref
653   // struct.
654   DIArray Fields = blockStruct.getElements();
655   DIDerivedType varField;
656   DIDerivedType forwardingField;
657
658   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
659     DIDerivedType DT(Fields.getElement(i));
660     StringRef fieldName = DT.getName();
661     if (fieldName == "__forwarding")
662       forwardingField = DT;
663     else if (fieldName == varName)
664       varField = DT;
665   }
666
667   // Get the offsets for the forwarding field and the variable field.
668   unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
669   unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
670
671   // Decode the original location, and use that as the start of the byref
672   // variable's location.
673   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
674
675   if (Location.isReg())
676     addRegisterOpPiece(*Loc, Location.getReg());
677   else
678     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
679
680   // If we started with a pointer to the __Block_byref... struct, then
681   // the first thing we need to do is dereference the pointer (DW_OP_deref).
682   if (isPointer)
683     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
684
685   // Next add the offset for the '__forwarding' field:
686   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
687   // adding the offset if it's 0.
688   if (forwardingFieldOffset > 0) {
689     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
690     addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
691   }
692
693   // Now dereference the __forwarding field to get to the real __Block_byref
694   // struct:  DW_OP_deref.
695   addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
696
697   // Now that we've got the real __Block_byref... struct, add the offset
698   // for the variable's field to get to the location of the actual variable:
699   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
700   if (varFieldOffset > 0) {
701     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
702     addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
703   }
704
705   // Now attach the location information to the DIE.
706   addBlock(Die, Attribute, Loc);
707 }
708
709 /// Return true if type encoding is unsigned.
710 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
711   DIDerivedType DTy(Ty);
712   if (DTy.isDerivedType()) {
713     dwarf::Tag T = (dwarf::Tag)Ty.getTag();
714     // Encode pointer constants as unsigned bytes. This is used at least for
715     // null pointer constant emission.
716     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
717     // here, but accept them for now due to a bug in SROA producing bogus
718     // dbg.values.
719     if (T == dwarf::DW_TAG_pointer_type ||
720         T == dwarf::DW_TAG_ptr_to_member_type ||
721         T == dwarf::DW_TAG_reference_type ||
722         T == dwarf::DW_TAG_rvalue_reference_type)
723       return true;
724     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
725            T == dwarf::DW_TAG_volatile_type ||
726            T == dwarf::DW_TAG_restrict_type ||
727            T == dwarf::DW_TAG_enumeration_type);
728     if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
729       return isUnsignedDIType(DD, DD->resolve(Deriv));
730     // FIXME: Enums without a fixed underlying type have unknown signedness
731     // here, leading to incorrectly emitted constants.
732     assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
733     return false;
734   }
735
736   DIBasicType BTy(Ty);
737   assert(BTy.isBasicType());
738   unsigned Encoding = BTy.getEncoding();
739   assert((Encoding == dwarf::DW_ATE_unsigned ||
740           Encoding == dwarf::DW_ATE_unsigned_char ||
741           Encoding == dwarf::DW_ATE_signed ||
742           Encoding == dwarf::DW_ATE_signed_char ||
743           Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
744          "Unsupported encoding");
745   return (Encoding == dwarf::DW_ATE_unsigned ||
746           Encoding == dwarf::DW_ATE_unsigned_char ||
747           Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
748 }
749
750 /// If this type is derived from a base type then return base type size.
751 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
752   unsigned Tag = Ty.getTag();
753
754   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
755       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
756       Tag != dwarf::DW_TAG_restrict_type)
757     return Ty.getSizeInBits();
758
759   DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
760
761   // If this type is not derived from any type or the type is a declaration then
762   // take conservative approach.
763   if (!BaseType.isValid() || BaseType.isForwardDecl())
764     return Ty.getSizeInBits();
765
766   // If this is a derived type, go ahead and get the base type, unless it's a
767   // reference then it's just the size of the field. Pointer types have no need
768   // of this since they're a different type of qualification on the type.
769   if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
770       BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
771     return Ty.getSizeInBits();
772
773   if (BaseType.isDerivedType())
774     return getBaseTypeSize(DD, DIDerivedType(BaseType));
775
776   return BaseType.getSizeInBits();
777 }
778
779 /// addConstantFPValue - Add constant value entry in variable DIE.
780 void DwarfUnit::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 DwarfUnit::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 DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
810   addConstantValue(Die, CI->getValue(), Ty);
811 }
812
813 /// addConstantValue - Add constant value entry in variable DIE.
814 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
815                                  DIType Ty) {
816   assert(MO.isImm() && "Invalid machine operand!");
817
818   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
819 }
820
821 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
822   // FIXME: This is a bit conservative/simple - it emits negative values always
823   // sign extended to 64 bits rather than minimizing the number of bytes.
824   addUInt(Die, dwarf::DW_AT_const_value,
825           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
826 }
827
828 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
829   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
830 }
831
832 // addConstantValue - Add constant value entry in variable DIE.
833 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
834   unsigned CIBitWidth = Val.getBitWidth();
835   if (CIBitWidth <= 64) {
836     addConstantValue(Die, Unsigned,
837                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
838     return;
839   }
840
841   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
842
843   // Get the raw data form of the large APInt.
844   const uint64_t *Ptr64 = Val.getRawData();
845
846   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
847   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
848
849   // Output the constant to DWARF one byte at a time.
850   for (int i = 0; i < NumBytes; i++) {
851     uint8_t c;
852     if (LittleEndian)
853       c = Ptr64[i / 8] >> (8 * (i & 7));
854     else
855       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
856     addUInt(*Block, dwarf::DW_FORM_data1, c);
857   }
858
859   addBlock(Die, dwarf::DW_AT_const_value, Block);
860 }
861
862 /// addTemplateParams - Add template parameters into buffer.
863 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
864   // Add template parameters.
865   for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
866     DIDescriptor Element = TParams.getElement(i);
867     if (Element.isTemplateTypeParameter())
868       constructTemplateTypeParameterDIE(Buffer,
869                                         DITemplateTypeParameter(Element));
870     else if (Element.isTemplateValueParameter())
871       constructTemplateValueParameterDIE(Buffer,
872                                          DITemplateValueParameter(Element));
873   }
874 }
875
876 /// getOrCreateContextDIE - Get context owner's DIE.
877 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
878   if (!Context || Context.isFile())
879     return &getUnitDie();
880   if (Context.isType())
881     return getOrCreateTypeDIE(DIType(Context));
882   if (Context.isNameSpace())
883     return getOrCreateNameSpace(DINameSpace(Context));
884   if (Context.isSubprogram())
885     return getOrCreateSubprogramDIE(DISubprogram(Context));
886   return getDIE(Context);
887 }
888
889 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
890   DIScope Context = resolve(Ty.getContext());
891   DIE *ContextDIE = getOrCreateContextDIE(Context);
892
893   if (DIE *TyDIE = getDIE(Ty))
894     return TyDIE;
895
896   // Create new type.
897   DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
898
899   constructTypeDIE(TyDIE, Ty);
900
901   updateAcceleratorTables(Context, Ty, TyDIE);
902   return &TyDIE;
903 }
904
905 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
906 /// given DIType.
907 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
908   if (!TyNode)
909     return nullptr;
910
911   DIType Ty(TyNode);
912   assert(Ty.isType());
913   assert(Ty == resolve(Ty.getRef()) &&
914          "type was not uniqued, possible ODR violation.");
915
916   // DW_TAG_restrict_type is not supported in DWARF2
917   if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
918     return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
919
920   // Construct the context before querying for the existence of the DIE in case
921   // such construction creates the DIE.
922   DIScope Context = resolve(Ty.getContext());
923   DIE *ContextDIE = getOrCreateContextDIE(Context);
924   assert(ContextDIE);
925
926   if (DIE *TyDIE = getDIE(Ty))
927     return TyDIE;
928
929   // Create new type.
930   DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
931
932   updateAcceleratorTables(Context, Ty, TyDIE);
933
934   if (Ty.isBasicType())
935     constructTypeDIE(TyDIE, DIBasicType(Ty));
936   else if (Ty.isCompositeType()) {
937     DICompositeType CTy(Ty);
938     if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
939       if (MDString *TypeId = CTy.getIdentifier()) {
940         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
941         // Skip updating the accelerator tables since this is not the full type.
942         return &TyDIE;
943       }
944     constructTypeDIE(TyDIE, CTy);
945   } else {
946     assert(Ty.isDerivedType() && "Unknown kind of DIType");
947     constructTypeDIE(TyDIE, DIDerivedType(Ty));
948   }
949
950   return &TyDIE;
951 }
952
953 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
954                                         const DIE &TyDIE) {
955   if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
956     bool IsImplementation = 0;
957     if (Ty.isCompositeType()) {
958       DICompositeType CT(Ty);
959       // A runtime language of 0 actually means C/C++ and that any
960       // non-negative value is some version of Objective-C/C++.
961       IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
962     }
963     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
964     DD->addAccelType(Ty.getName(), TyDIE, Flags);
965
966     if (!Context || Context.isCompileUnit() || Context.isFile() ||
967         Context.isNameSpace())
968       addGlobalType(Ty, TyDIE, Context);
969   }
970 }
971
972 /// addType - Add a new type attribute to the specified entity.
973 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
974   assert(Ty && "Trying to add a type that doesn't exist?");
975
976   // Check for pre-existence.
977   DIEEntry *Entry = getDIEEntry(Ty);
978   // If it exists then use the existing value.
979   if (Entry) {
980     addDIEEntry(Entity, Attribute, Entry);
981     return;
982   }
983
984   // Construct type.
985   DIE *Buffer = getOrCreateTypeDIE(Ty);
986
987   // Set up proxy.
988   Entry = createDIEEntry(*Buffer);
989   insertDIEEntry(Ty, Entry);
990   addDIEEntry(Entity, Attribute, Entry);
991 }
992
993 /// getParentContextString - Walks the metadata parent chain in a language
994 /// specific manner (using the compile unit language) and returns
995 /// it as a string. This is done at the metadata level because DIEs may
996 /// not currently have been added to the parent context and walking the
997 /// DIEs looking for names is more expensive than walking the metadata.
998 std::string DwarfUnit::getParentContextString(DIScope Context) const {
999   if (!Context)
1000     return "";
1001
1002   // FIXME: Decide whether to implement this for non-C++ languages.
1003   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1004     return "";
1005
1006   std::string CS;
1007   SmallVector<DIScope, 1> Parents;
1008   while (!Context.isCompileUnit()) {
1009     Parents.push_back(Context);
1010     if (Context.getContext())
1011       Context = resolve(Context.getContext());
1012     else
1013       // Structure, etc types will have a NULL context if they're at the top
1014       // level.
1015       break;
1016   }
1017
1018   // Reverse iterate over our list to go from the outermost construct to the
1019   // innermost.
1020   for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1021                                                   E = Parents.rend();
1022        I != E; ++I) {
1023     DIScope Ctx = *I;
1024     StringRef Name = Ctx.getName();
1025     if (Name.empty() && Ctx.isNameSpace())
1026       Name = "(anonymous namespace)";
1027     if (!Name.empty()) {
1028       CS += Name;
1029       CS += "::";
1030     }
1031   }
1032   return CS;
1033 }
1034
1035 /// constructTypeDIE - Construct basic type die from DIBasicType.
1036 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1037   // Get core information.
1038   StringRef Name = BTy.getName();
1039   // Add name if not anonymous or intermediate type.
1040   if (!Name.empty())
1041     addString(Buffer, dwarf::DW_AT_name, Name);
1042
1043   // An unspecified type only has a name attribute.
1044   if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1045     return;
1046
1047   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1048           BTy.getEncoding());
1049
1050   uint64_t Size = BTy.getSizeInBits() >> 3;
1051   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1052 }
1053
1054 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1055 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1056   // Get core information.
1057   StringRef Name = DTy.getName();
1058   uint64_t Size = DTy.getSizeInBits() >> 3;
1059   uint16_t Tag = Buffer.getTag();
1060
1061   // Map to main type, void will not have a type.
1062   DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1063   if (FromTy)
1064     addType(Buffer, FromTy);
1065
1066   // Add name if not anonymous or intermediate type.
1067   if (!Name.empty())
1068     addString(Buffer, dwarf::DW_AT_name, Name);
1069
1070   // Add size if non-zero (derived types might be zero-sized.)
1071   if (Size && Tag != dwarf::DW_TAG_pointer_type)
1072     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1073
1074   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1075     addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1076                 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
1077   // Add source line info if available and TyDesc is not a forward declaration.
1078   if (!DTy.isForwardDecl())
1079     addSourceLine(Buffer, DTy);
1080 }
1081
1082 /// constructSubprogramArguments - Construct function argument DIEs.
1083 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1084   for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1085     DIType Ty = resolve(Args.getElement(i));
1086     if (!Ty) {
1087       assert(i == N-1 && "Unspecified parameter must be the last argument");
1088       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1089     } else {
1090       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1091       addType(Arg, Ty);
1092       if (Ty.isArtificial())
1093         addFlag(Arg, dwarf::DW_AT_artificial);
1094     }
1095   }
1096 }
1097
1098 /// constructTypeDIE - Construct type DIE from DICompositeType.
1099 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1100   // Add name if not anonymous or intermediate type.
1101   StringRef Name = CTy.getName();
1102
1103   uint64_t Size = CTy.getSizeInBits() >> 3;
1104   uint16_t Tag = Buffer.getTag();
1105
1106   switch (Tag) {
1107   case dwarf::DW_TAG_array_type:
1108     constructArrayTypeDIE(Buffer, CTy);
1109     break;
1110   case dwarf::DW_TAG_enumeration_type:
1111     constructEnumTypeDIE(Buffer, CTy);
1112     break;
1113   case dwarf::DW_TAG_subroutine_type: {
1114     // Add return type. A void return won't have a type.
1115     DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1116     DIType RTy(resolve(Elements.getElement(0)));
1117     if (RTy)
1118       addType(Buffer, RTy);
1119
1120     bool isPrototyped = true;
1121     if (Elements.getNumElements() == 2 &&
1122         !Elements.getElement(1))
1123       isPrototyped = false;
1124
1125     constructSubprogramArguments(Buffer, Elements);
1126
1127     // Add prototype flag if we're dealing with a C language and the
1128     // function has been prototyped.
1129     uint16_t Language = getLanguage();
1130     if (isPrototyped &&
1131         (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1132          Language == dwarf::DW_LANG_ObjC))
1133       addFlag(Buffer, dwarf::DW_AT_prototyped);
1134
1135     if (CTy.isLValueReference())
1136       addFlag(Buffer, dwarf::DW_AT_reference);
1137
1138     if (CTy.isRValueReference())
1139       addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1140   } break;
1141   case dwarf::DW_TAG_structure_type:
1142   case dwarf::DW_TAG_union_type:
1143   case dwarf::DW_TAG_class_type: {
1144     // Add elements to structure type.
1145     DIArray Elements = CTy.getElements();
1146     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1147       DIDescriptor Element = Elements.getElement(i);
1148       if (Element.isSubprogram())
1149         getOrCreateSubprogramDIE(DISubprogram(Element));
1150       else if (Element.isDerivedType()) {
1151         DIDerivedType DDTy(Element);
1152         if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1153           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1154           addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1155                   dwarf::DW_AT_friend);
1156         } else if (DDTy.isStaticMember()) {
1157           getOrCreateStaticMemberDIE(DDTy);
1158         } else {
1159           constructMemberDIE(Buffer, DDTy);
1160         }
1161       } else if (Element.isObjCProperty()) {
1162         DIObjCProperty Property(Element);
1163         DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1164         StringRef PropertyName = Property.getObjCPropertyName();
1165         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1166         if (Property.getType())
1167           addType(ElemDie, Property.getType());
1168         addSourceLine(ElemDie, Property);
1169         StringRef GetterName = Property.getObjCPropertyGetterName();
1170         if (!GetterName.empty())
1171           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1172         StringRef SetterName = Property.getObjCPropertySetterName();
1173         if (!SetterName.empty())
1174           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1175         unsigned PropertyAttributes = 0;
1176         if (Property.isReadOnlyObjCProperty())
1177           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1178         if (Property.isReadWriteObjCProperty())
1179           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1180         if (Property.isAssignObjCProperty())
1181           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1182         if (Property.isRetainObjCProperty())
1183           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1184         if (Property.isCopyObjCProperty())
1185           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1186         if (Property.isNonAtomicObjCProperty())
1187           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1188         if (PropertyAttributes)
1189           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1190                   PropertyAttributes);
1191
1192         DIEEntry *Entry = getDIEEntry(Element);
1193         if (!Entry) {
1194           Entry = createDIEEntry(ElemDie);
1195           insertDIEEntry(Element, Entry);
1196         }
1197       } else
1198         continue;
1199     }
1200
1201     if (CTy.isAppleBlockExtension())
1202       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1203
1204     DICompositeType ContainingType(resolve(CTy.getContainingType()));
1205     if (ContainingType)
1206       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1207                   *getOrCreateTypeDIE(ContainingType));
1208
1209     if (CTy.isObjcClassComplete())
1210       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1211
1212     // Add template parameters to a class, structure or union types.
1213     // FIXME: The support isn't in the metadata for this yet.
1214     if (Tag == dwarf::DW_TAG_class_type ||
1215         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1216       addTemplateParams(Buffer, CTy.getTemplateParams());
1217
1218     break;
1219   }
1220   default:
1221     break;
1222   }
1223
1224   // Add name if not anonymous or intermediate type.
1225   if (!Name.empty())
1226     addString(Buffer, dwarf::DW_AT_name, Name);
1227
1228   if (Tag == dwarf::DW_TAG_enumeration_type ||
1229       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1230       Tag == dwarf::DW_TAG_union_type) {
1231     // Add size if non-zero (derived types might be zero-sized.)
1232     // TODO: Do we care about size for enum forward declarations?
1233     if (Size)
1234       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1235     else if (!CTy.isForwardDecl())
1236       // Add zero size if it is not a forward declaration.
1237       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1238
1239     // If we're a forward decl, say so.
1240     if (CTy.isForwardDecl())
1241       addFlag(Buffer, dwarf::DW_AT_declaration);
1242
1243     // Add source line info if available.
1244     if (!CTy.isForwardDecl())
1245       addSourceLine(Buffer, CTy);
1246
1247     // No harm in adding the runtime language to the declaration.
1248     unsigned RLang = CTy.getRunTimeLang();
1249     if (RLang)
1250       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1251               RLang);
1252   }
1253 }
1254
1255 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1256 /// DITemplateTypeParameter.
1257 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1258                                                   DITemplateTypeParameter TP) {
1259   DIE &ParamDIE =
1260       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1261   // Add the type if it exists, it could be void and therefore no type.
1262   if (TP.getType())
1263     addType(ParamDIE, resolve(TP.getType()));
1264   if (!TP.getName().empty())
1265     addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1266 }
1267
1268 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1269 /// DITemplateValueParameter.
1270 void
1271 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1272                                               DITemplateValueParameter VP) {
1273   DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1274
1275   // Add the type if there is one, template template and template parameter
1276   // packs will not have a type.
1277   if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1278     addType(ParamDIE, resolve(VP.getType()));
1279   if (!VP.getName().empty())
1280     addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1281   if (Value *Val = VP.getValue()) {
1282     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1283       addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1284     else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1285       // For declaration non-type template parameters (such as global values and
1286       // functions)
1287       DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1288       addOpAddress(*Loc, Asm->getSymbol(GV));
1289       // Emit DW_OP_stack_value to use the address as the immediate value of the
1290       // parameter, rather than a pointer to it.
1291       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1292       addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1293     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1294       assert(isa<MDString>(Val));
1295       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1296                 cast<MDString>(Val)->getString());
1297     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1298       assert(isa<MDNode>(Val));
1299       DIArray A(cast<MDNode>(Val));
1300       addTemplateParams(ParamDIE, A);
1301     }
1302   }
1303 }
1304
1305 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1306 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1307   // Construct the context before querying for the existence of the DIE in case
1308   // such construction creates the DIE.
1309   DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1310
1311   if (DIE *NDie = getDIE(NS))
1312     return NDie;
1313   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1314
1315   StringRef Name = NS.getName();
1316   if (!Name.empty())
1317     addString(NDie, dwarf::DW_AT_name, NS.getName());
1318   else
1319     Name = "(anonymous namespace)";
1320   DD->addAccelNamespace(Name, NDie);
1321   addGlobalName(Name, NDie, NS.getContext());
1322   addSourceLine(NDie, NS);
1323   return &NDie;
1324 }
1325
1326 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1327 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1328   // Construct the context before querying for the existence of the DIE in case
1329   // such construction creates the DIE (as is the case for member function
1330   // declarations).
1331   DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1332
1333   if (DIE *SPDie = getDIE(SP))
1334     return SPDie;
1335
1336   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1337     // Add subprogram definitions to the CU die directly.
1338     ContextDIE = &getUnitDie();
1339     // Build the decl now to ensure it precedes the definition.
1340     getOrCreateSubprogramDIE(SPDecl);
1341   }
1342
1343   // DW_TAG_inlined_subroutine may refer to this DIE.
1344   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1345
1346   // Stop here and fill this in later, depending on whether or not this
1347   // subprogram turns out to have inlined instances or not.
1348   if (SP.isDefinition())
1349     return &SPDie;
1350
1351   applySubprogramAttributes(SP, SPDie);
1352   return &SPDie;
1353 }
1354
1355 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1356   DISubprogram SPDecl = SP.getFunctionDeclaration();
1357   DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1358   applySubprogramAttributes(SP, SPDie);
1359   addGlobalName(SP.getName(), SPDie, Context);
1360 }
1361
1362 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1363   DIE *DeclDie = nullptr;
1364   StringRef DeclLinkageName;
1365   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1366     DeclDie = getDIE(SPDecl);
1367     assert(DeclDie && "This DIE should've already been constructed when the "
1368                       "definition DIE was created in "
1369                       "getOrCreateSubprogramDIE");
1370     DeclLinkageName = SPDecl.getLinkageName();
1371   }
1372
1373   // Add function template parameters.
1374   addTemplateParams(SPDie, SP.getTemplateParams());
1375
1376   // Add the linkage name if we have one and it isn't in the Decl.
1377   StringRef LinkageName = SP.getLinkageName();
1378   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1379           LinkageName == DeclLinkageName) &&
1380          "decl has a linkage name and it is different");
1381   if (!LinkageName.empty() && DeclLinkageName.empty())
1382     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1383               GlobalValue::getRealLinkageName(LinkageName));
1384
1385   if (DeclDie) {
1386     // Refer to the function declaration where all the other attributes will be
1387     // found.
1388     addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1389     return;
1390   }
1391
1392   // Constructors and operators for anonymous aggregates do not have names.
1393   if (!SP.getName().empty())
1394     addString(SPDie, dwarf::DW_AT_name, SP.getName());
1395
1396   // Skip the rest of the attributes under -gmlt to save space.
1397   if(getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1398     return;
1399
1400   addSourceLine(SPDie, SP);
1401
1402   // Add the prototype if we have a prototype and we have a C like
1403   // language.
1404   uint16_t Language = getLanguage();
1405   if (SP.isPrototyped() &&
1406       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1407        Language == dwarf::DW_LANG_ObjC))
1408     addFlag(SPDie, dwarf::DW_AT_prototyped);
1409
1410   DISubroutineType SPTy = SP.getType();
1411   assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1412          "the type of a subprogram should be a subroutine");
1413
1414   DITypeArray Args = SPTy.getTypeArray();
1415   // Add a return type. If this is a type like a C/C++ void type we don't add a
1416   // return type.
1417   if (resolve(Args.getElement(0)))
1418     addType(SPDie, DIType(resolve(Args.getElement(0))));
1419
1420   unsigned VK = SP.getVirtuality();
1421   if (VK) {
1422     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1423     DIELoc *Block = getDIELoc();
1424     addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1425     addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1426     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1427     ContainingTypeMap.insert(
1428         std::make_pair(&SPDie, resolve(SP.getContainingType())));
1429   }
1430
1431   if (!SP.isDefinition()) {
1432     addFlag(SPDie, dwarf::DW_AT_declaration);
1433
1434     // Add arguments. Do not add arguments for subprogram definition. They will
1435     // be handled while processing variables.
1436     constructSubprogramArguments(SPDie, Args);
1437   }
1438
1439   if (SP.isArtificial())
1440     addFlag(SPDie, dwarf::DW_AT_artificial);
1441
1442   if (!SP.isLocalToUnit())
1443     addFlag(SPDie, dwarf::DW_AT_external);
1444
1445   if (SP.isOptimized())
1446     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1447
1448   if (unsigned isa = Asm->getISAEncoding()) {
1449     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1450   }
1451
1452   if (SP.isLValueReference())
1453     addFlag(SPDie, dwarf::DW_AT_reference);
1454
1455   if (SP.isRValueReference())
1456     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1457
1458   if (SP.isProtected())
1459     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1460             dwarf::DW_ACCESS_protected);
1461   else if (SP.isPrivate())
1462     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1463             dwarf::DW_ACCESS_private);
1464   else if (SP.isPublic())
1465     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1466             dwarf::DW_ACCESS_public);
1467
1468   if (SP.isExplicit())
1469     addFlag(SPDie, dwarf::DW_AT_explicit);
1470 }
1471
1472 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1473                                         DIE &VariableDie) {
1474   StringRef Name = Var.getName();
1475   if (!Name.empty())
1476     addString(VariableDie, dwarf::DW_AT_name, Name);
1477   addSourceLine(VariableDie, Var.getVariable());
1478   addType(VariableDie, Var.getType());
1479   if (Var.isArtificial())
1480     addFlag(VariableDie, dwarf::DW_AT_artificial);
1481 }
1482
1483 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1484 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1485   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1486   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1487
1488   // The LowerBound value defines the lower bounds which is typically zero for
1489   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1490   // Count == -1 then the array is unbounded and we do not emit
1491   // DW_AT_lower_bound and DW_AT_count attributes.
1492   int64_t LowerBound = SR.getLo();
1493   int64_t DefaultLowerBound = getDefaultLowerBound();
1494   int64_t Count = SR.getCount();
1495
1496   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1497     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1498
1499   if (Count != -1)
1500     // FIXME: An unbounded array should reference the expression that defines
1501     // the array.
1502     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1503 }
1504
1505 DIE *DwarfUnit::getIndexTyDie() {
1506   if (IndexTyDie)
1507     return IndexTyDie;
1508   // Construct an integer type to use for indexes.
1509   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1510   addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1511   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1512   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1513           dwarf::DW_ATE_unsigned);
1514   return IndexTyDie;
1515 }
1516
1517 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1518 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1519   if (CTy.isVector())
1520     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1521
1522   // Emit the element type.
1523   addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1524
1525   // Get an anonymous type for index type.
1526   // FIXME: This type should be passed down from the front end
1527   // as different languages may have different sizes for indexes.
1528   DIE *IdxTy = getIndexTyDie();
1529
1530   // Add subranges to array type.
1531   DIArray Elements = CTy.getElements();
1532   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1533     DIDescriptor Element = Elements.getElement(i);
1534     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1535       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1536   }
1537 }
1538
1539 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1540 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1541   DIArray Elements = CTy.getElements();
1542
1543   // Add enumerators to enumeration type.
1544   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1545     DIEnumerator Enum(Elements.getElement(i));
1546     if (Enum.isEnumerator()) {
1547       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1548       StringRef Name = Enum.getName();
1549       addString(Enumerator, dwarf::DW_AT_name, Name);
1550       int64_t Value = Enum.getEnumValue();
1551       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1552               Value);
1553     }
1554   }
1555   DIType DTy = resolve(CTy.getTypeDerivedFrom());
1556   if (DTy) {
1557     addType(Buffer, DTy);
1558     addFlag(Buffer, dwarf::DW_AT_enum_class);
1559   }
1560 }
1561
1562 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1563 /// vtables.
1564 void DwarfUnit::constructContainingTypeDIEs() {
1565   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1566                                                  CE = ContainingTypeMap.end();
1567        CI != CE; ++CI) {
1568     DIE &SPDie = *CI->first;
1569     DIDescriptor D(CI->second);
1570     if (!D)
1571       continue;
1572     DIE *NDie = getDIE(D);
1573     if (!NDie)
1574       continue;
1575     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1576   }
1577 }
1578
1579 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1580 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1581   DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1582   StringRef Name = DT.getName();
1583   if (!Name.empty())
1584     addString(MemberDie, dwarf::DW_AT_name, Name);
1585
1586   addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1587
1588   addSourceLine(MemberDie, DT);
1589
1590   if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1591
1592     // For C++, virtual base classes are not at fixed offset. Use following
1593     // expression to extract appropriate offset from vtable.
1594     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1595
1596     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1597     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1598     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1599     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1600     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1601     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1602     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1603     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1604
1605     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1606   } else {
1607     uint64_t Size = DT.getSizeInBits();
1608     uint64_t FieldSize = getBaseTypeSize(DD, DT);
1609     uint64_t OffsetInBytes;
1610
1611     if (Size != FieldSize) {
1612       // Handle bitfield, assume bytes are 8 bits.
1613       addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1614       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1615
1616       uint64_t Offset = DT.getOffsetInBits();
1617       uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1618       uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1619       uint64_t FieldOffset = (HiMark - FieldSize);
1620       Offset -= FieldOffset;
1621
1622       // Maybe we need to work from the other end.
1623       if (Asm->getDataLayout().isLittleEndian())
1624         Offset = FieldSize - (Offset + Size);
1625       addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1626
1627       // Here DW_AT_data_member_location points to the anonymous
1628       // field that includes this bit field.
1629       OffsetInBytes = FieldOffset >> 3;
1630     } else
1631       // This is not a bitfield.
1632       OffsetInBytes = DT.getOffsetInBits() >> 3;
1633
1634     if (DD->getDwarfVersion() <= 2) {
1635       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1636       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1637       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1638       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1639     } else
1640       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1641               OffsetInBytes);
1642   }
1643
1644   if (DT.isProtected())
1645     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1646             dwarf::DW_ACCESS_protected);
1647   else if (DT.isPrivate())
1648     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1649             dwarf::DW_ACCESS_private);
1650   // Otherwise C++ member and base classes are considered public.
1651   else if (DT.isPublic())
1652     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1653             dwarf::DW_ACCESS_public);
1654   if (DT.isVirtual())
1655     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1656             dwarf::DW_VIRTUALITY_virtual);
1657
1658   // Objective-C properties.
1659   if (MDNode *PNode = DT.getObjCProperty())
1660     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1661       MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1662                          PropertyDie);
1663
1664   if (DT.isArtificial())
1665     addFlag(MemberDie, dwarf::DW_AT_artificial);
1666 }
1667
1668 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1669 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1670   if (!DT.Verify())
1671     return nullptr;
1672
1673   // Construct the context before querying for the existence of the DIE in case
1674   // such construction creates the DIE.
1675   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1676   assert(dwarf::isType(ContextDIE->getTag()) &&
1677          "Static member should belong to a type.");
1678
1679   if (DIE *StaticMemberDIE = getDIE(DT))
1680     return StaticMemberDIE;
1681
1682   DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1683
1684   DIType Ty = resolve(DT.getTypeDerivedFrom());
1685
1686   addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1687   addType(StaticMemberDIE, Ty);
1688   addSourceLine(StaticMemberDIE, DT);
1689   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1690   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1691
1692   // FIXME: We could omit private if the parent is a class_type, and
1693   // public if the parent is something else.
1694   if (DT.isProtected())
1695     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1696             dwarf::DW_ACCESS_protected);
1697   else if (DT.isPrivate())
1698     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1699             dwarf::DW_ACCESS_private);
1700   else if (DT.isPublic())
1701     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1702             dwarf::DW_ACCESS_public);
1703
1704   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1705     addConstantValue(StaticMemberDIE, CI, Ty);
1706   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1707     addConstantFPValue(StaticMemberDIE, CFP);
1708
1709   return &StaticMemberDIE;
1710 }
1711
1712 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
1713   // Emit size of content not including length itself
1714   Asm->OutStreamer.AddComment("Length of Unit");
1715   Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1716
1717   Asm->OutStreamer.AddComment("DWARF version number");
1718   Asm->EmitInt16(DD->getDwarfVersion());
1719   Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1720   // We share one abbreviations table across all units so it's always at the
1721   // start of the section. Use a relocatable offset where needed to ensure
1722   // linking doesn't invalidate that offset.
1723   if (ASectionSym)
1724     Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1725   else
1726     // Use a constant value when no symbol is provided.
1727     Asm->EmitInt32(0);
1728   Asm->OutStreamer.AddComment("Address Size (in bytes)");
1729   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1730 }
1731
1732 void DwarfUnit::initSection(const MCSection *Section) {
1733   assert(!this->Section);
1734   this->Section = Section;
1735 }
1736
1737 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
1738   DwarfUnit::emitHeader(ASectionSym);
1739   Asm->OutStreamer.AddComment("Type Signature");
1740   Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1741   Asm->OutStreamer.AddComment("Type DIE Offset");
1742   // In a skeleton type unit there is no type DIE so emit a zero offset.
1743   Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1744                                 sizeof(Ty->getOffset()));
1745 }
1746