1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for constructing a dwarf compile unit.
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"
39 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
40 cl::desc("Generate DWARF4 type units."),
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);
51 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
52 AsmPrinter *A, DwarfDebug *DW,
54 : DwarfUnit(UID, D, Node, A, DW, DWU) {
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) {
64 addSectionOffset(UnitDie.get(), dwarf::DW_AT_stmt_list, 0);
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();
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);
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()) {
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:
97 case dwarf::DW_LANG_Fortran77:
98 case dwarf::DW_LANG_Fortran90:
99 case dwarf::DW_LANG_Fortran95:
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)
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)
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
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
135 return (D.isType() ||
136 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
137 !GenerateDwarfTypeUnits;
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);
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);
158 MDNodeToDieMap.insert(std::make_pair(Desc, D));
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);
166 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
169 /// addUInt - Add an unsigned integer attribute data and value.
171 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
172 Optional<dwarf::Form> Form, uint64_t Integer) {
174 Form = DIEInteger::BestForm(false, Integer);
175 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
177 Die->addValue(Attribute, *Form, Value);
180 void DwarfUnit::addUInt(DIE *Block, dwarf::Form Form, uint64_t Integer) {
181 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
184 /// addSInt - Add an signed integer attribute data and value.
186 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
187 Optional<dwarf::Form> Form, int64_t Integer) {
189 Form = DIEInteger::BestForm(true, Integer);
190 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
191 Die->addValue(Attribute, *Form, Value);
194 void DwarfUnit::addSInt(DIELoc *Die, Optional<dwarf::Form> Form,
196 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
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
204 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
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);
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,
220 MCSymbol *Symb = DU->getStringPoolEntry(String);
222 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
223 Value = new (DIEValueAllocator) DIELabel(Symb);
225 MCSymbol *StringPool = DU->getStringPoolSym();
226 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
228 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
229 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str);
232 /// addExpr - Add a Dwarf expression attribute data and value.
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);
239 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
241 void DwarfUnit::addLocationList(DIE *Die, dwarf::Attribute Attribute,
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);
249 /// addLabel - Add a Dwarf label attribute data and value.
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);
257 void DwarfUnit::addLabel(DIELoc *Die, dwarf::Form Form, const MCSymbol *Label) {
258 addLabel(Die, (dwarf::Attribute)0, Form, Label);
261 /// addSectionLabel - Add a Dwarf section label attribute data and value.
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);
268 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
271 /// addSectionOffset - Add an offset into a section attribute data and value.
273 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
275 if (DD->getDwarfVersion() >= 4)
276 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
278 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
281 /// addLabelAddress - Add a dwarf label attribute data and value using
282 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
284 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
287 DD->addArangeLabel(SymbolCU(this, Label));
289 if (!DD->useSplitDwarf()) {
291 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
292 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
294 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
295 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
298 unsigned idx = DU->getAddrPoolIndex(Label);
299 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
300 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
304 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
305 // If we print assembly, we can't separate .file entries according to
306 // compile units. Thus all files will belong to the default compile unit.
308 // FIXME: add a better feature test than hasRawTextSupport. Even better,
309 // extend .file to support this.
310 return Asm->OutStreamer.EmitDwarfFileDirective(
311 0, DirName, FileName,
312 Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
315 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
316 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
317 : getCU().getOrCreateSourceID(FileName, DirName);
320 /// addOpAddress - Add a dwarf op address data and value using the
321 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
323 void DwarfUnit::addOpAddress(DIELoc *Die, const MCSymbol *Sym) {
324 if (!DD->useSplitDwarf()) {
325 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
326 addLabel(Die, dwarf::DW_FORM_udata, Sym);
328 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
329 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
333 /// addSectionDelta - Add a section label delta attribute data and value.
335 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
336 const MCSymbol *Hi, const MCSymbol *Lo) {
337 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
338 if (DD->getDwarfVersion() >= 4)
339 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
341 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
344 void DwarfUnit::addLabelDelta(DIE *Die, dwarf::Attribute Attribute,
345 const MCSymbol *Hi, const MCSymbol *Lo) {
346 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
347 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
350 /// addDIEEntry - Add a DIE attribute data and value.
352 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
353 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
356 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
357 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
358 new (DIEValueAllocator) DIETypeSignature(Type));
361 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
363 const DIE *DieCU = Die->getUnitOrNull();
364 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
366 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
367 DieCU = getUnitDie();
369 EntryCU = getUnitDie();
370 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
371 : dwarf::DW_FORM_ref_addr,
375 /// Create a DIE with the given Tag, add the DIE to its parent, and
376 /// call insertDIE if MD is not null.
377 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
378 DIE *Die = new DIE(Tag);
379 Parent.addChild(Die);
385 /// addBlock - Add block data.
387 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute, DIELoc *Loc) {
388 Loc->ComputeSize(Asm);
389 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
390 Die->addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
393 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
395 Block->ComputeSize(Asm);
396 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
397 Die->addValue(Attribute, Block->BestForm(), Block);
400 /// addSourceLine - Add location information to specified debug information
402 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
403 StringRef Directory) {
407 unsigned FileID = getOrCreateSourceID(File, Directory);
408 assert(FileID && "Invalid file id");
409 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
410 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
413 /// addSourceLine - Add location information to specified debug information
415 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
416 assert(V.isVariable());
418 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
419 V.getContext().getDirectory());
422 /// addSourceLine - Add location information to specified debug information
424 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
425 assert(G.isGlobalVariable());
427 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
430 /// addSourceLine - Add location information to specified debug information
432 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
433 assert(SP.isSubprogram());
435 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
438 /// addSourceLine - Add location information to specified debug information
440 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
443 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
446 /// addSourceLine - Add location information to specified debug information
448 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
449 assert(Ty.isObjCProperty());
451 DIFile File = Ty.getFile();
452 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
453 File.getDirectory());
456 /// addSourceLine - Add location information to specified debug information
458 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
461 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
464 /// addVariableAddress - Add DW_AT_location attribute for a
465 /// DbgVariable based on provided MachineLocation.
466 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
467 MachineLocation Location) {
468 if (DV.variableHasComplexAddress())
469 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
470 else if (DV.isBlockByrefVariable())
471 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
473 addAddress(Die, dwarf::DW_AT_location, Location,
474 DV.getVariable().isIndirect());
477 /// addRegisterOp - Add register operand.
478 void DwarfUnit::addRegisterOp(DIELoc *TheDie, unsigned Reg) {
479 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
480 int DWReg = RI->getDwarfRegNum(Reg, false);
481 bool isSubRegister = DWReg < 0;
485 // Go up the super-register chain until we hit a valid dwarf register number.
486 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
487 DWReg = RI->getDwarfRegNum(*SR, false);
489 Idx = RI->getSubRegIndex(*SR, Reg);
493 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
494 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
500 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
502 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
503 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
508 unsigned Size = RI->getSubRegIdxSize(Idx);
509 unsigned Offset = RI->getSubRegIdxOffset(Idx);
511 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
512 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
513 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
515 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
516 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
517 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
522 /// addRegisterOffset - Add register offset.
523 void DwarfUnit::addRegisterOffset(DIELoc *TheDie, unsigned Reg,
525 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
526 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
527 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
528 if (Reg == TRI->getFrameRegister(*Asm->MF))
529 // If variable offset is based in frame register then use fbreg.
530 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
532 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
534 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
535 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
537 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
540 /// addAddress - Add an address attribute to a die based on the location
542 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
543 const MachineLocation &Location, bool Indirect) {
544 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
546 if (Location.isReg() && !Indirect)
547 addRegisterOp(Loc, Location.getReg());
549 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
550 if (Indirect && !Location.isReg()) {
551 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
555 // Now attach the location information to the DIE.
556 addBlock(Die, Attribute, Loc);
559 /// addComplexAddress - Start with the address based on the location provided,
560 /// and generate the DWARF information necessary to find the actual variable
561 /// given the extra address information encoded in the DbgVariable, starting
562 /// from the starting location. Add the DWARF information to the die.
564 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
565 dwarf::Attribute Attribute,
566 const MachineLocation &Location) {
567 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
568 unsigned N = DV.getNumAddrElements();
570 if (Location.isReg()) {
571 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
572 // If first address element is OpPlus then emit
573 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
574 addRegisterOffset(Loc, Location.getReg(), DV.getAddrElement(1));
577 addRegisterOp(Loc, Location.getReg());
579 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
582 uint64_t Element = DV.getAddrElement(i);
583 if (Element == DIBuilder::OpPlus) {
584 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
585 addUInt(Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
586 } else if (Element == DIBuilder::OpDeref) {
587 if (!Location.isReg())
588 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
590 llvm_unreachable("unknown DIBuilder Opcode");
593 // Now attach the location information to the DIE.
594 addBlock(Die, Attribute, Loc);
597 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
598 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
599 gives the variable VarName either the struct, or a pointer to the struct, as
600 its type. This is necessary for various behind-the-scenes things the
601 compiler needs to do with by-reference variables in Blocks.
603 However, as far as the original *programmer* is concerned, the variable
604 should still have type 'SomeType', as originally declared.
606 The function getBlockByrefType dives into the __Block_byref_x_VarName
607 struct to find the original type of the variable, which is then assigned to
608 the variable's Debug Information Entry as its real type. So far, so good.
609 However now the debugger will expect the variable VarName to have the type
610 SomeType. So we need the location attribute for the variable to be an
611 expression that explains to the debugger how to navigate through the
612 pointers and struct to find the actual variable of type SomeType.
614 The following function does just that. We start by getting
615 the "normal" location for the variable. This will be the location
616 of either the struct __Block_byref_x_VarName or the pointer to the
617 struct __Block_byref_x_VarName.
619 The struct will look something like:
621 struct __Block_byref_x_VarName {
623 struct __Block_byref_x_VarName *forwarding;
624 ... <various other fields>
626 ... <maybe more fields>
629 If we are given the struct directly (as our starting point) we
630 need to tell the debugger to:
632 1). Add the offset of the forwarding field.
634 2). Follow that pointer to get the real __Block_byref_x_VarName
635 struct to use (the real one may have been copied onto the heap).
637 3). Add the offset for the field VarName, to find the actual variable.
639 If we started with a pointer to the struct, then we need to
640 dereference that pointer first, before the other steps.
641 Translating this into DWARF ops, we will need to append the following
642 to the current location description for the variable:
644 DW_OP_deref -- optional, if we start with a pointer
645 DW_OP_plus_uconst <forward_fld_offset>
647 DW_OP_plus_uconst <varName_fld_offset>
649 That is what this function does. */
651 /// addBlockByrefAddress - Start with the address based on the location
652 /// provided, and generate the DWARF information necessary to find the
653 /// actual Block variable (navigating the Block struct) based on the
654 /// starting location. Add the DWARF information to the die. For
655 /// more information, read large comment just above here.
657 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
658 dwarf::Attribute Attribute,
659 const MachineLocation &Location) {
660 DIType Ty = DV.getType();
662 uint16_t Tag = Ty.getTag();
663 bool isPointer = false;
665 StringRef varName = DV.getName();
667 if (Tag == dwarf::DW_TAG_pointer_type) {
668 DIDerivedType DTy(Ty);
669 TmpTy = resolve(DTy.getTypeDerivedFrom());
673 DICompositeType blockStruct(TmpTy);
675 // Find the __forwarding field and the variable field in the __Block_byref
677 DIArray Fields = blockStruct.getTypeArray();
678 DIDerivedType varField;
679 DIDerivedType forwardingField;
681 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
682 DIDerivedType DT(Fields.getElement(i));
683 StringRef fieldName = DT.getName();
684 if (fieldName == "__forwarding")
685 forwardingField = DT;
686 else if (fieldName == varName)
690 // Get the offsets for the forwarding field and the variable field.
691 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
692 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
694 // Decode the original location, and use that as the start of the byref
695 // variable's location.
696 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
698 if (Location.isReg())
699 addRegisterOp(Loc, Location.getReg());
701 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
703 // If we started with a pointer to the __Block_byref... struct, then
704 // the first thing we need to do is dereference the pointer (DW_OP_deref).
706 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
708 // Next add the offset for the '__forwarding' field:
709 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
710 // adding the offset if it's 0.
711 if (forwardingFieldOffset > 0) {
712 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
713 addUInt(Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
716 // Now dereference the __forwarding field to get to the real __Block_byref
717 // struct: DW_OP_deref.
718 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
720 // Now that we've got the real __Block_byref... struct, add the offset
721 // for the variable's field to get to the location of the actual variable:
722 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
723 if (varFieldOffset > 0) {
724 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
725 addUInt(Loc, dwarf::DW_FORM_udata, varFieldOffset);
728 // Now attach the location information to the DIE.
729 addBlock(Die, Attribute, Loc);
732 /// isTypeSigned - Return true if the type is signed.
733 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
734 if (Ty.isDerivedType())
735 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
737 if (Ty.isBasicType())
738 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
739 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
740 *SizeInBits = Ty.getSizeInBits();
746 /// Return true if type encoding is unsigned.
747 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
748 DIDerivedType DTy(Ty);
749 if (DTy.isDerivedType())
750 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
753 if (BTy.isBasicType()) {
754 unsigned Encoding = BTy.getEncoding();
755 if (Encoding == dwarf::DW_ATE_unsigned ||
756 Encoding == dwarf::DW_ATE_unsigned_char ||
757 Encoding == dwarf::DW_ATE_boolean)
763 /// If this type is derived from a base type then return base type size.
764 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
765 unsigned Tag = Ty.getTag();
767 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
768 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
769 Tag != dwarf::DW_TAG_restrict_type)
770 return Ty.getSizeInBits();
772 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
774 // If this type is not derived from any type or the type is a declaration then
775 // take conservative approach.
776 if (!BaseType.isValid() || BaseType.isForwardDecl())
777 return Ty.getSizeInBits();
779 // If this is a derived type, go ahead and get the base type, unless it's a
780 // reference then it's just the size of the field. Pointer types have no need
781 // of this since they're a different type of qualification on the type.
782 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
783 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
784 return Ty.getSizeInBits();
786 if (BaseType.isDerivedType())
787 return getBaseTypeSize(DD, DIDerivedType(BaseType));
789 return BaseType.getSizeInBits();
792 /// addConstantValue - Add constant value entry in variable DIE.
793 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
795 // FIXME: This is a bit conservative/simple - it emits negative values at
796 // their maximum bit width which is a bit unfortunate (& doesn't prefer
797 // udata/sdata over dataN as suggested by the DWARF spec)
798 assert(MO.isImm() && "Invalid machine operand!");
800 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
803 // If we're a signed constant definitely use sdata.
804 if (SignedConstant) {
805 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
809 // Else use data for now unless it's larger than we can deal with.
810 switch (SizeInBits) {
812 Form = dwarf::DW_FORM_data1;
815 Form = dwarf::DW_FORM_data2;
818 Form = dwarf::DW_FORM_data4;
821 Form = dwarf::DW_FORM_data8;
824 Form = dwarf::DW_FORM_udata;
825 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
828 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
831 /// addConstantFPValue - Add constant value entry in variable DIE.
832 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
833 assert(MO.isFPImm() && "Invalid machine operand!");
834 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
835 APFloat FPImm = MO.getFPImm()->getValueAPF();
837 // Get the raw data form of the floating point.
838 const APInt FltVal = FPImm.bitcastToAPInt();
839 const char *FltPtr = (const char *)FltVal.getRawData();
841 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
842 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
843 int Incr = (LittleEndian ? 1 : -1);
844 int Start = (LittleEndian ? 0 : NumBytes - 1);
845 int Stop = (LittleEndian ? NumBytes : -1);
847 // Output the constant to DWARF one byte at a time.
848 for (; Start != Stop; Start += Incr)
849 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
851 addBlock(Die, dwarf::DW_AT_const_value, Block);
854 /// addConstantFPValue - Add constant value entry in variable DIE.
855 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
856 // Pass this down to addConstantValue as an unsigned bag of bits.
857 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
860 /// addConstantValue - Add constant value entry in variable DIE.
861 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
863 addConstantValue(Die, CI->getValue(), Unsigned);
866 // addConstantValue - Add constant value entry in variable DIE.
867 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
868 unsigned CIBitWidth = Val.getBitWidth();
869 if (CIBitWidth <= 64) {
870 // If we're a signed constant definitely use sdata.
872 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
877 // Else use data for now unless it's larger than we can deal with.
879 switch (CIBitWidth) {
881 Form = dwarf::DW_FORM_data1;
884 Form = dwarf::DW_FORM_data2;
887 Form = dwarf::DW_FORM_data4;
890 Form = dwarf::DW_FORM_data8;
893 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
897 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
901 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
903 // Get the raw data form of the large APInt.
904 const uint64_t *Ptr64 = Val.getRawData();
906 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
907 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
909 // Output the constant to DWARF one byte at a time.
910 for (int i = 0; i < NumBytes; i++) {
913 c = Ptr64[i / 8] >> (8 * (i & 7));
915 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
916 addUInt(Block, dwarf::DW_FORM_data1, c);
919 addBlock(Die, dwarf::DW_AT_const_value, Block);
922 /// addTemplateParams - Add template parameters into buffer.
923 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
924 // Add template parameters.
925 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
926 DIDescriptor Element = TParams.getElement(i);
927 if (Element.isTemplateTypeParameter())
928 constructTemplateTypeParameterDIE(Buffer,
929 DITemplateTypeParameter(Element));
930 else if (Element.isTemplateValueParameter())
931 constructTemplateValueParameterDIE(Buffer,
932 DITemplateValueParameter(Element));
936 /// getOrCreateContextDIE - Get context owner's DIE.
937 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
938 if (!Context || Context.isFile())
940 if (Context.isType())
941 return getOrCreateTypeDIE(DIType(Context));
942 if (Context.isNameSpace())
943 return getOrCreateNameSpace(DINameSpace(Context));
944 if (Context.isSubprogram())
945 return getOrCreateSubprogramDIE(DISubprogram(Context));
946 return getDIE(Context);
949 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
950 DIScope Context = resolve(Ty.getContext());
951 DIE *ContextDIE = getOrCreateContextDIE(Context);
953 DIE *TyDIE = getDIE(Ty);
958 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
960 constructTypeDIE(*TyDIE, Ty);
962 updateAcceleratorTables(Context, Ty, TyDIE);
966 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
968 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
975 // Construct the context before querying for the existence of the DIE in case
976 // such construction creates the DIE.
977 DIScope Context = resolve(Ty.getContext());
978 DIE *ContextDIE = getOrCreateContextDIE(Context);
981 // Unique the type. This is a noop if the type has no unique identifier.
982 Ty = DIType(resolve(Ty.getRef()));
984 DIE *TyDIE = getDIE(Ty);
989 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
991 updateAcceleratorTables(Context, Ty, TyDIE);
993 if (Ty.isBasicType())
994 constructTypeDIE(*TyDIE, DIBasicType(Ty));
995 else if (Ty.isCompositeType()) {
996 DICompositeType CTy(Ty);
997 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
998 if (MDString *TypeId = CTy.getIdentifier()) {
999 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1000 // Skip updating the accelerator tables since this is not the full type.
1003 constructTypeDIE(*TyDIE, CTy);
1005 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1006 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
1012 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1014 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1015 bool IsImplementation = 0;
1016 if (Ty.isCompositeType()) {
1017 DICompositeType CT(Ty);
1018 // A runtime language of 0 actually means C/C++ and that any
1019 // non-negative value is some version of Objective-C/C++.
1020 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1022 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1023 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1025 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1026 Context.isNameSpace()) &&
1027 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1028 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1032 /// addType - Add a new type attribute to the specified entity.
1033 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1034 assert(Ty && "Trying to add a type that doesn't exist?");
1036 // Check for pre-existence.
1037 DIEEntry *Entry = getDIEEntry(Ty);
1038 // If it exists then use the existing value.
1040 addDIEEntry(Entity, Attribute, Entry);
1045 DIE *Buffer = getOrCreateTypeDIE(Ty);
1048 Entry = createDIEEntry(Buffer);
1049 insertDIEEntry(Ty, Entry);
1050 addDIEEntry(Entity, Attribute, Entry);
1053 // Accelerator table mutators - add each name along with its companion
1054 // DIE to the proper table while ensuring that the name that we're going
1055 // to reference is in the string table. We do this since the names we
1056 // add may not only be identical to the names in the DIE.
1057 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1058 if (!DD->useDwarfAccelTables())
1060 DU->getStringPoolEntry(Name);
1061 std::vector<const DIE *> &DIEs = AccelNames[Name];
1062 DIEs.push_back(Die);
1065 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1066 if (!DD->useDwarfAccelTables())
1068 DU->getStringPoolEntry(Name);
1069 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1070 DIEs.push_back(Die);
1073 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1074 if (!DD->useDwarfAccelTables())
1076 DU->getStringPoolEntry(Name);
1077 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1078 DIEs.push_back(Die);
1081 void DwarfUnit::addAccelType(StringRef Name,
1082 std::pair<const DIE *, unsigned> Die) {
1083 if (!DD->useDwarfAccelTables())
1085 DU->getStringPoolEntry(Name);
1086 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1087 DIEs.push_back(Die);
1090 /// addGlobalName - Add a new global name to the compile unit.
1091 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1092 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1094 std::string FullName = getParentContextString(Context) + Name.str();
1095 GlobalNames[FullName] = Die;
1098 /// getParentContextString - Walks the metadata parent chain in a language
1099 /// specific manner (using the compile unit language) and returns
1100 /// it as a string. This is done at the metadata level because DIEs may
1101 /// not currently have been added to the parent context and walking the
1102 /// DIEs looking for names is more expensive than walking the metadata.
1103 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1107 // FIXME: Decide whether to implement this for non-C++ languages.
1108 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1112 SmallVector<DIScope, 1> Parents;
1113 while (!Context.isCompileUnit()) {
1114 Parents.push_back(Context);
1115 if (Context.getContext())
1116 Context = resolve(Context.getContext());
1118 // Structure, etc types will have a NULL context if they're at the top
1123 // Reverse iterate over our list to go from the outermost construct to the
1125 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1129 StringRef Name = Ctx.getName();
1130 if (!Name.empty()) {
1138 /// constructTypeDIE - Construct basic type die from DIBasicType.
1139 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1140 // Get core information.
1141 StringRef Name = BTy.getName();
1142 // Add name if not anonymous or intermediate type.
1144 addString(&Buffer, dwarf::DW_AT_name, Name);
1146 // An unspecified type only has a name attribute.
1147 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1150 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1153 uint64_t Size = BTy.getSizeInBits() >> 3;
1154 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1157 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1158 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1159 // Get core information.
1160 StringRef Name = DTy.getName();
1161 uint64_t Size = DTy.getSizeInBits() >> 3;
1162 uint16_t Tag = Buffer.getTag();
1164 // Map to main type, void will not have a type.
1165 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1167 addType(&Buffer, FromTy);
1169 // Add name if not anonymous or intermediate type.
1171 addString(&Buffer, dwarf::DW_AT_name, Name);
1173 // Add size if non-zero (derived types might be zero-sized.)
1174 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1175 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1177 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1178 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1179 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1180 // Add source line info if available and TyDesc is not a forward declaration.
1181 if (!DTy.isForwardDecl())
1182 addSourceLine(&Buffer, DTy);
1185 /// constructSubprogramArguments - Construct function argument DIEs.
1186 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DIArray Args) {
1187 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1188 DIDescriptor Ty = Args.getElement(i);
1189 if (Ty.isUnspecifiedParameter()) {
1190 assert(i == N-1 && "Unspecified parameter must be the last argument");
1191 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1193 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1194 addType(Arg, DIType(Ty));
1195 if (DIType(Ty).isArtificial())
1196 addFlag(Arg, dwarf::DW_AT_artificial);
1201 /// constructTypeDIE - Construct type DIE from DICompositeType.
1202 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1203 // Add name if not anonymous or intermediate type.
1204 StringRef Name = CTy.getName();
1206 uint64_t Size = CTy.getSizeInBits() >> 3;
1207 uint16_t Tag = Buffer.getTag();
1210 case dwarf::DW_TAG_array_type:
1211 constructArrayTypeDIE(Buffer, CTy);
1213 case dwarf::DW_TAG_enumeration_type:
1214 constructEnumTypeDIE(Buffer, CTy);
1216 case dwarf::DW_TAG_subroutine_type: {
1217 // Add return type. A void return won't have a type.
1218 DIArray Elements = CTy.getTypeArray();
1219 DIType RTy(Elements.getElement(0));
1221 addType(&Buffer, RTy);
1223 bool isPrototyped = true;
1224 if (Elements.getNumElements() == 2 &&
1225 Elements.getElement(1).isUnspecifiedParameter())
1226 isPrototyped = false;
1228 constructSubprogramArguments(Buffer, Elements);
1230 // Add prototype flag if we're dealing with a C language and the
1231 // function has been prototyped.
1232 uint16_t Language = getLanguage();
1234 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1235 Language == dwarf::DW_LANG_ObjC))
1236 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1238 if (CTy.isLValueReference())
1239 addFlag(&Buffer, dwarf::DW_AT_reference);
1241 if (CTy.isRValueReference())
1242 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1244 case dwarf::DW_TAG_structure_type:
1245 case dwarf::DW_TAG_union_type:
1246 case dwarf::DW_TAG_class_type: {
1247 // Add elements to structure type.
1248 DIArray Elements = CTy.getTypeArray();
1249 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1250 DIDescriptor Element = Elements.getElement(i);
1251 DIE *ElemDie = NULL;
1252 if (Element.isSubprogram())
1253 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1254 else if (Element.isDerivedType()) {
1255 DIDerivedType DDTy(Element);
1256 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1257 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1258 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1259 dwarf::DW_AT_friend);
1260 } else if (DDTy.isStaticMember()) {
1261 getOrCreateStaticMemberDIE(DDTy);
1263 constructMemberDIE(Buffer, DDTy);
1265 } else if (Element.isObjCProperty()) {
1266 DIObjCProperty Property(Element);
1267 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1268 StringRef PropertyName = Property.getObjCPropertyName();
1269 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1270 if (Property.getType())
1271 addType(ElemDie, Property.getType());
1272 addSourceLine(ElemDie, Property);
1273 StringRef GetterName = Property.getObjCPropertyGetterName();
1274 if (!GetterName.empty())
1275 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1276 StringRef SetterName = Property.getObjCPropertySetterName();
1277 if (!SetterName.empty())
1278 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1279 unsigned PropertyAttributes = 0;
1280 if (Property.isReadOnlyObjCProperty())
1281 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1282 if (Property.isReadWriteObjCProperty())
1283 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1284 if (Property.isAssignObjCProperty())
1285 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1286 if (Property.isRetainObjCProperty())
1287 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1288 if (Property.isCopyObjCProperty())
1289 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1290 if (Property.isNonAtomicObjCProperty())
1291 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1292 if (PropertyAttributes)
1293 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1294 PropertyAttributes);
1296 DIEEntry *Entry = getDIEEntry(Element);
1298 Entry = createDIEEntry(ElemDie);
1299 insertDIEEntry(Element, Entry);
1305 if (CTy.isAppleBlockExtension())
1306 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1308 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1310 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1311 getOrCreateTypeDIE(ContainingType));
1313 if (CTy.isObjcClassComplete())
1314 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1316 // Add template parameters to a class, structure or union types.
1317 // FIXME: The support isn't in the metadata for this yet.
1318 if (Tag == dwarf::DW_TAG_class_type ||
1319 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1320 addTemplateParams(Buffer, CTy.getTemplateParams());
1328 // Add name if not anonymous or intermediate type.
1330 addString(&Buffer, dwarf::DW_AT_name, Name);
1332 if (Tag == dwarf::DW_TAG_enumeration_type ||
1333 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1334 Tag == dwarf::DW_TAG_union_type) {
1335 // Add size if non-zero (derived types might be zero-sized.)
1336 // TODO: Do we care about size for enum forward declarations?
1338 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1339 else if (!CTy.isForwardDecl())
1340 // Add zero size if it is not a forward declaration.
1341 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1343 // If we're a forward decl, say so.
1344 if (CTy.isForwardDecl())
1345 addFlag(&Buffer, dwarf::DW_AT_declaration);
1347 // Add source line info if available.
1348 if (!CTy.isForwardDecl())
1349 addSourceLine(&Buffer, CTy);
1351 // No harm in adding the runtime language to the declaration.
1352 unsigned RLang = CTy.getRunTimeLang();
1354 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1359 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1360 /// DITemplateTypeParameter.
1361 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1362 DITemplateTypeParameter TP) {
1364 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1365 // Add the type if it exists, it could be void and therefore no type.
1367 addType(ParamDIE, resolve(TP.getType()));
1368 if (!TP.getName().empty())
1369 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1372 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1373 /// DITemplateValueParameter.
1375 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1376 DITemplateValueParameter VP) {
1377 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1379 // Add the type if there is one, template template and template parameter
1380 // packs will not have a type.
1381 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1382 addType(ParamDIE, resolve(VP.getType()));
1383 if (!VP.getName().empty())
1384 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1385 if (Value *Val = VP.getValue()) {
1386 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1387 addConstantValue(ParamDIE, CI,
1388 isUnsignedDIType(DD, resolve(VP.getType())));
1389 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1390 // For declaration non-type template parameters (such as global values and
1392 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1393 addOpAddress(Loc, Asm->getSymbol(GV));
1394 // Emit DW_OP_stack_value to use the address as the immediate value of the
1395 // parameter, rather than a pointer to it.
1396 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1397 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1398 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1399 assert(isa<MDString>(Val));
1400 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1401 cast<MDString>(Val)->getString());
1402 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1403 assert(isa<MDNode>(Val));
1404 DIArray A(cast<MDNode>(Val));
1405 addTemplateParams(*ParamDIE, A);
1410 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1411 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1412 // Construct the context before querying for the existence of the DIE in case
1413 // such construction creates the DIE.
1414 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1416 DIE *NDie = getDIE(NS);
1419 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1421 if (!NS.getName().empty()) {
1422 addString(NDie, dwarf::DW_AT_name, NS.getName());
1423 addAccelNamespace(NS.getName(), NDie);
1424 addGlobalName(NS.getName(), NDie, NS.getContext());
1426 addAccelNamespace("(anonymous namespace)", NDie);
1427 addSourceLine(NDie, NS);
1431 /// Unique C++ member function declarations based on their
1432 /// context and mangled name.
1434 DwarfUnit::getOdrUniqueSubprogram(DIScope Context, DISubprogram SP) const {
1436 !Context.isCompositeType() ||
1437 SP.getLinkageName().empty() ||
1440 // Create a key with the UID of the parent class and this SP's name.
1441 Twine Key = SP.getContext().getName() + SP.getLinkageName();
1442 const MDNode *&Entry = DD->getOrCreateOdrMember(Key.str());
1446 return DISubprogram(Entry);
1449 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1450 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1451 // Construct the context before querying for the existence of the DIE in case
1452 // such construction creates the DIE (as is the case for member function
1454 DIScope Context = resolve(SP.getContext());
1455 DIE *ContextDIE = getOrCreateContextDIE(Context);
1456 // Unique declarations based on the ODR, where applicable.
1457 SP = getOdrUniqueSubprogram(Context, SP);
1459 DIE *SPDie = getDIE(SP);
1463 DISubprogram SPDecl = SP.getFunctionDeclaration();
1464 if (SPDecl.isSubprogram())
1465 // Add subprogram definitions to the CU die directly.
1466 ContextDIE = UnitDie.get();
1468 // DW_TAG_inlined_subroutine may refer to this DIE.
1469 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1471 DIE *DeclDie = NULL;
1472 if (SPDecl.isSubprogram())
1473 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1475 // Add function template parameters.
1476 addTemplateParams(*SPDie, SP.getTemplateParams());
1478 // If this DIE is going to refer declaration info using AT_specification
1479 // then there is no need to add other attributes.
1481 // Refer function declaration directly.
1482 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1487 // Add the linkage name if we have one.
1488 StringRef LinkageName = SP.getLinkageName();
1489 if (!LinkageName.empty())
1490 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1491 GlobalValue::getRealLinkageName(LinkageName));
1493 // Constructors and operators for anonymous aggregates do not have names.
1494 if (!SP.getName().empty())
1495 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1497 addSourceLine(SPDie, SP);
1499 // Add the prototype if we have a prototype and we have a C like
1501 uint16_t Language = getLanguage();
1502 if (SP.isPrototyped() &&
1503 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1504 Language == dwarf::DW_LANG_ObjC))
1505 addFlag(SPDie, dwarf::DW_AT_prototyped);
1507 DICompositeType SPTy = SP.getType();
1508 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1509 "the type of a subprogram should be a subroutine");
1511 DIArray Args = SPTy.getTypeArray();
1512 // Add a return type. If this is a type like a C/C++ void type we don't add a
1514 if (Args.getElement(0))
1515 addType(SPDie, DIType(Args.getElement(0)));
1517 unsigned VK = SP.getVirtuality();
1519 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1520 DIELoc *Block = getDIELoc();
1521 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1522 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1523 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1524 ContainingTypeMap.insert(
1525 std::make_pair(SPDie, resolve(SP.getContainingType())));
1528 if (!SP.isDefinition()) {
1529 addFlag(SPDie, dwarf::DW_AT_declaration);
1531 // Add arguments. Do not add arguments for subprogram definition. They will
1532 // be handled while processing variables.
1533 constructSubprogramArguments(*SPDie, Args);
1536 if (SP.isArtificial())
1537 addFlag(SPDie, dwarf::DW_AT_artificial);
1539 if (!SP.isLocalToUnit())
1540 addFlag(SPDie, dwarf::DW_AT_external);
1542 if (SP.isOptimized())
1543 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1545 if (unsigned isa = Asm->getISAEncoding()) {
1546 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1549 if (SP.isLValueReference())
1550 addFlag(SPDie, dwarf::DW_AT_reference);
1552 if (SP.isRValueReference())
1553 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1555 if (SP.isProtected())
1556 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1557 dwarf::DW_ACCESS_protected);
1558 else if (SP.isPrivate())
1559 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1560 dwarf::DW_ACCESS_private);
1562 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1563 dwarf::DW_ACCESS_public);
1565 if (SP.isExplicit())
1566 addFlag(SPDie, dwarf::DW_AT_explicit);
1571 // Return const expression if value is a GEP to access merged global
1573 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1574 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1575 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1576 if (!CE || CE->getNumOperands() != 3 ||
1577 CE->getOpcode() != Instruction::GetElementPtr)
1580 // First operand points to a global struct.
1581 Value *Ptr = CE->getOperand(0);
1582 if (!isa<GlobalValue>(Ptr) ||
1583 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1586 // Second operand is zero.
1587 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1588 if (!CI || !CI->isZero())
1591 // Third operand is offset.
1592 if (!isa<ConstantInt>(CE->getOperand(2)))
1598 /// createGlobalVariableDIE - create global variable DIE.
1599 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1600 // Check for pre-existence.
1604 assert(GV.isGlobalVariable());
1606 DIScope GVContext = GV.getContext();
1607 DIType GTy = GV.getType();
1609 // If this is a static data member definition, some attributes belong
1610 // to the declaration DIE.
1611 DIE *VariableDIE = NULL;
1612 bool IsStaticMember = false;
1613 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1614 if (SDMDecl.Verify()) {
1615 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1616 // We need the declaration DIE that is in the static member's class.
1617 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1618 IsStaticMember = true;
1621 // If this is not a static data member definition, create the variable
1622 // DIE and add the initial set of attributes to it.
1624 // Construct the context before querying for the existence of the DIE in
1625 // case such construction creates the DIE.
1626 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1629 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1631 // Add name and type.
1632 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1633 addType(VariableDIE, GTy);
1635 // Add scoping info.
1636 if (!GV.isLocalToUnit())
1637 addFlag(VariableDIE, dwarf::DW_AT_external);
1639 // Add line number info.
1640 addSourceLine(VariableDIE, GV);
1644 bool addToAccelTable = false;
1645 DIE *VariableSpecDIE = NULL;
1646 bool isGlobalVariable = GV.getGlobal() != NULL;
1647 if (isGlobalVariable) {
1648 addToAccelTable = true;
1649 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1650 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1651 if (GV.getGlobal()->isThreadLocal()) {
1652 // FIXME: Make this work with -gsplit-dwarf.
1653 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1654 assert((PointerSize == 4 || PointerSize == 8) &&
1655 "Add support for other sizes if necessary");
1656 // Based on GCC's support for TLS:
1657 if (!DD->useSplitDwarf()) {
1658 // 1) Start with a constNu of the appropriate pointer size
1659 addUInt(Loc, dwarf::DW_FORM_data1,
1660 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1661 // 2) containing the (relocated) offset of the TLS variable
1662 // within the module's TLS block.
1663 addExpr(Loc, dwarf::DW_FORM_udata,
1664 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1666 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1667 addUInt(Loc, dwarf::DW_FORM_udata,
1668 DU->getAddrPoolIndex(Sym, /* TLS */ true));
1670 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1671 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1673 DD->addArangeLabel(SymbolCU(this, Sym));
1674 addOpAddress(Loc, Sym);
1676 // Do not create specification DIE if context is either compile unit
1678 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1679 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1680 // Create specification DIE.
1681 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1682 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1683 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Loc);
1684 // A static member's declaration is already flagged as such.
1685 if (!SDMDecl.Verify())
1686 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1688 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1690 // Add the linkage name.
1691 StringRef LinkageName = GV.getLinkageName();
1692 if (!LinkageName.empty())
1693 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1694 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1696 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1698 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1699 : dwarf::DW_AT_MIPS_linkage_name,
1700 GlobalValue::getRealLinkageName(LinkageName));
1701 } else if (const ConstantInt *CI =
1702 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1703 // AT_const_value was added when the static member was created. To avoid
1704 // emitting AT_const_value multiple times, we only add AT_const_value when
1705 // it is not a static member.
1706 if (!IsStaticMember)
1707 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1708 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1709 addToAccelTable = true;
1710 // GV is a merged global.
1711 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1712 Value *Ptr = CE->getOperand(0);
1713 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1714 DD->addArangeLabel(SymbolCU(this, Sym));
1715 addOpAddress(Loc, Sym);
1716 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1717 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1718 addUInt(Loc, dwarf::DW_FORM_udata,
1719 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1720 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1721 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1724 if (addToAccelTable) {
1725 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1726 addAccelName(GV.getName(), AddrDIE);
1728 // If the linkage name is different than the name, go ahead and output
1729 // that as well into the name table.
1730 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1731 addAccelName(GV.getLinkageName(), AddrDIE);
1734 if (!GV.isLocalToUnit())
1735 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1739 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1740 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1741 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1742 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1744 // The LowerBound value defines the lower bounds which is typically zero for
1745 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1746 // Count == -1 then the array is unbounded and we do not emit
1747 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1748 // Count == 0, then the array has zero elements in which case we do not emit
1750 int64_t LowerBound = SR.getLo();
1751 int64_t DefaultLowerBound = getDefaultLowerBound();
1752 int64_t Count = SR.getCount();
1754 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1755 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1757 if (Count != -1 && Count != 0)
1758 // FIXME: An unbounded array should reference the expression that defines
1760 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1761 LowerBound + Count - 1);
1764 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1765 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1767 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1769 // Emit the element type.
1770 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1772 // Get an anonymous type for index type.
1773 // FIXME: This type should be passed down from the front end
1774 // as different languages may have different sizes for indexes.
1775 DIE *IdxTy = getIndexTyDie();
1777 // Construct an anonymous type for index type.
1778 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1779 addString(IdxTy, dwarf::DW_AT_name, "int");
1780 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1781 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1782 dwarf::DW_ATE_signed);
1783 setIndexTyDie(IdxTy);
1786 // Add subranges to array type.
1787 DIArray Elements = CTy.getTypeArray();
1788 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1789 DIDescriptor Element = Elements.getElement(i);
1790 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1791 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1795 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1796 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1797 DIArray Elements = CTy.getTypeArray();
1799 // Add enumerators to enumeration type.
1800 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1801 DIEnumerator Enum(Elements.getElement(i));
1802 if (Enum.isEnumerator()) {
1803 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1804 StringRef Name = Enum.getName();
1805 addString(Enumerator, dwarf::DW_AT_name, Name);
1806 int64_t Value = Enum.getEnumValue();
1807 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1811 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1813 addType(&Buffer, DTy);
1814 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1818 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1820 void DwarfUnit::constructContainingTypeDIEs() {
1821 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1822 CE = ContainingTypeMap.end();
1824 DIE *SPDie = CI->first;
1825 DIDescriptor D(CI->second);
1828 DIE *NDie = getDIE(D);
1831 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1835 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1836 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1837 StringRef Name = DV.getName();
1839 // Define variable debug information entry.
1840 DIE *VariableDie = new DIE(DV.getTag());
1841 DbgVariable *AbsVar = DV.getAbstractVariable();
1842 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1844 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1847 addString(VariableDie, dwarf::DW_AT_name, Name);
1848 addSourceLine(VariableDie, DV.getVariable());
1849 addType(VariableDie, DV.getType());
1852 if (DV.isArtificial())
1853 addFlag(VariableDie, dwarf::DW_AT_artificial);
1855 if (isScopeAbstract) {
1856 DV.setDIE(VariableDie);
1860 // Add variable address.
1862 unsigned Offset = DV.getDotDebugLocOffset();
1863 if (Offset != ~0U) {
1864 addLocationList(VariableDie, dwarf::DW_AT_location, Offset);
1865 DV.setDIE(VariableDie);
1869 // Check if variable is described by a DBG_VALUE instruction.
1870 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1871 assert(DVInsn->getNumOperands() == 3);
1872 if (DVInsn->getOperand(0).isReg()) {
1873 const MachineOperand RegOp = DVInsn->getOperand(0);
1874 // If the second operand is an immediate, this is an indirect value.
1875 if (DVInsn->getOperand(1).isImm()) {
1876 MachineLocation Location(RegOp.getReg(),
1877 DVInsn->getOperand(1).getImm());
1878 addVariableAddress(DV, VariableDie, Location);
1879 } else if (RegOp.getReg())
1880 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1881 } else if (DVInsn->getOperand(0).isImm())
1882 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1883 else if (DVInsn->getOperand(0).isFPImm())
1884 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1885 else if (DVInsn->getOperand(0).isCImm())
1886 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1887 isUnsignedDIType(DD, DV.getType()));
1889 DV.setDIE(VariableDie);
1892 // .. else use frame index.
1893 int FI = DV.getFrameIndex();
1895 unsigned FrameReg = 0;
1896 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1897 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1898 MachineLocation Location(FrameReg, Offset);
1899 addVariableAddress(DV, VariableDie, Location);
1903 DV.setDIE(VariableDie);
1907 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1908 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1909 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1910 StringRef Name = DT.getName();
1912 addString(MemberDie, dwarf::DW_AT_name, Name);
1914 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1916 addSourceLine(MemberDie, DT);
1918 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1920 // For C++, virtual base classes are not at fixed offset. Use following
1921 // expression to extract appropriate offset from vtable.
1922 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1924 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1925 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1926 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1927 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1928 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1929 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1930 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1931 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1933 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1935 uint64_t Size = DT.getSizeInBits();
1936 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1937 uint64_t OffsetInBytes;
1939 if (Size != FieldSize) {
1940 // Handle bitfield, assume bytes are 8 bits.
1941 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1942 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1944 uint64_t Offset = DT.getOffsetInBits();
1945 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1946 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1947 uint64_t FieldOffset = (HiMark - FieldSize);
1948 Offset -= FieldOffset;
1950 // Maybe we need to work from the other end.
1951 if (Asm->getDataLayout().isLittleEndian())
1952 Offset = FieldSize - (Offset + Size);
1953 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1955 // Here DW_AT_data_member_location points to the anonymous
1956 // field that includes this bit field.
1957 OffsetInBytes = FieldOffset >> 3;
1959 // This is not a bitfield.
1960 OffsetInBytes = DT.getOffsetInBits() >> 3;
1962 if (DD->getDwarfVersion() <= 2) {
1963 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1964 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1965 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1966 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1968 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1972 if (DT.isProtected())
1973 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1974 dwarf::DW_ACCESS_protected);
1975 else if (DT.isPrivate())
1976 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1977 dwarf::DW_ACCESS_private);
1978 // Otherwise C++ member and base classes are considered public.
1980 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1981 dwarf::DW_ACCESS_public);
1983 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1984 dwarf::DW_VIRTUALITY_virtual);
1986 // Objective-C properties.
1987 if (MDNode *PNode = DT.getObjCProperty())
1988 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1989 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1992 if (DT.isArtificial())
1993 addFlag(MemberDie, dwarf::DW_AT_artificial);
1996 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1997 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
2001 // Construct the context before querying for the existence of the DIE in case
2002 // such construction creates the DIE.
2003 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
2004 assert(dwarf::isType(ContextDIE->getTag()) &&
2005 "Static member should belong to a type.");
2007 DIE *StaticMemberDIE = getDIE(DT);
2008 if (StaticMemberDIE)
2009 return StaticMemberDIE;
2011 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
2013 DIType Ty = resolve(DT.getTypeDerivedFrom());
2015 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
2016 addType(StaticMemberDIE, Ty);
2017 addSourceLine(StaticMemberDIE, DT);
2018 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2019 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2021 // FIXME: We could omit private if the parent is a class_type, and
2022 // public if the parent is something else.
2023 if (DT.isProtected())
2024 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2025 dwarf::DW_ACCESS_protected);
2026 else if (DT.isPrivate())
2027 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2028 dwarf::DW_ACCESS_private);
2030 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2031 dwarf::DW_ACCESS_public);
2033 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2034 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
2035 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2036 addConstantFPValue(StaticMemberDIE, CFP);
2038 return StaticMemberDIE;
2041 void DwarfUnit::emitHeader(const MCSection *ASection,
2042 const MCSymbol *ASectionSym) const {
2043 Asm->OutStreamer.AddComment("DWARF version number");
2044 Asm->EmitInt16(DD->getDwarfVersion());
2045 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2046 // We share one abbreviations table across all units so it's always at the
2047 // start of the section. Use a relocatable offset where needed to ensure
2048 // linking doesn't invalidate that offset.
2049 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2050 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2051 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2054 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2055 // Define start line table label for each Compile Unit.
2056 MCSymbol *LineTableStartSym =
2057 Asm->GetTempSymbol("line_table_start", getUniqueID());
2058 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
2061 // Use a single line table if we are generating assembly.
2062 bool UseTheFirstCU =
2063 Asm->OutStreamer.hasRawTextSupport() || (getUniqueID() == 0);
2065 stmtListIndex = UnitDie->getValues().size();
2067 // DW_AT_stmt_list is a offset of line number information for this
2068 // compile unit in debug_line section. For split dwarf this is
2069 // left in the skeleton CU and so not included.
2070 // The line table entries are not always emitted in assembly, so it
2071 // is not okay to use line_table_start here.
2072 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2073 addSectionLabel(UnitDie.get(), dwarf::DW_AT_stmt_list,
2074 UseTheFirstCU ? DwarfLineSectionSym : LineTableStartSym);
2075 else if (UseTheFirstCU)
2076 addSectionOffset(UnitDie.get(), dwarf::DW_AT_stmt_list, 0);
2078 addSectionDelta(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym,
2079 DwarfLineSectionSym);
2082 void DwarfCompileUnit::applyStmtList(DIE &D) {
2083 D.addValue(dwarf::DW_AT_stmt_list,
2084 UnitDie->getAbbrev().getData()[stmtListIndex].getForm(),
2085 UnitDie->getValues()[stmtListIndex]);
2088 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2089 const MCSymbol *ASectionSym) const {
2090 DwarfUnit::emitHeader(ASection, ASectionSym);
2091 Asm->OutStreamer.AddComment("Type Signature");
2092 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2093 Asm->OutStreamer.AddComment("Type DIE Offset");
2094 // In a skeleton type unit there is no type DIE so emit a zero offset.
2095 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2096 sizeof(Ty->getOffset()));
2099 void DwarfTypeUnit::initSection(const MCSection *Section) {
2100 assert(!this->Section);
2101 this->Section = Section;
2102 // Since each type unit is contained in its own COMDAT section, the begin
2103 // label and the section label are the same. Using the begin label emission in
2104 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2105 // the only other alternative of lazily constructing start-of-section labels
2106 // and storing a mapping in DwarfDebug (or AsmPrinter).
2107 this->SectionSym = this->LabelBegin =
2108 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2110 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2111 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());