1221337Sdim//===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Unit ------------===//
2221337Sdim//
3221337Sdim//                     The LLVM Compiler Infrastructure
4221337Sdim//
5221337Sdim// This file is distributed under the University of Illinois Open Source
6221337Sdim// License. See LICENSE.TXT for details.
7221337Sdim//
8221337Sdim//===----------------------------------------------------------------------===//
9221337Sdim//
10245431Sdim// This file contains support for constructing a dwarf compile unit.
11221337Sdim//
12221337Sdim//===----------------------------------------------------------------------===//
13221337Sdim
14221337Sdim#define DEBUG_TYPE "dwarfdebug"
15221337Sdim
16252723Sdim#include "DwarfCompileUnit.h"
17235633Sdim#include "DwarfAccelTable.h"
18221337Sdim#include "DwarfDebug.h"
19252723Sdim#include "llvm/ADT/APFloat.h"
20245431Sdim#include "llvm/DIBuilder.h"
21252723Sdim#include "llvm/IR/Constants.h"
22252723Sdim#include "llvm/IR/DataLayout.h"
23252723Sdim#include "llvm/IR/GlobalVariable.h"
24252723Sdim#include "llvm/IR/Instructions.h"
25263509Sdim#include "llvm/MC/MCSection.h"
26263509Sdim#include "llvm/MC/MCStreamer.h"
27226890Sdim#include "llvm/Target/Mangler.h"
28221337Sdim#include "llvm/Target/TargetFrameLowering.h"
29221337Sdim#include "llvm/Target/TargetMachine.h"
30263509Sdim#include "llvm/Target/TargetLoweringObjectFile.h"
31221337Sdim#include "llvm/Target/TargetRegisterInfo.h"
32221337Sdim
33221337Sdimusing namespace llvm;
34221337Sdim
35221337Sdim/// CompileUnit - Compile unit constructor.
36263509SdimCompileUnit::CompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
37263509Sdim                         AsmPrinter *A, DwarfDebug *DW, DwarfUnits *DWU)
38263509Sdim    : UniqueID(UID), Node(Node), CUDie(D), Asm(A), DD(DW), DU(DWU),
39263509Sdim      IndexTyDie(0), DebugInfoOffset(0) {
40221337Sdim  DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
41263509Sdim  insertDIE(Node, D);
42221337Sdim}
43221337Sdim
44221337Sdim/// ~CompileUnit - Destructor for compile unit.
45221337SdimCompileUnit::~CompileUnit() {
46221337Sdim  for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
47221337Sdim    DIEBlocks[j]->~DIEBlock();
48221337Sdim}
49221337Sdim
50221337Sdim/// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
51221337Sdim/// information entry.
52221337SdimDIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
53221337Sdim  DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
54221337Sdim  return Value;
55221337Sdim}
56221337Sdim
57252723Sdim/// getDefaultLowerBound - Return the default lower bound for an array. If the
58252723Sdim/// DWARF version doesn't handle the language, return -1.
59252723Sdimint64_t CompileUnit::getDefaultLowerBound() const {
60263509Sdim  switch (getLanguage()) {
61252723Sdim  default:
62252723Sdim    break;
63252723Sdim
64252723Sdim  case dwarf::DW_LANG_C89:
65252723Sdim  case dwarf::DW_LANG_C99:
66252723Sdim  case dwarf::DW_LANG_C:
67252723Sdim  case dwarf::DW_LANG_C_plus_plus:
68252723Sdim  case dwarf::DW_LANG_ObjC:
69252723Sdim  case dwarf::DW_LANG_ObjC_plus_plus:
70252723Sdim    return 0;
71252723Sdim
72252723Sdim  case dwarf::DW_LANG_Fortran77:
73252723Sdim  case dwarf::DW_LANG_Fortran90:
74252723Sdim  case dwarf::DW_LANG_Fortran95:
75252723Sdim    return 1;
76252723Sdim
77252723Sdim  // The languages below have valid values only if the DWARF version >= 4.
78252723Sdim  case dwarf::DW_LANG_Java:
79252723Sdim  case dwarf::DW_LANG_Python:
80252723Sdim  case dwarf::DW_LANG_UPC:
81252723Sdim  case dwarf::DW_LANG_D:
82252723Sdim    if (dwarf::DWARF_VERSION >= 4)
83252723Sdim      return 0;
84252723Sdim    break;
85252723Sdim
86252723Sdim  case dwarf::DW_LANG_Ada83:
87252723Sdim  case dwarf::DW_LANG_Ada95:
88252723Sdim  case dwarf::DW_LANG_Cobol74:
89252723Sdim  case dwarf::DW_LANG_Cobol85:
90252723Sdim  case dwarf::DW_LANG_Modula2:
91252723Sdim  case dwarf::DW_LANG_Pascal83:
92252723Sdim  case dwarf::DW_LANG_PLI:
93252723Sdim    if (dwarf::DWARF_VERSION >= 4)
94252723Sdim      return 1;
95252723Sdim    break;
96252723Sdim  }
97252723Sdim
98252723Sdim  return -1;
99252723Sdim}
100252723Sdim
101263509Sdim/// Check whether the DIE for this MDNode can be shared across CUs.
102263509Sdimstatic bool isShareableAcrossCUs(DIDescriptor D) {
103263509Sdim  // When the MDNode can be part of the type system, the DIE can be
104263509Sdim  // shared across CUs.
105263509Sdim  return D.isType() ||
106263509Sdim         (D.isSubprogram() && !DISubprogram(D).isDefinition());
107263509Sdim}
108263509Sdim
109263509Sdim/// getDIE - Returns the debug information entry map slot for the
110263509Sdim/// specified debug variable. We delegate the request to DwarfDebug
111263509Sdim/// when the DIE for this MDNode can be shared across CUs. The mappings
112263509Sdim/// will be kept in DwarfDebug for shareable DIEs.
113263509SdimDIE *CompileUnit::getDIE(DIDescriptor D) const {
114263509Sdim  if (isShareableAcrossCUs(D))
115263509Sdim    return DD->getDIE(D);
116263509Sdim  return MDNodeToDieMap.lookup(D);
117263509Sdim}
118263509Sdim
119263509Sdim/// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
120263509Sdim/// when the DIE for this MDNode can be shared across CUs. The mappings
121263509Sdim/// will be kept in DwarfDebug for shareable DIEs.
122263509Sdimvoid CompileUnit::insertDIE(DIDescriptor Desc, DIE *D) {
123263509Sdim  if (isShareableAcrossCUs(Desc)) {
124263509Sdim    DD->insertDIE(Desc, D);
125263509Sdim    return;
126263509Sdim  }
127263509Sdim  MDNodeToDieMap.insert(std::make_pair(Desc, D));
128263509Sdim}
129263509Sdim
130245431Sdim/// addFlag - Add a flag that is true.
131263509Sdimvoid CompileUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
132263509Sdim  if (DD->getDwarfVersion() >= 4)
133263509Sdim    Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
134245431Sdim  else
135263509Sdim    Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
136245431Sdim}
137245431Sdim
138221337Sdim/// addUInt - Add an unsigned integer attribute data and value.
139221337Sdim///
140263509Sdimvoid CompileUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
141263509Sdim                          Optional<dwarf::Form> Form, uint64_t Integer) {
142263509Sdim  if (!Form)
143263509Sdim    Form = DIEInteger::BestForm(false, Integer);
144263509Sdim  DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
145263509Sdim                        DIEInteger(Integer);
146263509Sdim  Die->addValue(Attribute, *Form, Value);
147221337Sdim}
148221337Sdim
149263509Sdimvoid CompileUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
150263509Sdim  addUInt(Block, (dwarf::Attribute)0, Form, Integer);
151263509Sdim}
152263509Sdim
153221337Sdim/// addSInt - Add an signed integer attribute data and value.
154221337Sdim///
155263509Sdimvoid CompileUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
156263509Sdim                          Optional<dwarf::Form> Form, int64_t Integer) {
157263509Sdim  if (!Form)
158263509Sdim    Form = DIEInteger::BestForm(true, Integer);
159221337Sdim  DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
160263509Sdim  Die->addValue(Attribute, *Form, Value);
161221337Sdim}
162221337Sdim
163263509Sdimvoid CompileUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
164263509Sdim                          int64_t Integer) {
165263509Sdim  addSInt(Die, (dwarf::Attribute)0, Form, Integer);
166263509Sdim}
167263509Sdim
168235633Sdim/// addString - Add a string attribute data and value. We always emit a
169235633Sdim/// reference to the string pool instead of immediate strings so that DIEs have
170252723Sdim/// more predictable sizes. In the case of split dwarf we emit an index
171252723Sdim/// into another table which gets us the static offset into the string
172252723Sdim/// table.
173263509Sdimvoid CompileUnit::addString(DIE *Die, dwarf::Attribute Attribute,
174263509Sdim                            StringRef String) {
175263509Sdim  DIEValue *Value;
176263509Sdim  dwarf::Form Form;
177252723Sdim  if (!DD->useSplitDwarf()) {
178252723Sdim    MCSymbol *Symb = DU->getStringPoolEntry(String);
179252723Sdim    if (Asm->needsRelocationsForDwarfStringPool())
180252723Sdim      Value = new (DIEValueAllocator) DIELabel(Symb);
181252723Sdim    else {
182252723Sdim      MCSymbol *StringPool = DU->getStringPoolSym();
183252723Sdim      Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
184252723Sdim    }
185263509Sdim    Form = dwarf::DW_FORM_strp;
186252723Sdim  } else {
187252723Sdim    unsigned idx = DU->getStringPoolIndex(String);
188263509Sdim    Value = new (DIEValueAllocator) DIEInteger(idx);
189263509Sdim    Form = dwarf::DW_FORM_GNU_str_index;
190252723Sdim  }
191263509Sdim  DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
192263509Sdim  Die->addValue(Attribute, Form, Str);
193252723Sdim}
194252723Sdim
195252723Sdim/// addLocalString - Add a string attribute data and value. This is guaranteed
196252723Sdim/// to be in the local string pool instead of indirected.
197263509Sdimvoid CompileUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
198252723Sdim                                 StringRef String) {
199252723Sdim  MCSymbol *Symb = DU->getStringPoolEntry(String);
200235633Sdim  DIEValue *Value;
201235633Sdim  if (Asm->needsRelocationsForDwarfStringPool())
202235633Sdim    Value = new (DIEValueAllocator) DIELabel(Symb);
203235633Sdim  else {
204252723Sdim    MCSymbol *StringPool = DU->getStringPoolSym();
205235633Sdim    Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
206235633Sdim  }
207235633Sdim  Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
208221337Sdim}
209221337Sdim
210263509Sdim/// addExpr - Add a Dwarf expression attribute data and value.
211263509Sdim///
212263509Sdimvoid CompileUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
213263509Sdim  DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
214263509Sdim  Die->addValue((dwarf::Attribute)0, Form, Value);
215263509Sdim}
216263509Sdim
217221337Sdim/// addLabel - Add a Dwarf label attribute data and value.
218221337Sdim///
219263509Sdimvoid CompileUnit::addLabel(DIE *Die, dwarf::Attribute Attribute,
220263509Sdim                           dwarf::Form Form, const MCSymbol *Label) {
221221337Sdim  DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
222221337Sdim  Die->addValue(Attribute, Form, Value);
223221337Sdim}
224221337Sdim
225263509Sdimvoid CompileUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
226263509Sdim                           const MCSymbol *Label) {
227263509Sdim  addLabel(Die, (dwarf::Attribute)0, Form, Label);
228263509Sdim}
229263509Sdim
230263509Sdim/// addSectionLabel - Add a Dwarf section label attribute data and value.
231263509Sdim///
232263509Sdimvoid CompileUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
233263509Sdim                                  const MCSymbol *Label) {
234263509Sdim  if (DD->getDwarfVersion() >= 4)
235263509Sdim    addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
236263509Sdim  else
237263509Sdim    addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
238263509Sdim}
239263509Sdim
240263509Sdim/// addSectionOffset - Add an offset into a section attribute data and value.
241263509Sdim///
242263509Sdimvoid CompileUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
243263509Sdim                                   uint64_t Integer) {
244263509Sdim  if (DD->getDwarfVersion() >= 4)
245263509Sdim    addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
246263509Sdim  else
247263509Sdim    addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
248263509Sdim}
249263509Sdim
250252723Sdim/// addLabelAddress - Add a dwarf label attribute data and value using
251252723Sdim/// DW_FORM_addr or DW_FORM_GNU_addr_index.
252252723Sdim///
253263509Sdimvoid CompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
254252723Sdim                                  MCSymbol *Label) {
255263509Sdim  if (Label)
256263509Sdim    DD->addArangeLabel(SymbolCU(this, Label));
257263509Sdim
258252723Sdim  if (!DD->useSplitDwarf()) {
259252723Sdim    if (Label != NULL) {
260252723Sdim      DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
261252723Sdim      Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
262252723Sdim    } else {
263252723Sdim      DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
264252723Sdim      Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
265252723Sdim    }
266252723Sdim  } else {
267252723Sdim    unsigned idx = DU->getAddrPoolIndex(Label);
268252723Sdim    DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
269252723Sdim    Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
270252723Sdim  }
271252723Sdim}
272252723Sdim
273252723Sdim/// addOpAddress - Add a dwarf op address data and value using the
274252723Sdim/// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
275252723Sdim///
276263509Sdimvoid CompileUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
277263509Sdim  DD->addArangeLabel(SymbolCU(this, Sym));
278252723Sdim  if (!DD->useSplitDwarf()) {
279263509Sdim    addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
280263509Sdim    addLabel(Die, dwarf::DW_FORM_udata, Sym);
281252723Sdim  } else {
282263509Sdim    addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
283263509Sdim    addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
284252723Sdim  }
285252723Sdim}
286252723Sdim
287263509Sdim/// addSectionDelta - Add a section label delta attribute data and value.
288221337Sdim///
289263509Sdimvoid CompileUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
290263509Sdim                                  const MCSymbol *Hi, const MCSymbol *Lo) {
291221337Sdim  DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
292263509Sdim  if (DD->getDwarfVersion() >= 4)
293263509Sdim    Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
294263509Sdim  else
295263509Sdim    Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
296221337Sdim}
297221337Sdim
298221337Sdim/// addDIEEntry - Add a DIE attribute data and value.
299221337Sdim///
300263509Sdimvoid CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
301221337Sdim                              DIE *Entry) {
302263509Sdim  addDIEEntry(Die, Attribute, createDIEEntry(Entry));
303221337Sdim}
304221337Sdim
305263509Sdimvoid CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
306263509Sdim                              DIEEntry *Entry) {
307263509Sdim  const DIE *DieCU = Die->getCompileUnitOrNull();
308263509Sdim  const DIE *EntryCU = Entry->getEntry()->getCompileUnitOrNull();
309263509Sdim  if (!DieCU)
310263509Sdim    // We assume that Die belongs to this CU, if it is not linked to any CU yet.
311263509Sdim    DieCU = getCUDie();
312263509Sdim  if (!EntryCU)
313263509Sdim    EntryCU = getCUDie();
314263509Sdim  Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
315263509Sdim                                            : dwarf::DW_FORM_ref_addr,
316263509Sdim                Entry);
317263509Sdim}
318263509Sdim
319263509Sdim/// Create a DIE with the given Tag, add the DIE to its parent, and
320263509Sdim/// call insertDIE if MD is not null.
321263509SdimDIE *CompileUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
322263509Sdim  DIE *Die = new DIE(Tag);
323263509Sdim  Parent.addChild(Die);
324263509Sdim  if (N)
325263509Sdim    insertDIE(N, Die);
326263509Sdim  return Die;
327263509Sdim}
328263509Sdim
329221337Sdim/// addBlock - Add block data.
330221337Sdim///
331263509Sdimvoid CompileUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
332221337Sdim                           DIEBlock *Block) {
333221337Sdim  Block->ComputeSize(Asm);
334221337Sdim  DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
335221337Sdim  Die->addValue(Attribute, Block->BestForm(), Block);
336221337Sdim}
337221337Sdim
338221337Sdim/// addSourceLine - Add location information to specified debug information
339221337Sdim/// entry.
340221337Sdimvoid CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
341221337Sdim  // Verify variable.
342263509Sdim  if (!V.isVariable())
343221337Sdim    return;
344252723Sdim
345221337Sdim  unsigned Line = V.getLineNumber();
346221337Sdim  if (Line == 0)
347221337Sdim    return;
348263509Sdim  unsigned FileID =
349263509Sdim      DD->getOrCreateSourceID(V.getContext().getFilename(),
350263509Sdim                              V.getContext().getDirectory(), getUniqueID());
351221337Sdim  assert(FileID && "Invalid file id");
352263509Sdim  addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
353263509Sdim  addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
354221337Sdim}
355221337Sdim
356221337Sdim/// addSourceLine - Add location information to specified debug information
357221337Sdim/// entry.
358221337Sdimvoid CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
359221337Sdim  // Verify global variable.
360263509Sdim  if (!G.isGlobalVariable())
361221337Sdim    return;
362221337Sdim
363221337Sdim  unsigned Line = G.getLineNumber();
364221337Sdim  if (Line == 0)
365221337Sdim    return;
366263509Sdim  unsigned FileID =
367263509Sdim      DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
368221337Sdim  assert(FileID && "Invalid file id");
369263509Sdim  addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
370263509Sdim  addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
371221337Sdim}
372221337Sdim
373221337Sdim/// addSourceLine - Add location information to specified debug information
374221337Sdim/// entry.
375221337Sdimvoid CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
376221337Sdim  // Verify subprogram.
377263509Sdim  if (!SP.isSubprogram())
378221337Sdim    return;
379235633Sdim
380221337Sdim  // If the line number is 0, don't add it.
381235633Sdim  unsigned Line = SP.getLineNumber();
382235633Sdim  if (Line == 0)
383221337Sdim    return;
384221337Sdim
385263509Sdim  unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
386263509Sdim                                            getUniqueID());
387221337Sdim  assert(FileID && "Invalid file id");
388263509Sdim  addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
389263509Sdim  addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
390221337Sdim}
391221337Sdim
392221337Sdim/// addSourceLine - Add location information to specified debug information
393221337Sdim/// entry.
394221337Sdimvoid CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
395221337Sdim  // Verify type.
396263509Sdim  if (!Ty.isType())
397221337Sdim    return;
398221337Sdim
399221337Sdim  unsigned Line = Ty.getLineNumber();
400235633Sdim  if (Line == 0)
401221337Sdim    return;
402263509Sdim  unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
403263509Sdim                                            getUniqueID());
404221337Sdim  assert(FileID && "Invalid file id");
405263509Sdim  addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
406263509Sdim  addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
407221337Sdim}
408221337Sdim
409221337Sdim/// addSourceLine - Add location information to specified debug information
410221337Sdim/// entry.
411235633Sdimvoid CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
412235633Sdim  // Verify type.
413263509Sdim  if (!Ty.isObjCProperty())
414235633Sdim    return;
415235633Sdim
416235633Sdim  unsigned Line = Ty.getLineNumber();
417235633Sdim  if (Line == 0)
418235633Sdim    return;
419235633Sdim  DIFile File = Ty.getFile();
420252723Sdim  unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
421252723Sdim                                            File.getDirectory(), getUniqueID());
422235633Sdim  assert(FileID && "Invalid file id");
423263509Sdim  addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
424263509Sdim  addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
425235633Sdim}
426235633Sdim
427235633Sdim/// addSourceLine - Add location information to specified debug information
428235633Sdim/// entry.
429221337Sdimvoid CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
430221337Sdim  // Verify namespace.
431221337Sdim  if (!NS.Verify())
432221337Sdim    return;
433221337Sdim
434221337Sdim  unsigned Line = NS.getLineNumber();
435221337Sdim  if (Line == 0)
436221337Sdim    return;
437221337Sdim  StringRef FN = NS.getFilename();
438221337Sdim
439263509Sdim  unsigned FileID =
440263509Sdim      DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
441221337Sdim  assert(FileID && "Invalid file id");
442263509Sdim  addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
443263509Sdim  addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
444221337Sdim}
445221337Sdim
446252723Sdim/// addVariableAddress - Add DW_AT_location attribute for a
447221337Sdim/// DbgVariable based on provided MachineLocation.
448263509Sdimvoid CompileUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
449221337Sdim                                     MachineLocation Location) {
450263509Sdim  if (DV.variableHasComplexAddress())
451221337Sdim    addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
452263509Sdim  else if (DV.isBlockByrefVariable())
453221337Sdim    addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
454221337Sdim  else
455263509Sdim    addAddress(Die, dwarf::DW_AT_location, Location,
456263509Sdim               DV.getVariable().isIndirect());
457221337Sdim}
458221337Sdim
459221337Sdim/// addRegisterOp - Add register operand.
460263509Sdimvoid CompileUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
461221337Sdim  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
462221337Sdim  unsigned DWReg = RI->getDwarfRegNum(Reg, false);
463221337Sdim  if (DWReg < 32)
464263509Sdim    addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
465221337Sdim  else {
466263509Sdim    addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
467263509Sdim    addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
468221337Sdim  }
469221337Sdim}
470221337Sdim
471221337Sdim/// addRegisterOffset - Add register offset.
472263509Sdimvoid CompileUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
473221337Sdim                                    int64_t Offset) {
474221337Sdim  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
475221337Sdim  unsigned DWReg = RI->getDwarfRegNum(Reg, false);
476221337Sdim  const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
477221337Sdim  if (Reg == TRI->getFrameRegister(*Asm->MF))
478221337Sdim    // If variable offset is based in frame register then use fbreg.
479263509Sdim    addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
480221337Sdim  else if (DWReg < 32)
481263509Sdim    addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
482221337Sdim  else {
483263509Sdim    addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
484263509Sdim    addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
485221337Sdim  }
486263509Sdim  addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
487221337Sdim}
488221337Sdim
489221337Sdim/// addAddress - Add an address attribute to a die based on the location
490221337Sdim/// provided.
491263509Sdimvoid CompileUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
492263509Sdim                             const MachineLocation &Location, bool Indirect) {
493221337Sdim  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
494221337Sdim
495263509Sdim  if (Location.isReg() && !Indirect)
496221337Sdim    addRegisterOp(Block, Location.getReg());
497263509Sdim  else {
498221337Sdim    addRegisterOffset(Block, Location.getReg(), Location.getOffset());
499263509Sdim    if (Indirect && !Location.isReg()) {
500263509Sdim      addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
501263509Sdim    }
502263509Sdim  }
503221337Sdim
504221337Sdim  // Now attach the location information to the DIE.
505263509Sdim  addBlock(Die, Attribute, Block);
506221337Sdim}
507221337Sdim
508221337Sdim/// addComplexAddress - Start with the address based on the location provided,
509221337Sdim/// and generate the DWARF information necessary to find the actual variable
510221337Sdim/// given the extra address information encoded in the DIVariable, starting from
511221337Sdim/// the starting location.  Add the DWARF information to the die.
512221337Sdim///
513263509Sdimvoid CompileUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
514263509Sdim                                    dwarf::Attribute Attribute,
515221337Sdim                                    const MachineLocation &Location) {
516221337Sdim  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
517263509Sdim  unsigned N = DV.getNumAddrElements();
518221337Sdim  unsigned i = 0;
519221337Sdim  if (Location.isReg()) {
520263509Sdim    if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
521221337Sdim      // If first address element is OpPlus then emit
522221337Sdim      // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
523263509Sdim      addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
524221337Sdim      i = 2;
525221337Sdim    } else
526221337Sdim      addRegisterOp(Block, Location.getReg());
527263509Sdim  } else
528221337Sdim    addRegisterOffset(Block, Location.getReg(), Location.getOffset());
529221337Sdim
530263509Sdim  for (; i < N; ++i) {
531263509Sdim    uint64_t Element = DV.getAddrElement(i);
532221337Sdim    if (Element == DIBuilder::OpPlus) {
533263509Sdim      addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
534263509Sdim      addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
535221337Sdim    } else if (Element == DIBuilder::OpDeref) {
536245431Sdim      if (!Location.isReg())
537263509Sdim        addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
538263509Sdim    } else
539263509Sdim      llvm_unreachable("unknown DIBuilder Opcode");
540221337Sdim  }
541221337Sdim
542221337Sdim  // Now attach the location information to the DIE.
543263509Sdim  addBlock(Die, Attribute, Block);
544221337Sdim}
545221337Sdim
546221337Sdim/* Byref variables, in Blocks, are declared by the programmer as "SomeType
547221337Sdim   VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
548221337Sdim   gives the variable VarName either the struct, or a pointer to the struct, as
549221337Sdim   its type.  This is necessary for various behind-the-scenes things the
550221337Sdim   compiler needs to do with by-reference variables in Blocks.
551221337Sdim
552221337Sdim   However, as far as the original *programmer* is concerned, the variable
553221337Sdim   should still have type 'SomeType', as originally declared.
554221337Sdim
555221337Sdim   The function getBlockByrefType dives into the __Block_byref_x_VarName
556221337Sdim   struct to find the original type of the variable, which is then assigned to
557221337Sdim   the variable's Debug Information Entry as its real type.  So far, so good.
558221337Sdim   However now the debugger will expect the variable VarName to have the type
559221337Sdim   SomeType.  So we need the location attribute for the variable to be an
560221337Sdim   expression that explains to the debugger how to navigate through the
561221337Sdim   pointers and struct to find the actual variable of type SomeType.
562221337Sdim
563221337Sdim   The following function does just that.  We start by getting
564221337Sdim   the "normal" location for the variable. This will be the location
565221337Sdim   of either the struct __Block_byref_x_VarName or the pointer to the
566221337Sdim   struct __Block_byref_x_VarName.
567221337Sdim
568221337Sdim   The struct will look something like:
569221337Sdim
570221337Sdim   struct __Block_byref_x_VarName {
571221337Sdim     ... <various fields>
572221337Sdim     struct __Block_byref_x_VarName *forwarding;
573221337Sdim     ... <various other fields>
574221337Sdim     SomeType VarName;
575221337Sdim     ... <maybe more fields>
576221337Sdim   };
577221337Sdim
578221337Sdim   If we are given the struct directly (as our starting point) we
579221337Sdim   need to tell the debugger to:
580221337Sdim
581221337Sdim   1).  Add the offset of the forwarding field.
582221337Sdim
583221337Sdim   2).  Follow that pointer to get the real __Block_byref_x_VarName
584221337Sdim   struct to use (the real one may have been copied onto the heap).
585221337Sdim
586221337Sdim   3).  Add the offset for the field VarName, to find the actual variable.
587221337Sdim
588221337Sdim   If we started with a pointer to the struct, then we need to
589221337Sdim   dereference that pointer first, before the other steps.
590221337Sdim   Translating this into DWARF ops, we will need to append the following
591221337Sdim   to the current location description for the variable:
592221337Sdim
593221337Sdim   DW_OP_deref                    -- optional, if we start with a pointer
594221337Sdim   DW_OP_plus_uconst <forward_fld_offset>
595221337Sdim   DW_OP_deref
596221337Sdim   DW_OP_plus_uconst <varName_fld_offset>
597221337Sdim
598221337Sdim   That is what this function does.  */
599221337Sdim
600221337Sdim/// addBlockByrefAddress - Start with the address based on the location
601221337Sdim/// provided, and generate the DWARF information necessary to find the
602221337Sdim/// actual Block variable (navigating the Block struct) based on the
603221337Sdim/// starting location.  Add the DWARF information to the die.  For
604221337Sdim/// more information, read large comment just above here.
605221337Sdim///
606263509Sdimvoid CompileUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
607263509Sdim                                       dwarf::Attribute Attribute,
608221337Sdim                                       const MachineLocation &Location) {
609263509Sdim  DIType Ty = DV.getType();
610221337Sdim  DIType TmpTy = Ty;
611263509Sdim  uint16_t Tag = Ty.getTag();
612221337Sdim  bool isPointer = false;
613221337Sdim
614263509Sdim  StringRef varName = DV.getName();
615221337Sdim
616221337Sdim  if (Tag == dwarf::DW_TAG_pointer_type) {
617263509Sdim    DIDerivedType DTy(Ty);
618263509Sdim    TmpTy = resolve(DTy.getTypeDerivedFrom());
619221337Sdim    isPointer = true;
620221337Sdim  }
621221337Sdim
622263509Sdim  DICompositeType blockStruct(TmpTy);
623221337Sdim
624221337Sdim  // Find the __forwarding field and the variable field in the __Block_byref
625221337Sdim  // struct.
626221337Sdim  DIArray Fields = blockStruct.getTypeArray();
627263509Sdim  DIDerivedType varField;
628263509Sdim  DIDerivedType forwardingField;
629221337Sdim
630221337Sdim  for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
631263509Sdim    DIDerivedType DT(Fields.getElement(i));
632221337Sdim    StringRef fieldName = DT.getName();
633221337Sdim    if (fieldName == "__forwarding")
634263509Sdim      forwardingField = DT;
635221337Sdim    else if (fieldName == varName)
636263509Sdim      varField = DT;
637221337Sdim  }
638221337Sdim
639221337Sdim  // Get the offsets for the forwarding field and the variable field.
640263509Sdim  unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
641263509Sdim  unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
642221337Sdim
643221337Sdim  // Decode the original location, and use that as the start of the byref
644221337Sdim  // variable's location.
645221337Sdim  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
646221337Sdim
647245431Sdim  if (Location.isReg())
648245431Sdim    addRegisterOp(Block, Location.getReg());
649245431Sdim  else
650245431Sdim    addRegisterOffset(Block, Location.getReg(), Location.getOffset());
651221337Sdim
652221337Sdim  // If we started with a pointer to the __Block_byref... struct, then
653221337Sdim  // the first thing we need to do is dereference the pointer (DW_OP_deref).
654221337Sdim  if (isPointer)
655263509Sdim    addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
656221337Sdim
657221337Sdim  // Next add the offset for the '__forwarding' field:
658221337Sdim  // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
659221337Sdim  // adding the offset if it's 0.
660221337Sdim  if (forwardingFieldOffset > 0) {
661263509Sdim    addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
662263509Sdim    addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
663221337Sdim  }
664221337Sdim
665221337Sdim  // Now dereference the __forwarding field to get to the real __Block_byref
666221337Sdim  // struct:  DW_OP_deref.
667263509Sdim  addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
668221337Sdim
669221337Sdim  // Now that we've got the real __Block_byref... struct, add the offset
670221337Sdim  // for the variable's field to get to the location of the actual variable:
671221337Sdim  // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
672221337Sdim  if (varFieldOffset > 0) {
673263509Sdim    addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
674263509Sdim    addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
675221337Sdim  }
676221337Sdim
677221337Sdim  // Now attach the location information to the DIE.
678263509Sdim  addBlock(Die, Attribute, Block);
679221337Sdim}
680221337Sdim
681226890Sdim/// isTypeSigned - Return true if the type is signed.
682263509Sdimstatic bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
683226890Sdim  if (Ty.isDerivedType())
684263509Sdim    return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
685263509Sdim                        SizeInBits);
686226890Sdim  if (Ty.isBasicType())
687263509Sdim    if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
688263509Sdim        DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
689226890Sdim      *SizeInBits = Ty.getSizeInBits();
690226890Sdim      return true;
691226890Sdim    }
692226890Sdim  return false;
693226890Sdim}
694226890Sdim
695263509Sdim/// Return true if type encoding is unsigned.
696263509Sdimstatic bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
697263509Sdim  DIDerivedType DTy(Ty);
698263509Sdim  if (DTy.isDerivedType())
699263509Sdim    return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
700263509Sdim
701263509Sdim  DIBasicType BTy(Ty);
702263509Sdim  if (BTy.isBasicType()) {
703263509Sdim    unsigned Encoding = BTy.getEncoding();
704263509Sdim    if (Encoding == dwarf::DW_ATE_unsigned ||
705263509Sdim        Encoding == dwarf::DW_ATE_unsigned_char ||
706263509Sdim        Encoding == dwarf::DW_ATE_boolean)
707263509Sdim      return true;
708263509Sdim  }
709263509Sdim  return false;
710263509Sdim}
711263509Sdim
712263509Sdim/// If this type is derived from a base type then return base type size.
713263509Sdimstatic uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
714263509Sdim  unsigned Tag = Ty.getTag();
715263509Sdim
716263509Sdim  if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
717263509Sdim      Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
718263509Sdim      Tag != dwarf::DW_TAG_restrict_type)
719263509Sdim    return Ty.getSizeInBits();
720263509Sdim
721263509Sdim  DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
722263509Sdim
723263509Sdim  // If this type is not derived from any type then take conservative approach.
724263509Sdim  if (!BaseType.isValid())
725263509Sdim    return Ty.getSizeInBits();
726263509Sdim
727263509Sdim  // If this is a derived type, go ahead and get the base type, unless it's a
728263509Sdim  // reference then it's just the size of the field. Pointer types have no need
729263509Sdim  // of this since they're a different type of qualification on the type.
730263509Sdim  if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
731263509Sdim      BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
732263509Sdim    return Ty.getSizeInBits();
733263509Sdim
734263509Sdim  if (BaseType.isDerivedType())
735263509Sdim    return getBaseTypeSize(DD, DIDerivedType(BaseType));
736263509Sdim
737263509Sdim  return BaseType.getSizeInBits();
738263509Sdim}
739263509Sdim
740221337Sdim/// addConstantValue - Add constant value entry in variable DIE.
741263509Sdimvoid CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
742223017Sdim                                   DIType Ty) {
743263509Sdim  // FIXME: This is a bit conservative/simple - it emits negative values at
744263509Sdim  // their maximum bit width which is a bit unfortunate (& doesn't prefer
745263509Sdim  // udata/sdata over dataN as suggested by the DWARF spec)
746235633Sdim  assert(MO.isImm() && "Invalid machine operand!");
747226890Sdim  int SizeInBits = -1;
748263509Sdim  bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
749263509Sdim  dwarf::Form Form;
750263509Sdim
751263509Sdim  // If we're a signed constant definitely use sdata.
752263509Sdim  if (SignedConstant) {
753263509Sdim    addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
754263509Sdim    return;
755263509Sdim  }
756263509Sdim
757263509Sdim  // Else use data for now unless it's larger than we can deal with.
758226890Sdim  switch (SizeInBits) {
759263509Sdim  case 8:
760263509Sdim    Form = dwarf::DW_FORM_data1;
761263509Sdim    break;
762263509Sdim  case 16:
763263509Sdim    Form = dwarf::DW_FORM_data2;
764263509Sdim    break;
765263509Sdim  case 32:
766263509Sdim    Form = dwarf::DW_FORM_data4;
767263509Sdim    break;
768263509Sdim  case 64:
769263509Sdim    Form = dwarf::DW_FORM_data8;
770263509Sdim    break;
771263509Sdim  default:
772263509Sdim    Form = dwarf::DW_FORM_udata;
773263509Sdim    addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
774263509Sdim    return;
775223017Sdim  }
776263509Sdim  addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
777221337Sdim}
778221337Sdim
779221337Sdim/// addConstantFPValue - Add constant value entry in variable DIE.
780263509Sdimvoid CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
781263509Sdim  assert(MO.isFPImm() && "Invalid machine operand!");
782221337Sdim  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
783221337Sdim  APFloat FPImm = MO.getFPImm()->getValueAPF();
784221337Sdim
785221337Sdim  // Get the raw data form of the floating point.
786221337Sdim  const APInt FltVal = FPImm.bitcastToAPInt();
787263509Sdim  const char *FltPtr = (const char *)FltVal.getRawData();
788221337Sdim
789221337Sdim  int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
790245431Sdim  bool LittleEndian = Asm->getDataLayout().isLittleEndian();
791221337Sdim  int Incr = (LittleEndian ? 1 : -1);
792221337Sdim  int Start = (LittleEndian ? 0 : NumBytes - 1);
793221337Sdim  int Stop = (LittleEndian ? NumBytes : -1);
794221337Sdim
795221337Sdim  // Output the constant to DWARF one byte at a time.
796221337Sdim  for (; Start != Stop; Start += Incr)
797263509Sdim    addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
798221337Sdim
799263509Sdim  addBlock(Die, dwarf::DW_AT_const_value, Block);
800221337Sdim}
801221337Sdim
802252723Sdim/// addConstantFPValue - Add constant value entry in variable DIE.
803263509Sdimvoid CompileUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
804263509Sdim  // Pass this down to addConstantValue as an unsigned bag of bits.
805263509Sdim  addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
806252723Sdim}
807252723Sdim
808221337Sdim/// addConstantValue - Add constant value entry in variable DIE.
809263509Sdimvoid CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
810221337Sdim                                   bool Unsigned) {
811263509Sdim  addConstantValue(Die, CI->getValue(), Unsigned);
812252723Sdim}
813252723Sdim
814252723Sdim// addConstantValue - Add constant value entry in variable DIE.
815263509Sdimvoid CompileUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
816252723Sdim  unsigned CIBitWidth = Val.getBitWidth();
817223017Sdim  if (CIBitWidth <= 64) {
818263509Sdim    // If we're a signed constant definitely use sdata.
819263509Sdim    if (!Unsigned) {
820263509Sdim      addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
821263509Sdim              Val.getSExtValue());
822263509Sdim      return;
823263509Sdim    }
824263509Sdim
825263509Sdim    // Else use data for now unless it's larger than we can deal with.
826263509Sdim    dwarf::Form Form;
827223017Sdim    switch (CIBitWidth) {
828263509Sdim    case 8:
829263509Sdim      Form = dwarf::DW_FORM_data1;
830263509Sdim      break;
831263509Sdim    case 16:
832263509Sdim      Form = dwarf::DW_FORM_data2;
833263509Sdim      break;
834263509Sdim    case 32:
835263509Sdim      Form = dwarf::DW_FORM_data4;
836263509Sdim      break;
837263509Sdim    case 64:
838263509Sdim      Form = dwarf::DW_FORM_data8;
839263509Sdim      break;
840252723Sdim    default:
841263509Sdim      addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
842263509Sdim              Val.getZExtValue());
843263509Sdim      return;
844223017Sdim    }
845263509Sdim    addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
846263509Sdim    return;
847221337Sdim  }
848221337Sdim
849221337Sdim  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
850221337Sdim
851221337Sdim  // Get the raw data form of the large APInt.
852229042Sdim  const uint64_t *Ptr64 = Val.getRawData();
853221337Sdim
854221337Sdim  int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
855245431Sdim  bool LittleEndian = Asm->getDataLayout().isLittleEndian();
856221337Sdim
857221337Sdim  // Output the constant to DWARF one byte at a time.
858229042Sdim  for (int i = 0; i < NumBytes; i++) {
859229042Sdim    uint8_t c;
860229042Sdim    if (LittleEndian)
861229042Sdim      c = Ptr64[i / 8] >> (8 * (i & 7));
862229042Sdim    else
863229042Sdim      c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
864263509Sdim    addUInt(Block, dwarf::DW_FORM_data1, c);
865229042Sdim  }
866221337Sdim
867263509Sdim  addBlock(Die, dwarf::DW_AT_const_value, Block);
868221337Sdim}
869221337Sdim
870252723Sdim/// addTemplateParams - Add template parameters into buffer.
871221337Sdimvoid CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
872221337Sdim  // Add template parameters.
873221337Sdim  for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
874221337Sdim    DIDescriptor Element = TParams.getElement(i);
875221337Sdim    if (Element.isTemplateTypeParameter())
876263509Sdim      constructTemplateTypeParameterDIE(Buffer,
877263509Sdim                                        DITemplateTypeParameter(Element));
878221337Sdim    else if (Element.isTemplateValueParameter())
879263509Sdim      constructTemplateValueParameterDIE(Buffer,
880263509Sdim                                         DITemplateValueParameter(Element));
881221337Sdim  }
882235633Sdim}
883221337Sdim
884252723Sdim/// getOrCreateContextDIE - Get context owner's DIE.
885263509SdimDIE *CompileUnit::getOrCreateContextDIE(DIScope Context) {
886263509Sdim  if (!Context || Context.isFile())
887263509Sdim    return getCUDie();
888252723Sdim  if (Context.isType())
889252723Sdim    return getOrCreateTypeDIE(DIType(Context));
890263509Sdim  if (Context.isNameSpace())
891252723Sdim    return getOrCreateNameSpace(DINameSpace(Context));
892263509Sdim  if (Context.isSubprogram())
893252723Sdim    return getOrCreateSubprogramDIE(DISubprogram(Context));
894263509Sdim  return getDIE(Context);
895252723Sdim}
896252723Sdim
897221337Sdim/// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
898221337Sdim/// given DIType.
899226890SdimDIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
900263509Sdim  if (!TyNode)
901263509Sdim    return NULL;
902263509Sdim
903226890Sdim  DIType Ty(TyNode);
904263509Sdim  assert(Ty.isType());
905263509Sdim
906263509Sdim  // Construct the context before querying for the existence of the DIE in case
907263509Sdim  // such construction creates the DIE.
908263509Sdim  DIE *ContextDIE = getOrCreateContextDIE(resolve(Ty.getContext()));
909263509Sdim  assert(ContextDIE);
910263509Sdim
911221337Sdim  DIE *TyDIE = getDIE(Ty);
912221337Sdim  if (TyDIE)
913221337Sdim    return TyDIE;
914221337Sdim
915221337Sdim  // Create new type.
916263509Sdim  TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
917263509Sdim
918221337Sdim  if (Ty.isBasicType())
919221337Sdim    constructTypeDIE(*TyDIE, DIBasicType(Ty));
920221337Sdim  else if (Ty.isCompositeType())
921221337Sdim    constructTypeDIE(*TyDIE, DICompositeType(Ty));
922221337Sdim  else {
923221337Sdim    assert(Ty.isDerivedType() && "Unknown kind of DIType");
924221337Sdim    constructTypeDIE(*TyDIE, DIDerivedType(Ty));
925221337Sdim  }
926235633Sdim  // If this is a named finished type then include it in the list of types
927235633Sdim  // for the accelerator tables.
928235633Sdim  if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
929235633Sdim    bool IsImplementation = 0;
930235633Sdim    if (Ty.isCompositeType()) {
931235633Sdim      DICompositeType CT(Ty);
932235633Sdim      // A runtime language of 0 actually means C/C++ and that any
933235633Sdim      // non-negative value is some version of Objective-C/C++.
934263509Sdim      IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
935235633Sdim    }
936263509Sdim    unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
937235633Sdim    addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
938235633Sdim  }
939252723Sdim
940221337Sdim  return TyDIE;
941221337Sdim}
942221337Sdim
943221337Sdim/// addType - Add a new type attribute to the specified entity.
944263509Sdimvoid CompileUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
945263509Sdim  assert(Ty && "Trying to add a type that doesn't exist?");
946221337Sdim
947221337Sdim  // Check for pre-existence.
948221337Sdim  DIEEntry *Entry = getDIEEntry(Ty);
949221337Sdim  // If it exists then use the existing value.
950221337Sdim  if (Entry) {
951263509Sdim    addDIEEntry(Entity, Attribute, Entry);
952221337Sdim    return;
953221337Sdim  }
954221337Sdim
955221337Sdim  // Construct type.
956221337Sdim  DIE *Buffer = getOrCreateTypeDIE(Ty);
957221337Sdim
958221337Sdim  // Set up proxy.
959221337Sdim  Entry = createDIEEntry(Buffer);
960221337Sdim  insertDIEEntry(Ty, Entry);
961263509Sdim  addDIEEntry(Entity, Attribute, Entry);
962221337Sdim
963223017Sdim  // If this is a complete composite type then include it in the
964223017Sdim  // list of global types.
965223017Sdim  addGlobalType(Ty);
966221337Sdim}
967221337Sdim
968263509Sdim// Accelerator table mutators - add each name along with its companion
969263509Sdim// DIE to the proper table while ensuring that the name that we're going
970263509Sdim// to reference is in the string table. We do this since the names we
971263509Sdim// add may not only be identical to the names in the DIE.
972263509Sdimvoid CompileUnit::addAccelName(StringRef Name, DIE *Die) {
973263509Sdim  DU->getStringPoolEntry(Name);
974263509Sdim  std::vector<DIE *> &DIEs = AccelNames[Name];
975263509Sdim  DIEs.push_back(Die);
976263509Sdim}
977263509Sdim
978263509Sdimvoid CompileUnit::addAccelObjC(StringRef Name, DIE *Die) {
979263509Sdim  DU->getStringPoolEntry(Name);
980263509Sdim  std::vector<DIE *> &DIEs = AccelObjC[Name];
981263509Sdim  DIEs.push_back(Die);
982263509Sdim}
983263509Sdim
984263509Sdimvoid CompileUnit::addAccelNamespace(StringRef Name, DIE *Die) {
985263509Sdim  DU->getStringPoolEntry(Name);
986263509Sdim  std::vector<DIE *> &DIEs = AccelNamespace[Name];
987263509Sdim  DIEs.push_back(Die);
988263509Sdim}
989263509Sdim
990263509Sdimvoid CompileUnit::addAccelType(StringRef Name, std::pair<DIE *, unsigned> Die) {
991263509Sdim  DU->getStringPoolEntry(Name);
992263509Sdim  std::vector<std::pair<DIE *, unsigned> > &DIEs = AccelTypes[Name];
993263509Sdim  DIEs.push_back(Die);
994263509Sdim}
995263509Sdim
996263509Sdim/// addGlobalName - Add a new global name to the compile unit.
997263509Sdimvoid CompileUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
998263509Sdim  std::string FullName = getParentContextString(Context) + Name.str();
999263509Sdim  GlobalNames[FullName] = Die;
1000263509Sdim}
1001263509Sdim
1002223017Sdim/// addGlobalType - Add a new global type to the compile unit.
1003223017Sdim///
1004223017Sdimvoid CompileUnit::addGlobalType(DIType Ty) {
1005263509Sdim  DIScope Context = resolve(Ty.getContext());
1006263509Sdim  if (!Ty.getName().empty() && !Ty.isForwardDecl() &&
1007263509Sdim      (!Context || Context.isCompileUnit() || Context.isFile() ||
1008263509Sdim       Context.isNameSpace()))
1009263509Sdim    if (DIEEntry *Entry = getDIEEntry(Ty)) {
1010263509Sdim      std::string FullName =
1011263509Sdim          getParentContextString(Context) + Ty.getName().str();
1012263509Sdim      GlobalTypes[FullName] = Entry->getEntry();
1013263509Sdim    }
1014223017Sdim}
1015223017Sdim
1016263509Sdim/// getParentContextString - Walks the metadata parent chain in a language
1017263509Sdim/// specific manner (using the compile unit language) and returns
1018263509Sdim/// it as a string. This is done at the metadata level because DIEs may
1019263509Sdim/// not currently have been added to the parent context and walking the
1020263509Sdim/// DIEs looking for names is more expensive than walking the metadata.
1021263509Sdimstd::string CompileUnit::getParentContextString(DIScope Context) const {
1022263509Sdim  if (!Context)
1023263509Sdim    return "";
1024263509Sdim
1025263509Sdim  // FIXME: Decide whether to implement this for non-C++ languages.
1026263509Sdim  if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1027263509Sdim    return "";
1028263509Sdim
1029263509Sdim  std::string CS;
1030263509Sdim  SmallVector<DIScope, 1> Parents;
1031263509Sdim  while (!Context.isCompileUnit()) {
1032263509Sdim    Parents.push_back(Context);
1033263509Sdim    if (Context.getContext())
1034263509Sdim      Context = resolve(Context.getContext());
1035263509Sdim    else
1036263509Sdim      // Structure, etc types will have a NULL context if they're at the top
1037263509Sdim      // level.
1038263509Sdim      break;
1039263509Sdim  }
1040263509Sdim
1041263509Sdim  // Reverse iterate over our list to go from the outermost construct to the
1042263509Sdim  // innermost.
1043263509Sdim  for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1044263509Sdim                                                  E = Parents.rend();
1045263509Sdim       I != E; ++I) {
1046263509Sdim    DIScope Ctx = *I;
1047263509Sdim    StringRef Name = Ctx.getName();
1048263509Sdim    if (!Name.empty()) {
1049263509Sdim      CS += Name;
1050263509Sdim      CS += "::";
1051263509Sdim    }
1052263509Sdim  }
1053263509Sdim  return CS;
1054263509Sdim}
1055263509Sdim
1056263509Sdim/// addPubTypes - Add subprogram argument types for pubtypes section.
1057223017Sdimvoid CompileUnit::addPubTypes(DISubprogram SP) {
1058223017Sdim  DICompositeType SPTy = SP.getType();
1059263509Sdim  uint16_t SPTag = SPTy.getTag();
1060223017Sdim  if (SPTag != dwarf::DW_TAG_subroutine_type)
1061223017Sdim    return;
1062223017Sdim
1063223017Sdim  DIArray Args = SPTy.getTypeArray();
1064223017Sdim  for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1065223017Sdim    DIType ATy(Args.getElement(i));
1066263509Sdim    if (!ATy.isType())
1067223017Sdim      continue;
1068223017Sdim    addGlobalType(ATy);
1069223017Sdim  }
1070223017Sdim}
1071223017Sdim
1072221337Sdim/// constructTypeDIE - Construct basic type die from DIBasicType.
1073221337Sdimvoid CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1074221337Sdim  // Get core information.
1075221337Sdim  StringRef Name = BTy.getName();
1076226890Sdim  // Add name if not anonymous or intermediate type.
1077226890Sdim  if (!Name.empty())
1078235633Sdim    addString(&Buffer, dwarf::DW_AT_name, Name);
1079226890Sdim
1080263509Sdim  // An unspecified type only has a name attribute.
1081263509Sdim  if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1082226890Sdim    return;
1083226890Sdim
1084235633Sdim  addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1085235633Sdim          BTy.getEncoding());
1086221337Sdim
1087221337Sdim  uint64_t Size = BTy.getSizeInBits() >> 3;
1088263509Sdim  addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1089221337Sdim}
1090221337Sdim
1091221337Sdim/// constructTypeDIE - Construct derived type die from DIDerivedType.
1092221337Sdimvoid CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1093221337Sdim  // Get core information.
1094221337Sdim  StringRef Name = DTy.getName();
1095221337Sdim  uint64_t Size = DTy.getSizeInBits() >> 3;
1096263509Sdim  uint16_t Tag = Buffer.getTag();
1097221337Sdim
1098221337Sdim  // Map to main type, void will not have a type.
1099263509Sdim  DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1100263509Sdim  if (FromTy)
1101263509Sdim    addType(&Buffer, FromTy);
1102221337Sdim
1103221337Sdim  // Add name if not anonymous or intermediate type.
1104221337Sdim  if (!Name.empty())
1105235633Sdim    addString(&Buffer, dwarf::DW_AT_name, Name);
1106221337Sdim
1107221337Sdim  // Add size if non-zero (derived types might be zero-sized.)
1108235633Sdim  if (Size && Tag != dwarf::DW_TAG_pointer_type)
1109263509Sdim    addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1110221337Sdim
1111252723Sdim  if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1112263509Sdim    addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1113263509Sdim                getOrCreateTypeDIE(resolve(DTy.getClassType())));
1114221337Sdim  // Add source line info if available and TyDesc is not a forward declaration.
1115221337Sdim  if (!DTy.isForwardDecl())
1116221337Sdim    addSourceLine(&Buffer, DTy);
1117221337Sdim}
1118221337Sdim
1119263509Sdim/// Return true if the type is appropriately scoped to be contained inside
1120263509Sdim/// its own type unit.
1121263509Sdimstatic bool isTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
1122263509Sdim  DIScope Parent = DD->resolve(Ty.getContext());
1123263509Sdim  while (Parent) {
1124263509Sdim    // Don't generate a hash for anything scoped inside a function.
1125263509Sdim    if (Parent.isSubprogram())
1126263509Sdim      return false;
1127263509Sdim    Parent = DD->resolve(Parent.getContext());
1128263509Sdim  }
1129263509Sdim  return true;
1130263509Sdim}
1131263509Sdim
1132263509Sdim/// Return true if the type should be split out into a type unit.
1133263509Sdimstatic bool shouldCreateTypeUnit(DICompositeType CTy, const DwarfDebug *DD) {
1134263509Sdim  uint16_t Tag = CTy.getTag();
1135263509Sdim
1136263509Sdim  switch (Tag) {
1137263509Sdim  case dwarf::DW_TAG_structure_type:
1138263509Sdim  case dwarf::DW_TAG_union_type:
1139263509Sdim  case dwarf::DW_TAG_enumeration_type:
1140263509Sdim  case dwarf::DW_TAG_class_type:
1141263509Sdim    // If this is a class, structure, union, or enumeration type
1142263509Sdim    // that is a definition (not a declaration), and not scoped
1143263509Sdim    // inside a function then separate this out as a type unit.
1144263509Sdim    return !CTy.isForwardDecl() && isTypeUnitScoped(CTy, DD);
1145263509Sdim  default:
1146263509Sdim    return false;
1147263509Sdim  }
1148263509Sdim}
1149263509Sdim
1150221337Sdim/// constructTypeDIE - Construct type DIE from DICompositeType.
1151221337Sdimvoid CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1152221337Sdim  // Get core information.
1153221337Sdim  StringRef Name = CTy.getName();
1154221337Sdim
1155221337Sdim  uint64_t Size = CTy.getSizeInBits() >> 3;
1156263509Sdim  uint16_t Tag = Buffer.getTag();
1157221337Sdim
1158221337Sdim  switch (Tag) {
1159221337Sdim  case dwarf::DW_TAG_array_type:
1160263509Sdim    constructArrayTypeDIE(Buffer, CTy);
1161221337Sdim    break;
1162263509Sdim  case dwarf::DW_TAG_enumeration_type:
1163263509Sdim    constructEnumTypeDIE(Buffer, CTy);
1164221337Sdim    break;
1165221337Sdim  case dwarf::DW_TAG_subroutine_type: {
1166263509Sdim    // Add return type. A void return won't have a type.
1167221337Sdim    DIArray Elements = CTy.getTypeArray();
1168263509Sdim    DIType RTy(Elements.getElement(0));
1169263509Sdim    if (RTy)
1170263509Sdim      addType(&Buffer, RTy);
1171221337Sdim
1172221337Sdim    bool isPrototyped = true;
1173221337Sdim    // Add arguments.
1174221337Sdim    for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1175221337Sdim      DIDescriptor Ty = Elements.getElement(i);
1176221337Sdim      if (Ty.isUnspecifiedParameter()) {
1177263509Sdim        createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1178221337Sdim        isPrototyped = false;
1179221337Sdim      } else {
1180263509Sdim        DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1181221337Sdim        addType(Arg, DIType(Ty));
1182252723Sdim        if (DIType(Ty).isArtificial())
1183252723Sdim          addFlag(Arg, dwarf::DW_AT_artificial);
1184221337Sdim      }
1185221337Sdim    }
1186235633Sdim    // Add prototype flag if we're dealing with a C language and the
1187235633Sdim    // function has been prototyped.
1188263509Sdim    uint16_t Language = getLanguage();
1189235633Sdim    if (isPrototyped &&
1190263509Sdim        (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1191245431Sdim         Language == dwarf::DW_LANG_ObjC))
1192245431Sdim      addFlag(&Buffer, dwarf::DW_AT_prototyped);
1193263509Sdim  } break;
1194221337Sdim  case dwarf::DW_TAG_structure_type:
1195221337Sdim  case dwarf::DW_TAG_union_type:
1196221337Sdim  case dwarf::DW_TAG_class_type: {
1197221337Sdim    // Add elements to structure type.
1198221337Sdim    DIArray Elements = CTy.getTypeArray();
1199263509Sdim    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1200221337Sdim      DIDescriptor Element = Elements.getElement(i);
1201221337Sdim      DIE *ElemDie = NULL;
1202221337Sdim      if (Element.isSubprogram()) {
1203221337Sdim        DISubprogram SP(Element);
1204263509Sdim        ElemDie = getOrCreateSubprogramDIE(SP);
1205221337Sdim        if (SP.isProtected())
1206235633Sdim          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1207221337Sdim                  dwarf::DW_ACCESS_protected);
1208221337Sdim        else if (SP.isPrivate())
1209235633Sdim          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1210221337Sdim                  dwarf::DW_ACCESS_private);
1211252723Sdim        else
1212235633Sdim          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1213263509Sdim                  dwarf::DW_ACCESS_public);
1214221337Sdim        if (SP.isExplicit())
1215245431Sdim          addFlag(ElemDie, dwarf::DW_AT_explicit);
1216235633Sdim      } else if (Element.isDerivedType()) {
1217245431Sdim        DIDerivedType DDTy(Element);
1218245431Sdim        if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1219263509Sdim          ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1220263509Sdim          addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1221263509Sdim                  dwarf::DW_AT_friend);
1222263509Sdim        } else if (DDTy.isStaticMember()) {
1223263509Sdim          getOrCreateStaticMemberDIE(DDTy);
1224263509Sdim        } else {
1225263509Sdim          constructMemberDIE(Buffer, DDTy);
1226263509Sdim        }
1227235633Sdim      } else if (Element.isObjCProperty()) {
1228235633Sdim        DIObjCProperty Property(Element);
1229263509Sdim        ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1230235633Sdim        StringRef PropertyName = Property.getObjCPropertyName();
1231235633Sdim        addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1232245431Sdim        addType(ElemDie, Property.getType());
1233245431Sdim        addSourceLine(ElemDie, Property);
1234235633Sdim        StringRef GetterName = Property.getObjCPropertyGetterName();
1235235633Sdim        if (!GetterName.empty())
1236235633Sdim          addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1237235633Sdim        StringRef SetterName = Property.getObjCPropertySetterName();
1238235633Sdim        if (!SetterName.empty())
1239235633Sdim          addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1240235633Sdim        unsigned PropertyAttributes = 0;
1241235633Sdim        if (Property.isReadOnlyObjCProperty())
1242235633Sdim          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1243235633Sdim        if (Property.isReadWriteObjCProperty())
1244235633Sdim          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1245235633Sdim        if (Property.isAssignObjCProperty())
1246235633Sdim          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1247235633Sdim        if (Property.isRetainObjCProperty())
1248235633Sdim          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1249235633Sdim        if (Property.isCopyObjCProperty())
1250235633Sdim          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1251235633Sdim        if (Property.isNonAtomicObjCProperty())
1252235633Sdim          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1253235633Sdim        if (PropertyAttributes)
1254263509Sdim          addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1255263509Sdim                  PropertyAttributes);
1256235633Sdim
1257235633Sdim        DIEEntry *Entry = getDIEEntry(Element);
1258235633Sdim        if (!Entry) {
1259235633Sdim          Entry = createDIEEntry(ElemDie);
1260235633Sdim          insertDIEEntry(Element, Entry);
1261235633Sdim        }
1262235633Sdim      } else
1263221337Sdim        continue;
1264221337Sdim    }
1265221337Sdim
1266221337Sdim    if (CTy.isAppleBlockExtension())
1267245431Sdim      addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1268221337Sdim
1269263509Sdim    DICompositeType ContainingType(resolve(CTy.getContainingType()));
1270263509Sdim    if (ContainingType)
1271263509Sdim      addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1272263509Sdim                  getOrCreateTypeDIE(ContainingType));
1273221337Sdim
1274223017Sdim    if (CTy.isObjcClassComplete())
1275245431Sdim      addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1276223017Sdim
1277235633Sdim    // Add template parameters to a class, structure or union types.
1278235633Sdim    // FIXME: The support isn't in the metadata for this yet.
1279235633Sdim    if (Tag == dwarf::DW_TAG_class_type ||
1280263509Sdim        Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1281221337Sdim      addTemplateParams(Buffer, CTy.getTemplateParams());
1282221337Sdim
1283221337Sdim    break;
1284221337Sdim  }
1285221337Sdim  default:
1286221337Sdim    break;
1287221337Sdim  }
1288221337Sdim
1289221337Sdim  // Add name if not anonymous or intermediate type.
1290221337Sdim  if (!Name.empty())
1291235633Sdim    addString(&Buffer, dwarf::DW_AT_name, Name);
1292221337Sdim
1293245431Sdim  if (Tag == dwarf::DW_TAG_enumeration_type ||
1294263509Sdim      Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1295245431Sdim      Tag == dwarf::DW_TAG_union_type) {
1296221337Sdim    // Add size if non-zero (derived types might be zero-sized.)
1297245431Sdim    // TODO: Do we care about size for enum forward declarations?
1298221337Sdim    if (Size)
1299263509Sdim      addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1300245431Sdim    else if (!CTy.isForwardDecl())
1301221337Sdim      // Add zero size if it is not a forward declaration.
1302263509Sdim      addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1303221337Sdim
1304245431Sdim    // If we're a forward decl, say so.
1305245431Sdim    if (CTy.isForwardDecl())
1306245431Sdim      addFlag(&Buffer, dwarf::DW_AT_declaration);
1307245431Sdim
1308221337Sdim    // Add source line info if available.
1309221337Sdim    if (!CTy.isForwardDecl())
1310221337Sdim      addSourceLine(&Buffer, CTy);
1311235633Sdim
1312235633Sdim    // No harm in adding the runtime language to the declaration.
1313235633Sdim    unsigned RLang = CTy.getRunTimeLang();
1314235633Sdim    if (RLang)
1315263509Sdim      addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1316263509Sdim              RLang);
1317221337Sdim  }
1318263509Sdim  // If this is a type applicable to a type unit it then add it to the
1319263509Sdim  // list of types we'll compute a hash for later.
1320263509Sdim  if (shouldCreateTypeUnit(CTy, DD))
1321263509Sdim    DD->addTypeUnitType(&Buffer);
1322221337Sdim}
1323221337Sdim
1324263509Sdim/// constructTemplateTypeParameterDIE - Construct new DIE for the given
1325263509Sdim/// DITemplateTypeParameter.
1326263509Sdimvoid
1327263509SdimCompileUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1328263509Sdim                                               DITemplateTypeParameter TP) {
1329263509Sdim  DIE *ParamDIE =
1330263509Sdim      createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1331263509Sdim  // Add the type if it exists, it could be void and therefore no type.
1332263509Sdim  if (TP.getType())
1333263509Sdim    addType(ParamDIE, resolve(TP.getType()));
1334263509Sdim  if (!TP.getName().empty())
1335263509Sdim    addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1336221337Sdim}
1337221337Sdim
1338263509Sdim/// constructTemplateValueParameterDIE - Construct new DIE for the given
1339263509Sdim/// DITemplateValueParameter.
1340263509Sdimvoid
1341263509SdimCompileUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1342263509Sdim                                                DITemplateValueParameter VP) {
1343263509Sdim  DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1344221337Sdim
1345263509Sdim  // Add the type if there is one, template template and template parameter
1346263509Sdim  // packs will not have a type.
1347263509Sdim  if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1348263509Sdim    addType(ParamDIE, resolve(VP.getType()));
1349263509Sdim  if (!VP.getName().empty())
1350263509Sdim    addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1351263509Sdim  if (Value *Val = VP.getValue()) {
1352263509Sdim    if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1353263509Sdim      addConstantValue(ParamDIE, CI,
1354263509Sdim                       isUnsignedDIType(DD, resolve(VP.getType())));
1355263509Sdim    else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1356263509Sdim      // For declaration non-type template parameters (such as global values and
1357263509Sdim      // functions)
1358263509Sdim      DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1359263509Sdim      addOpAddress(Block, Asm->getSymbol(GV));
1360263509Sdim      // Emit DW_OP_stack_value to use the address as the immediate value of the
1361263509Sdim      // parameter, rather than a pointer to it.
1362263509Sdim      addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1363263509Sdim      addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1364263509Sdim    } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1365263509Sdim      assert(isa<MDString>(Val));
1366263509Sdim      addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1367263509Sdim                cast<MDString>(Val)->getString());
1368263509Sdim    } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1369263509Sdim      assert(isa<MDNode>(Val));
1370263509Sdim      DIArray A(cast<MDNode>(Val));
1371263509Sdim      addTemplateParams(*ParamDIE, A);
1372263509Sdim    }
1373263509Sdim  }
1374221337Sdim}
1375221337Sdim
1376223017Sdim/// getOrCreateNameSpace - Create a DIE for DINameSpace.
1377223017SdimDIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
1378263509Sdim  // Construct the context before querying for the existence of the DIE in case
1379263509Sdim  // such construction creates the DIE.
1380263509Sdim  DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1381263509Sdim
1382223017Sdim  DIE *NDie = getDIE(NS);
1383223017Sdim  if (NDie)
1384223017Sdim    return NDie;
1385263509Sdim  NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1386263509Sdim
1387235633Sdim  if (!NS.getName().empty()) {
1388235633Sdim    addString(NDie, dwarf::DW_AT_name, NS.getName());
1389235633Sdim    addAccelNamespace(NS.getName(), NDie);
1390263509Sdim    addGlobalName(NS.getName(), NDie, NS.getContext());
1391235633Sdim  } else
1392235633Sdim    addAccelNamespace("(anonymous namespace)", NDie);
1393223017Sdim  addSourceLine(NDie, NS);
1394223017Sdim  return NDie;
1395223017Sdim}
1396223017Sdim
1397226890Sdim/// getOrCreateSubprogramDIE - Create new DIE using SP.
1398226890SdimDIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1399263509Sdim  // Construct the context before querying for the existence of the DIE in case
1400263509Sdim  // such construction creates the DIE (as is the case for member function
1401263509Sdim  // declarations).
1402263509Sdim  DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1403263509Sdim
1404226890Sdim  DIE *SPDie = getDIE(SP);
1405226890Sdim  if (SPDie)
1406226890Sdim    return SPDie;
1407226890Sdim
1408263509Sdim  DISubprogram SPDecl = SP.getFunctionDeclaration();
1409263509Sdim  if (SPDecl.isSubprogram())
1410263509Sdim    // Add subprogram definitions to the CU die directly.
1411263509Sdim    ContextDIE = CUDie.get();
1412245431Sdim
1413245431Sdim  // DW_TAG_inlined_subroutine may refer to this DIE.
1414263509Sdim  SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1415245431Sdim
1416235633Sdim  DIE *DeclDie = NULL;
1417263509Sdim  if (SPDecl.isSubprogram())
1418235633Sdim    DeclDie = getOrCreateSubprogramDIE(SPDecl);
1419235633Sdim
1420226890Sdim  // Add function template parameters.
1421226890Sdim  addTemplateParams(*SPDie, SP.getTemplateParams());
1422226890Sdim
1423226890Sdim  // If this DIE is going to refer declaration info using AT_specification
1424226890Sdim  // then there is no need to add other attributes.
1425235633Sdim  if (DeclDie) {
1426235633Sdim    // Refer function declaration directly.
1427263509Sdim    addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1428235633Sdim
1429226890Sdim    return SPDie;
1430235633Sdim  }
1431226890Sdim
1432245431Sdim  // Add the linkage name if we have one.
1433263509Sdim  StringRef LinkageName = SP.getLinkageName();
1434263509Sdim  if (!LinkageName.empty())
1435245431Sdim    addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1436263509Sdim              GlobalValue::getRealLinkageName(LinkageName));
1437245431Sdim
1438226890Sdim  // Constructors and operators for anonymous aggregates do not have names.
1439226890Sdim  if (!SP.getName().empty())
1440235633Sdim    addString(SPDie, dwarf::DW_AT_name, SP.getName());
1441226890Sdim
1442226890Sdim  addSourceLine(SPDie, SP);
1443226890Sdim
1444235633Sdim  // Add the prototype if we have a prototype and we have a C like
1445235633Sdim  // language.
1446263509Sdim  uint16_t Language = getLanguage();
1447235633Sdim  if (SP.isPrototyped() &&
1448263509Sdim      (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1449235633Sdim       Language == dwarf::DW_LANG_ObjC))
1450245431Sdim    addFlag(SPDie, dwarf::DW_AT_prototyped);
1451226890Sdim
1452226890Sdim  DICompositeType SPTy = SP.getType();
1453263509Sdim  assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1454263509Sdim         "the type of a subprogram should be a subroutine");
1455263509Sdim
1456226890Sdim  DIArray Args = SPTy.getTypeArray();
1457263509Sdim  // Add a return type. If this is a type like a C/C++ void type we don't add a
1458263509Sdim  // return type.
1459263509Sdim  if (Args.getElement(0))
1460226890Sdim    addType(SPDie, DIType(Args.getElement(0)));
1461226890Sdim
1462226890Sdim  unsigned VK = SP.getVirtuality();
1463226890Sdim  if (VK) {
1464235633Sdim    addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1465226890Sdim    DIEBlock *Block = getDIEBlock();
1466263509Sdim    addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1467263509Sdim    addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1468263509Sdim    addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1469263509Sdim    ContainingTypeMap.insert(
1470263509Sdim        std::make_pair(SPDie, resolve(SP.getContainingType())));
1471226890Sdim  }
1472226890Sdim
1473226890Sdim  if (!SP.isDefinition()) {
1474245431Sdim    addFlag(SPDie, dwarf::DW_AT_declaration);
1475252723Sdim
1476226890Sdim    // Add arguments. Do not add arguments for subprogram definition. They will
1477226890Sdim    // be handled while processing variables.
1478263509Sdim    for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1479263509Sdim      DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1480263509Sdim      DIType ATy(Args.getElement(i));
1481263509Sdim      addType(Arg, ATy);
1482263509Sdim      if (ATy.isArtificial())
1483263509Sdim        addFlag(Arg, dwarf::DW_AT_artificial);
1484263509Sdim    }
1485226890Sdim  }
1486226890Sdim
1487226890Sdim  if (SP.isArtificial())
1488245431Sdim    addFlag(SPDie, dwarf::DW_AT_artificial);
1489226890Sdim
1490226890Sdim  if (!SP.isLocalToUnit())
1491245431Sdim    addFlag(SPDie, dwarf::DW_AT_external);
1492226890Sdim
1493226890Sdim  if (SP.isOptimized())
1494245431Sdim    addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1495226890Sdim
1496226890Sdim  if (unsigned isa = Asm->getISAEncoding()) {
1497226890Sdim    addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1498226890Sdim  }
1499226890Sdim
1500226890Sdim  return SPDie;
1501226890Sdim}
1502226890Sdim
1503226890Sdim// Return const expression if value is a GEP to access merged global
1504226890Sdim// constant. e.g.
1505226890Sdim// i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1506226890Sdimstatic const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1507226890Sdim  const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1508226890Sdim  if (!CE || CE->getNumOperands() != 3 ||
1509226890Sdim      CE->getOpcode() != Instruction::GetElementPtr)
1510226890Sdim    return NULL;
1511226890Sdim
1512226890Sdim  // First operand points to a global struct.
1513226890Sdim  Value *Ptr = CE->getOperand(0);
1514226890Sdim  if (!isa<GlobalValue>(Ptr) ||
1515226890Sdim      !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1516226890Sdim    return NULL;
1517226890Sdim
1518226890Sdim  // Second operand is zero.
1519226890Sdim  const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1520226890Sdim  if (!CI || !CI->isZero())
1521226890Sdim    return NULL;
1522226890Sdim
1523226890Sdim  // Third operand is offset.
1524226890Sdim  if (!isa<ConstantInt>(CE->getOperand(2)))
1525226890Sdim    return NULL;
1526226890Sdim
1527226890Sdim  return CE;
1528226890Sdim}
1529226890Sdim
1530226890Sdim/// createGlobalVariableDIE - create global variable DIE.
1531263509Sdimvoid CompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1532263509Sdim
1533226890Sdim  // Check for pre-existence.
1534263509Sdim  if (getDIE(GV))
1535226890Sdim    return;
1536226890Sdim
1537263509Sdim  if (!GV.isGlobalVariable())
1538226890Sdim    return;
1539226890Sdim
1540263509Sdim  DIScope GVContext = GV.getContext();
1541226890Sdim  DIType GTy = GV.getType();
1542226890Sdim
1543252723Sdim  // If this is a static data member definition, some attributes belong
1544252723Sdim  // to the declaration DIE.
1545252723Sdim  DIE *VariableDIE = NULL;
1546252723Sdim  bool IsStaticMember = false;
1547252723Sdim  DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1548252723Sdim  if (SDMDecl.Verify()) {
1549252723Sdim    assert(SDMDecl.isStaticMember() && "Expected static member decl");
1550252723Sdim    // We need the declaration DIE that is in the static member's class.
1551263509Sdim    VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1552252723Sdim    IsStaticMember = true;
1553252723Sdim  }
1554235633Sdim
1555252723Sdim  // If this is not a static data member definition, create the variable
1556252723Sdim  // DIE and add the initial set of attributes to it.
1557252723Sdim  if (!VariableDIE) {
1558263509Sdim    // Construct the context before querying for the existence of the DIE in
1559263509Sdim    // case such construction creates the DIE.
1560263509Sdim    DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1561263509Sdim
1562252723Sdim    // Add to map.
1563263509Sdim    VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1564252723Sdim
1565252723Sdim    // Add name and type.
1566252723Sdim    addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1567252723Sdim    addType(VariableDIE, GTy);
1568252723Sdim
1569252723Sdim    // Add scoping info.
1570263509Sdim    if (!GV.isLocalToUnit())
1571252723Sdim      addFlag(VariableDIE, dwarf::DW_AT_external);
1572252723Sdim
1573252723Sdim    // Add line number info.
1574252723Sdim    addSourceLine(VariableDIE, GV);
1575252723Sdim  }
1576252723Sdim
1577226890Sdim  // Add location.
1578235633Sdim  bool addToAccelTable = false;
1579235633Sdim  DIE *VariableSpecDIE = NULL;
1580252723Sdim  bool isGlobalVariable = GV.getGlobal() != NULL;
1581226890Sdim  if (isGlobalVariable) {
1582235633Sdim    addToAccelTable = true;
1583226890Sdim    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1584263509Sdim    const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1585263509Sdim    if (GV.getGlobal()->isThreadLocal()) {
1586263509Sdim      // FIXME: Make this work with -gsplit-dwarf.
1587263509Sdim      unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1588263509Sdim      assert((PointerSize == 4 || PointerSize == 8) &&
1589263509Sdim             "Add support for other sizes if necessary");
1590263509Sdim      const MCExpr *Expr =
1591263509Sdim          Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1592263509Sdim      // Based on GCC's support for TLS:
1593263509Sdim      if (!DD->useSplitDwarf()) {
1594263509Sdim        // 1) Start with a constNu of the appropriate pointer size
1595263509Sdim        addUInt(Block, dwarf::DW_FORM_data1,
1596263509Sdim                PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1597263509Sdim        // 2) containing the (relocated) offset of the TLS variable
1598263509Sdim        //    within the module's TLS block.
1599263509Sdim        addExpr(Block, dwarf::DW_FORM_udata, Expr);
1600263509Sdim      } else {
1601263509Sdim        addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1602263509Sdim        addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1603263509Sdim      }
1604263509Sdim      // 3) followed by a custom OP to make the debugger do a TLS lookup.
1605263509Sdim      addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1606263509Sdim    } else
1607263509Sdim      addOpAddress(Block, Sym);
1608226890Sdim    // Do not create specification DIE if context is either compile unit
1609226890Sdim    // or a subprogram.
1610226890Sdim    if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1611263509Sdim        !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1612226890Sdim      // Create specification DIE.
1613263509Sdim      VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *CUDie);
1614263509Sdim      addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1615263509Sdim      addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1616252723Sdim      // A static member's declaration is already flagged as such.
1617252723Sdim      if (!SDMDecl.Verify())
1618252723Sdim        addFlag(VariableDIE, dwarf::DW_AT_declaration);
1619226890Sdim    } else {
1620263509Sdim      addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1621235633Sdim    }
1622263509Sdim    // Add the linkage name.
1623252723Sdim    StringRef LinkageName = GV.getLinkageName();
1624263509Sdim    if (!LinkageName.empty())
1625252723Sdim      // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1626252723Sdim      // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1627252723Sdim      // TAG_variable.
1628263509Sdim      addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1629263509Sdim                                                  : VariableDIE,
1630263509Sdim                dwarf::DW_AT_MIPS_linkage_name,
1631263509Sdim                GlobalValue::getRealLinkageName(LinkageName));
1632252723Sdim  } else if (const ConstantInt *CI =
1633263509Sdim                 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1634252723Sdim    // AT_const_value was added when the static member was created. To avoid
1635252723Sdim    // emitting AT_const_value multiple times, we only add AT_const_value when
1636252723Sdim    // it is not a static member.
1637252723Sdim    if (!IsStaticMember)
1638263509Sdim      addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1639263509Sdim  } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1640235633Sdim    addToAccelTable = true;
1641226890Sdim    // GV is a merged global.
1642226890Sdim    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1643226890Sdim    Value *Ptr = CE->getOperand(0);
1644263509Sdim    addOpAddress(Block, Asm->getSymbol(cast<GlobalValue>(Ptr)));
1645263509Sdim    addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1646263509Sdim    SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1647263509Sdim    addUInt(Block, dwarf::DW_FORM_udata,
1648263509Sdim            Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1649263509Sdim    addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1650263509Sdim    addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1651226890Sdim  }
1652226890Sdim
1653235633Sdim  if (addToAccelTable) {
1654235633Sdim    DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1655235633Sdim    addAccelName(GV.getName(), AddrDIE);
1656235633Sdim
1657235633Sdim    // If the linkage name is different than the name, go ahead and output
1658235633Sdim    // that as well into the name table.
1659235633Sdim    if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1660235633Sdim      addAccelName(GV.getLinkageName(), AddrDIE);
1661235633Sdim  }
1662235633Sdim
1663263509Sdim  if (!GV.isLocalToUnit())
1664263509Sdim    addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1665263509Sdim                  GV.getContext());
1666226890Sdim}
1667226890Sdim
1668221337Sdim/// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1669245431Sdimvoid CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1670245431Sdim                                       DIE *IndexTy) {
1671263509Sdim  DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1672263509Sdim  addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1673221337Sdim
1674252723Sdim  // The LowerBound value defines the lower bounds which is typically zero for
1675252723Sdim  // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1676252723Sdim  // Count == -1 then the array is unbounded and we do not emit
1677252723Sdim  // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1678252723Sdim  // Count == 0, then the array has zero elements in which case we do not emit
1679252723Sdim  // an upper bound.
1680252723Sdim  int64_t LowerBound = SR.getLo();
1681252723Sdim  int64_t DefaultLowerBound = getDefaultLowerBound();
1682252723Sdim  int64_t Count = SR.getCount();
1683221337Sdim
1684252723Sdim  if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1685263509Sdim    addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1686252723Sdim
1687252723Sdim  if (Count != -1 && Count != 0)
1688252723Sdim    // FIXME: An unbounded array should reference the expression that defines
1689252723Sdim    // the array.
1690263509Sdim    addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1691263509Sdim            LowerBound + Count - 1);
1692221337Sdim}
1693221337Sdim
1694221337Sdim/// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1695263509Sdimvoid CompileUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1696263509Sdim  if (CTy.isVector())
1697245431Sdim    addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1698221337Sdim
1699263509Sdim  // Emit the element type.
1700263509Sdim  addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1701221337Sdim
1702221337Sdim  // Get an anonymous type for index type.
1703252723Sdim  // FIXME: This type should be passed down from the front end
1704252723Sdim  // as different languages may have different sizes for indexes.
1705221337Sdim  DIE *IdxTy = getIndexTyDie();
1706221337Sdim  if (!IdxTy) {
1707221337Sdim    // Construct an anonymous type for index type.
1708263509Sdim    IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *CUDie.get());
1709252723Sdim    addString(IdxTy, dwarf::DW_AT_name, "int");
1710263509Sdim    addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1711221337Sdim    addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1712221337Sdim            dwarf::DW_ATE_signed);
1713221337Sdim    setIndexTyDie(IdxTy);
1714221337Sdim  }
1715221337Sdim
1716221337Sdim  // Add subranges to array type.
1717263509Sdim  DIArray Elements = CTy.getTypeArray();
1718221337Sdim  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1719221337Sdim    DIDescriptor Element = Elements.getElement(i);
1720221337Sdim    if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1721221337Sdim      constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1722221337Sdim  }
1723221337Sdim}
1724221337Sdim
1725263509Sdim/// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1726263509Sdimvoid CompileUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1727263509Sdim  DIArray Elements = CTy.getTypeArray();
1728263509Sdim
1729263509Sdim  // Add enumerators to enumeration type.
1730263509Sdim  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1731263509Sdim    DIEnumerator Enum(Elements.getElement(i));
1732263509Sdim    if (Enum.isEnumerator()) {
1733263509Sdim      DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1734263509Sdim      StringRef Name = Enum.getName();
1735263509Sdim      addString(Enumerator, dwarf::DW_AT_name, Name);
1736263509Sdim      int64_t Value = Enum.getEnumValue();
1737263509Sdim      addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1738263509Sdim    }
1739263509Sdim  }
1740263509Sdim  DIType DTy = resolve(CTy.getTypeDerivedFrom());
1741263509Sdim  if (DTy) {
1742263509Sdim    addType(&Buffer, DTy);
1743263509Sdim    addFlag(&Buffer, dwarf::DW_AT_enum_class);
1744263509Sdim  }
1745221337Sdim}
1746221337Sdim
1747226890Sdim/// constructContainingTypeDIEs - Construct DIEs for types that contain
1748226890Sdim/// vtables.
1749226890Sdimvoid CompileUnit::constructContainingTypeDIEs() {
1750226890Sdim  for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1751263509Sdim                                                 CE = ContainingTypeMap.end();
1752263509Sdim       CI != CE; ++CI) {
1753226890Sdim    DIE *SPDie = CI->first;
1754263509Sdim    DIDescriptor D(CI->second);
1755263509Sdim    if (!D)
1756263509Sdim      continue;
1757263509Sdim    DIE *NDie = getDIE(D);
1758263509Sdim    if (!NDie)
1759263509Sdim      continue;
1760263509Sdim    addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1761226890Sdim  }
1762226890Sdim}
1763226890Sdim
1764226890Sdim/// constructVariableDIE - Construct a DIE for the given DbgVariable.
1765263509SdimDIE *CompileUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1766263509Sdim  StringRef Name = DV.getName();
1767226890Sdim
1768226890Sdim  // Define variable debug information entry.
1769263509Sdim  DIE *VariableDie = new DIE(DV.getTag());
1770263509Sdim  DbgVariable *AbsVar = DV.getAbstractVariable();
1771226890Sdim  DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1772226890Sdim  if (AbsDIE)
1773263509Sdim    addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1774226890Sdim  else {
1775263509Sdim    if (!Name.empty())
1776263509Sdim      addString(VariableDie, dwarf::DW_AT_name, Name);
1777263509Sdim    addSourceLine(VariableDie, DV.getVariable());
1778263509Sdim    addType(VariableDie, DV.getType());
1779226890Sdim  }
1780226890Sdim
1781263509Sdim  if (DV.isArtificial())
1782245431Sdim    addFlag(VariableDie, dwarf::DW_AT_artificial);
1783226890Sdim
1784226890Sdim  if (isScopeAbstract) {
1785263509Sdim    DV.setDIE(VariableDie);
1786226890Sdim    return VariableDie;
1787226890Sdim  }
1788226890Sdim
1789226890Sdim  // Add variable address.
1790226890Sdim
1791263509Sdim  unsigned Offset = DV.getDotDebugLocOffset();
1792226890Sdim  if (Offset != ~0U) {
1793263509Sdim    addSectionLabel(VariableDie, dwarf::DW_AT_location,
1794263509Sdim                    Asm->GetTempSymbol("debug_loc", Offset));
1795263509Sdim    DV.setDIE(VariableDie);
1796226890Sdim    return VariableDie;
1797226890Sdim  }
1798226890Sdim
1799226890Sdim  // Check if variable is described by a DBG_VALUE instruction.
1800263509Sdim  if (const MachineInstr *DVInsn = DV.getMInsn()) {
1801263509Sdim    assert(DVInsn->getNumOperands() == 3);
1802263509Sdim    if (DVInsn->getOperand(0).isReg()) {
1803263509Sdim      const MachineOperand RegOp = DVInsn->getOperand(0);
1804263509Sdim      // If the second operand is an immediate, this is an indirect value.
1805263509Sdim      if (DVInsn->getOperand(1).isImm()) {
1806263509Sdim        MachineLocation Location(RegOp.getReg(),
1807263509Sdim                                 DVInsn->getOperand(1).getImm());
1808263509Sdim        addVariableAddress(DV, VariableDie, Location);
1809263509Sdim      } else if (RegOp.getReg())
1810263509Sdim        addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1811263509Sdim    } else if (DVInsn->getOperand(0).isImm())
1812263509Sdim      addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1813263509Sdim    else if (DVInsn->getOperand(0).isFPImm())
1814263509Sdim      addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1815263509Sdim    else if (DVInsn->getOperand(0).isCImm())
1816263509Sdim      addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1817263509Sdim                       isUnsignedDIType(DD, DV.getType()));
1818252723Sdim
1819263509Sdim    DV.setDIE(VariableDie);
1820226890Sdim    return VariableDie;
1821226890Sdim  } else {
1822226890Sdim    // .. else use frame index.
1823263509Sdim    int FI = DV.getFrameIndex();
1824226890Sdim    if (FI != ~0) {
1825226890Sdim      unsigned FrameReg = 0;
1826226890Sdim      const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1827263509Sdim      int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1828226890Sdim      MachineLocation Location(FrameReg, Offset);
1829226890Sdim      addVariableAddress(DV, VariableDie, Location);
1830226890Sdim    }
1831226890Sdim  }
1832226890Sdim
1833263509Sdim  DV.setDIE(VariableDie);
1834226890Sdim  return VariableDie;
1835226890Sdim}
1836226890Sdim
1837263509Sdim/// constructMemberDIE - Construct member DIE from DIDerivedType.
1838263509Sdimvoid CompileUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1839263509Sdim  DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1840221337Sdim  StringRef Name = DT.getName();
1841221337Sdim  if (!Name.empty())
1842235633Sdim    addString(MemberDie, dwarf::DW_AT_name, Name);
1843221337Sdim
1844263509Sdim  addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1845221337Sdim
1846221337Sdim  addSourceLine(MemberDie, DT);
1847221337Sdim
1848263509Sdim  if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1849221337Sdim
1850263509Sdim    // For C++, virtual base classes are not at fixed offset. Use following
1851263509Sdim    // expression to extract appropriate offset from vtable.
1852263509Sdim    // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1853221337Sdim
1854263509Sdim    DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1855263509Sdim    addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1856263509Sdim    addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1857263509Sdim    addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1858263509Sdim    addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1859263509Sdim    addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1860263509Sdim    addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1861263509Sdim    addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1862221337Sdim
1863263509Sdim    addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1864263509Sdim  } else {
1865263509Sdim    uint64_t Size = DT.getSizeInBits();
1866263509Sdim    uint64_t FieldSize = getBaseTypeSize(DD, DT);
1867263509Sdim    uint64_t OffsetInBytes;
1868221337Sdim
1869263509Sdim    if (Size != FieldSize) {
1870263509Sdim      // Handle bitfield.
1871263509Sdim      addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1872263509Sdim              getBaseTypeSize(DD, DT) >> 3);
1873263509Sdim      addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1874221337Sdim
1875263509Sdim      uint64_t Offset = DT.getOffsetInBits();
1876263509Sdim      uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1877263509Sdim      uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1878263509Sdim      uint64_t FieldOffset = (HiMark - FieldSize);
1879263509Sdim      Offset -= FieldOffset;
1880221337Sdim
1881263509Sdim      // Maybe we need to work from the other end.
1882263509Sdim      if (Asm->getDataLayout().isLittleEndian())
1883263509Sdim        Offset = FieldSize - (Offset + Size);
1884263509Sdim      addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1885221337Sdim
1886263509Sdim      // Here WD_AT_data_member_location points to the anonymous
1887263509Sdim      // field that includes this bit field.
1888263509Sdim      OffsetInBytes = FieldOffset >> 3;
1889263509Sdim    } else
1890263509Sdim      // This is not a bitfield.
1891263509Sdim      OffsetInBytes = DT.getOffsetInBits() >> 3;
1892221337Sdim
1893263509Sdim    if (DD->getDwarfVersion() <= 2) {
1894263509Sdim      DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1895263509Sdim      addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1896263509Sdim      addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1897263509Sdim      addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1898263509Sdim    } else
1899263509Sdim      addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1900263509Sdim              OffsetInBytes);
1901263509Sdim  }
1902221337Sdim
1903221337Sdim  if (DT.isProtected())
1904235633Sdim    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1905221337Sdim            dwarf::DW_ACCESS_protected);
1906221337Sdim  else if (DT.isPrivate())
1907235633Sdim    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1908221337Sdim            dwarf::DW_ACCESS_private);
1909221337Sdim  // Otherwise C++ member and base classes are considered public.
1910252723Sdim  else
1911235633Sdim    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1912221337Sdim            dwarf::DW_ACCESS_public);
1913221337Sdim  if (DT.isVirtual())
1914235633Sdim    addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1915221337Sdim            dwarf::DW_VIRTUALITY_virtual);
1916221337Sdim
1917221337Sdim  // Objective-C properties.
1918235633Sdim  if (MDNode *PNode = DT.getObjCProperty())
1919235633Sdim    if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1920252723Sdim      MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1921235633Sdim                          PropertyDie);
1922235633Sdim
1923252723Sdim  if (DT.isArtificial())
1924252723Sdim    addFlag(MemberDie, dwarf::DW_AT_artificial);
1925221337Sdim}
1926252723Sdim
1927263509Sdim/// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1928263509SdimDIE *CompileUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1929252723Sdim  if (!DT.Verify())
1930252723Sdim    return NULL;
1931252723Sdim
1932263509Sdim  // Construct the context before querying for the existence of the DIE in case
1933263509Sdim  // such construction creates the DIE.
1934263509Sdim  DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1935263509Sdim  assert(dwarf::isType(ContextDIE->getTag()) &&
1936263509Sdim         "Static member should belong to a type.");
1937252723Sdim
1938263509Sdim  DIE *StaticMemberDIE = getDIE(DT);
1939263509Sdim  if (StaticMemberDIE)
1940263509Sdim    return StaticMemberDIE;
1941263509Sdim
1942263509Sdim  StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1943263509Sdim
1944263509Sdim  DIType Ty = resolve(DT.getTypeDerivedFrom());
1945263509Sdim
1946252723Sdim  addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1947252723Sdim  addType(StaticMemberDIE, Ty);
1948252723Sdim  addSourceLine(StaticMemberDIE, DT);
1949252723Sdim  addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1950252723Sdim  addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1951252723Sdim
1952252723Sdim  // FIXME: We could omit private if the parent is a class_type, and
1953252723Sdim  // public if the parent is something else.
1954252723Sdim  if (DT.isProtected())
1955252723Sdim    addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1956252723Sdim            dwarf::DW_ACCESS_protected);
1957252723Sdim  else if (DT.isPrivate())
1958252723Sdim    addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1959252723Sdim            dwarf::DW_ACCESS_private);
1960252723Sdim  else
1961252723Sdim    addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1962252723Sdim            dwarf::DW_ACCESS_public);
1963252723Sdim
1964252723Sdim  if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1965263509Sdim    addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1966252723Sdim  if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1967252723Sdim    addConstantFPValue(StaticMemberDIE, CFP);
1968252723Sdim
1969252723Sdim  return StaticMemberDIE;
1970252723Sdim}
1971263509Sdim
1972263509Sdimvoid CompileUnit::emitHeader(const MCSection *ASection,
1973263509Sdim                             const MCSymbol *ASectionSym) {
1974263509Sdim  Asm->OutStreamer.AddComment("DWARF version number");
1975263509Sdim  Asm->EmitInt16(DD->getDwarfVersion());
1976263509Sdim  Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1977263509Sdim  Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1978263509Sdim                         ASectionSym);
1979263509Sdim  Asm->OutStreamer.AddComment("Address Size (in bytes)");
1980263509Sdim  Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1981263509Sdim}
1982