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