1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
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 writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
13 #define DEBUG_TYPE "dwarfdebug"
14 #include "DwarfDebug.h"
15 #include "llvm/Module.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetFrameInfo.h"
23 #include "llvm/Target/TargetLoweringObjectFile.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/System/Path.h"
32 static TimerGroup &getDwarfTimerGroup() {
33 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
34 return DwarfTimerGroup;
37 //===----------------------------------------------------------------------===//
39 /// Configuration values for initial hash set sizes (log2).
41 static const unsigned InitDiesSetSize = 9; // log2(512)
42 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
43 static const unsigned InitValuesSetSize = 9; // log2(512)
47 //===----------------------------------------------------------------------===//
48 /// CompileUnit - This dwarf writer support class manages information associate
49 /// with a source file.
50 class VISIBILITY_HIDDEN CompileUnit {
51 /// ID - File identifier for source.
55 /// Die - Compile unit debug information entry.
59 /// GVToDieMap - Tracks the mapping of unit level debug informaton
60 /// variables to debug information entries.
61 /// FIXME : Rename GVToDieMap -> NodeToDieMap
62 std::map<MDNode *, DIE *> GVToDieMap;
64 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
65 /// descriptors to debug information entries using a DIEEntry proxy.
67 std::map<MDNode *, DIEEntry *> GVToDIEEntryMap;
69 /// Globals - A map of globally visible named entities for this unit.
71 StringMap<DIE*> Globals;
73 /// DiesSet - Used to uniquely define dies within the compile unit.
75 FoldingSet<DIE> DiesSet;
77 CompileUnit(unsigned I, DIE *D)
78 : ID(I), Die(D), DiesSet(InitDiesSetSize) {}
79 ~CompileUnit() { delete Die; }
82 unsigned getID() const { return ID; }
83 DIE* getDie() const { return Die; }
84 StringMap<DIE*> &getGlobals() { return Globals; }
86 /// hasContent - Return true if this compile unit has something to write out.
88 bool hasContent() const { return !Die->getChildren().empty(); }
90 /// AddGlobal - Add a new global entity to the compile unit.
92 void AddGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
94 /// getDieMapSlotFor - Returns the debug information entry map slot for the
95 /// specified debug variable.
96 DIE *&getDieMapSlotFor(MDNode *N) { return GVToDieMap[N]; }
98 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for
99 /// the specified debug variable.
100 DIEEntry *&getDIEEntrySlotFor(MDNode *N) {
101 return GVToDIEEntryMap[N];
104 /// AddDie - Adds or interns the DIE to the compile unit.
106 DIE *AddDie(DIE &Buffer) {
110 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
113 Die = new DIE(Buffer);
114 DiesSet.InsertNode(Die, Where);
115 this->Die->AddChild(Die);
123 //===----------------------------------------------------------------------===//
124 /// DbgVariable - This class is used to track local variable information.
126 class VISIBILITY_HIDDEN DbgVariable {
127 DIVariable Var; // Variable Descriptor.
128 unsigned FrameIndex; // Variable frame index.
129 bool InlinedFnVar; // Variable for an inlined function.
131 DbgVariable(DIVariable V, unsigned I, bool IFV)
132 : Var(V), FrameIndex(I), InlinedFnVar(IFV) {}
135 DIVariable getVariable() const { return Var; }
136 unsigned getFrameIndex() const { return FrameIndex; }
137 bool isInlinedFnVar() const { return InlinedFnVar; }
140 //===----------------------------------------------------------------------===//
141 /// DbgScope - This class is used to track scope information.
143 class DbgConcreteScope;
144 class VISIBILITY_HIDDEN DbgScope {
145 DbgScope *Parent; // Parent to this scope.
146 DIDescriptor Desc; // Debug info descriptor for scope.
147 // Either subprogram or block.
148 unsigned StartLabelID; // Label ID of the beginning of scope.
149 unsigned EndLabelID; // Label ID of the end of scope.
150 const MachineInstr *LastInsn; // Last instruction of this scope.
151 const MachineInstr *FirstInsn; // First instruction of this scope.
152 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
153 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
154 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
156 // Private state for dump()
157 mutable unsigned IndentLevel;
159 DbgScope(DbgScope *P, DIDescriptor D)
160 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), LastInsn(0),
161 FirstInsn(0), IndentLevel(0) {}
165 DbgScope *getParent() const { return Parent; }
166 DIDescriptor getDesc() const { return Desc; }
167 unsigned getStartLabelID() const { return StartLabelID; }
168 unsigned getEndLabelID() const { return EndLabelID; }
169 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
170 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
171 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
172 void setStartLabelID(unsigned S) { StartLabelID = S; }
173 void setEndLabelID(unsigned E) { EndLabelID = E; }
174 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
175 const MachineInstr *getLastInsn() { return LastInsn; }
176 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
177 const MachineInstr *getFirstInsn() { return FirstInsn; }
178 /// AddScope - Add a scope to the scope.
180 void AddScope(DbgScope *S) { Scopes.push_back(S); }
182 /// AddVariable - Add a variable to the scope.
184 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
186 /// AddConcreteInst - Add a concrete instance to the scope.
188 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
196 void DbgScope::dump() const {
197 raw_ostream &err = errs();
198 err.indent(IndentLevel);
200 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
204 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
205 if (Scopes[i] != this)
212 //===----------------------------------------------------------------------===//
213 /// DbgConcreteScope - This class is used to track a scope that holds concrete
214 /// instance information.
216 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
218 DIE *Die; // Debug info for this concrete scope.
220 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
223 DIE *getDie() const { return Die; }
224 void setDie(DIE *D) { Die = D; }
227 DbgScope::~DbgScope() {
228 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
230 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
232 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
233 delete ConcreteInsts[k];
236 } // end llvm namespace
238 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
239 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
240 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
241 ValuesSet(InitValuesSetSize), Values(), StringPool(),
242 SectionSourceLines(), didInitial(false), shouldEmit(false),
243 FunctionDbgScope(0), DebugTimer(0) {
244 if (TimePassesIsEnabled)
245 DebugTimer = new Timer("Dwarf Debug Writer",
246 getDwarfTimerGroup());
248 DwarfDebug::~DwarfDebug() {
249 for (unsigned j = 0, M = Values.size(); j < M; ++j)
252 for (DenseMap<const MDNode *, DbgScope *>::iterator
253 I = AbstractInstanceRootMap.begin(),
254 E = AbstractInstanceRootMap.end(); I != E;++I)
260 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
262 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
263 // Profile the node so that we can make it unique.
267 // Check the set for priors.
268 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
270 // If it's newly added.
271 if (InSet == &Abbrev) {
272 // Add to abbreviation list.
273 Abbreviations.push_back(&Abbrev);
275 // Assign the vector position + 1 as its number.
276 Abbrev.setNumber(Abbreviations.size());
278 // Assign existing abbreviation number.
279 Abbrev.setNumber(InSet->getNumber());
283 /// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
284 /// information entry.
285 DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
290 DIEEntry::Profile(ID, Entry);
292 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
294 if (Value) return Value;
296 Value = new DIEEntry(Entry);
297 ValuesSet.InsertNode(Value, Where);
299 Value = new DIEEntry(Entry);
302 Values.push_back(Value);
306 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
308 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
309 Value->setEntry(Entry);
311 // Add to values set if not already there. If it is, we merely have a
312 // duplicate in the values list (no harm.)
313 ValuesSet.GetOrInsertNode(Value);
316 /// AddUInt - Add an unsigned integer attribute data and value.
318 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
319 unsigned Form, uint64_t Integer) {
320 if (!Form) Form = DIEInteger::BestForm(false, Integer);
323 DIEInteger::Profile(ID, Integer);
325 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
328 Value = new DIEInteger(Integer);
329 ValuesSet.InsertNode(Value, Where);
330 Values.push_back(Value);
333 Die->AddValue(Attribute, Form, Value);
336 /// AddSInt - Add an signed integer attribute data and value.
338 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
339 unsigned Form, int64_t Integer) {
340 if (!Form) Form = DIEInteger::BestForm(true, Integer);
343 DIEInteger::Profile(ID, (uint64_t)Integer);
345 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
348 Value = new DIEInteger(Integer);
349 ValuesSet.InsertNode(Value, Where);
350 Values.push_back(Value);
353 Die->AddValue(Attribute, Form, Value);
356 /// AddString - Add a string attribute data and value.
358 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
359 const std::string &String) {
361 DIEString::Profile(ID, String);
363 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
366 Value = new DIEString(String);
367 ValuesSet.InsertNode(Value, Where);
368 Values.push_back(Value);
371 Die->AddValue(Attribute, Form, Value);
374 /// AddLabel - Add a Dwarf label attribute data and value.
376 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
377 const DWLabel &Label) {
379 DIEDwarfLabel::Profile(ID, Label);
381 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
384 Value = new DIEDwarfLabel(Label);
385 ValuesSet.InsertNode(Value, Where);
386 Values.push_back(Value);
389 Die->AddValue(Attribute, Form, Value);
392 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
394 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
395 const std::string &Label) {
397 DIEObjectLabel::Profile(ID, Label);
399 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
402 Value = new DIEObjectLabel(Label);
403 ValuesSet.InsertNode(Value, Where);
404 Values.push_back(Value);
407 Die->AddValue(Attribute, Form, Value);
410 /// AddSectionOffset - Add a section offset label attribute data and value.
412 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
413 const DWLabel &Label, const DWLabel &Section,
414 bool isEH, bool useSet) {
416 DIESectionOffset::Profile(ID, Label, Section);
418 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
421 Value = new DIESectionOffset(Label, Section, isEH, useSet);
422 ValuesSet.InsertNode(Value, Where);
423 Values.push_back(Value);
426 Die->AddValue(Attribute, Form, Value);
429 /// AddDelta - Add a label delta attribute data and value.
431 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
432 const DWLabel &Hi, const DWLabel &Lo) {
434 DIEDelta::Profile(ID, Hi, Lo);
436 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
439 Value = new DIEDelta(Hi, Lo);
440 ValuesSet.InsertNode(Value, Where);
441 Values.push_back(Value);
444 Die->AddValue(Attribute, Form, Value);
447 /// AddBlock - Add block data.
449 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
451 Block->ComputeSize(TD);
455 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
459 ValuesSet.InsertNode(Value, Where);
460 Values.push_back(Value);
462 // Already exists, reuse the previous one.
464 Block = cast<DIEBlock>(Value);
467 Die->AddValue(Attribute, Block->BestForm(), Value);
470 /// AddSourceLine - Add location information to specified debug information
472 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
473 // If there is no compile unit specified, don't add a line #.
474 if (V->getCompileUnit().isNull())
477 unsigned Line = V->getLineNumber();
478 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
479 assert(FileID && "Invalid file id");
480 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
481 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
484 /// AddSourceLine - Add location information to specified debug information
486 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
487 // If there is no compile unit specified, don't add a line #.
488 if (G->getCompileUnit().isNull())
491 unsigned Line = G->getLineNumber();
492 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
493 assert(FileID && "Invalid file id");
494 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
495 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
498 /// AddSourceLine - Add location information to specified debug information
500 void DwarfDebug::AddSourceLine(DIE *Die, const DISubprogram *SP) {
501 // If there is no compile unit specified, don't add a line #.
502 if (SP->getCompileUnit().isNull())
504 // If the line number is 0, don't add it.
505 if (SP->getLineNumber() == 0)
509 unsigned Line = SP->getLineNumber();
510 unsigned FileID = FindCompileUnit(SP->getCompileUnit()).getID();
511 assert(FileID && "Invalid file id");
512 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
513 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
516 /// AddSourceLine - Add location information to specified debug information
518 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
519 // If there is no compile unit specified, don't add a line #.
520 DICompileUnit CU = Ty->getCompileUnit();
524 unsigned Line = Ty->getLineNumber();
525 unsigned FileID = FindCompileUnit(CU).getID();
526 assert(FileID && "Invalid file id");
527 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
528 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
531 /* Byref variables, in Blocks, are declared by the programmer as
532 "SomeType VarName;", but the compiler creates a
533 __Block_byref_x_VarName struct, and gives the variable VarName
534 either the struct, or a pointer to the struct, as its type. This
535 is necessary for various behind-the-scenes things the compiler
536 needs to do with by-reference variables in blocks.
538 However, as far as the original *programmer* is concerned, the
539 variable should still have type 'SomeType', as originally declared.
541 The following function dives into the __Block_byref_x_VarName
542 struct to find the original type of the variable. This will be
543 passed back to the code generating the type for the Debug
544 Information Entry for the variable 'VarName'. 'VarName' will then
545 have the original type 'SomeType' in its debug information.
547 The original type 'SomeType' will be the type of the field named
548 'VarName' inside the __Block_byref_x_VarName struct.
550 NOTE: In order for this to not completely fail on the debugger
551 side, the Debug Information Entry for the variable VarName needs to
552 have a DW_AT_location that tells the debugger how to unwind through
553 the pointers and __Block_byref_x_VarName struct to find the actual
554 value of the variable. The function AddBlockByrefType does this. */
556 /// Find the type the programmer originally declared the variable to be
557 /// and return that type.
559 DIType DwarfDebug::GetBlockByrefType(DIType Ty, std::string Name) {
562 unsigned tag = Ty.getTag();
564 if (tag == dwarf::DW_TAG_pointer_type) {
565 DIDerivedType DTy = DIDerivedType(Ty.getNode());
566 subType = DTy.getTypeDerivedFrom();
569 DICompositeType blockStruct = DICompositeType(subType.getNode());
571 DIArray Elements = blockStruct.getTypeArray();
573 if (Elements.isNull())
576 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
577 DIDescriptor Element = Elements.getElement(i);
578 DIDerivedType DT = DIDerivedType(Element.getNode());
579 if (strcmp(Name.c_str(), DT.getName()) == 0)
580 return (DT.getTypeDerivedFrom());
586 /// AddComplexAddress - Start with the address based on the location provided,
587 /// and generate the DWARF information necessary to find the actual variable
588 /// given the extra address information encoded in the DIVariable, starting from
589 /// the starting location. Add the DWARF information to the die.
591 void DwarfDebug::AddComplexAddress(DbgVariable *&DV, DIE *Die,
593 const MachineLocation &Location) {
594 const DIVariable &VD = DV->getVariable();
595 DIType Ty = VD.getType();
597 // Decode the original location, and use that as the start of the byref
598 // variable's location.
599 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
600 DIEBlock *Block = new DIEBlock();
602 if (Location.isReg()) {
604 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
606 Reg = Reg - dwarf::DW_OP_reg0;
607 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
608 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
612 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
614 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
615 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
618 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
621 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
622 uint64_t Element = VD.getAddrElement(i);
624 if (Element == DIFactory::OpPlus) {
625 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
626 AddUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
627 } else if (Element == DIFactory::OpDeref) {
628 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
629 } else llvm_unreachable("unknown DIFactory Opcode");
632 // Now attach the location information to the DIE.
633 AddBlock(Die, Attribute, 0, Block);
636 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
637 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
638 gives the variable VarName either the struct, or a pointer to the struct, as
639 its type. This is necessary for various behind-the-scenes things the
640 compiler needs to do with by-reference variables in Blocks.
642 However, as far as the original *programmer* is concerned, the variable
643 should still have type 'SomeType', as originally declared.
645 The function GetBlockByrefType dives into the __Block_byref_x_VarName
646 struct to find the original type of the variable, which is then assigned to
647 the variable's Debug Information Entry as its real type. So far, so good.
648 However now the debugger will expect the variable VarName to have the type
649 SomeType. So we need the location attribute for the variable to be an
650 expression that explains to the debugger how to navigate through the
651 pointers and struct to find the actual variable of type SomeType.
653 The following function does just that. We start by getting
654 the "normal" location for the variable. This will be the location
655 of either the struct __Block_byref_x_VarName or the pointer to the
656 struct __Block_byref_x_VarName.
658 The struct will look something like:
660 struct __Block_byref_x_VarName {
662 struct __Block_byref_x_VarName *forwarding;
663 ... <various other fields>
665 ... <maybe more fields>
668 If we are given the struct directly (as our starting point) we
669 need to tell the debugger to:
671 1). Add the offset of the forwarding field.
673 2). Follow that pointer to get the the real __Block_byref_x_VarName
674 struct to use (the real one may have been copied onto the heap).
676 3). Add the offset for the field VarName, to find the actual variable.
678 If we started with a pointer to the struct, then we need to
679 dereference that pointer first, before the other steps.
680 Translating this into DWARF ops, we will need to append the following
681 to the current location description for the variable:
683 DW_OP_deref -- optional, if we start with a pointer
684 DW_OP_plus_uconst <forward_fld_offset>
686 DW_OP_plus_uconst <varName_fld_offset>
688 That is what this function does. */
690 /// AddBlockByrefAddress - Start with the address based on the location
691 /// provided, and generate the DWARF information necessary to find the
692 /// actual Block variable (navigating the Block struct) based on the
693 /// starting location. Add the DWARF information to the die. For
694 /// more information, read large comment just above here.
696 void DwarfDebug::AddBlockByrefAddress(DbgVariable *&DV, DIE *Die,
698 const MachineLocation &Location) {
699 const DIVariable &VD = DV->getVariable();
700 DIType Ty = VD.getType();
702 unsigned Tag = Ty.getTag();
703 bool isPointer = false;
705 const char *varName = VD.getName();
707 if (Tag == dwarf::DW_TAG_pointer_type) {
708 DIDerivedType DTy = DIDerivedType(Ty.getNode());
709 TmpTy = DTy.getTypeDerivedFrom();
713 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
715 // Find the __forwarding field and the variable field in the __Block_byref
717 DIArray Fields = blockStruct.getTypeArray();
718 DIDescriptor varField = DIDescriptor();
719 DIDescriptor forwardingField = DIDescriptor();
722 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
723 DIDescriptor Element = Fields.getElement(i);
724 DIDerivedType DT = DIDerivedType(Element.getNode());
725 const char *fieldName = DT.getName();
726 if (strcmp(fieldName, "__forwarding") == 0)
727 forwardingField = Element;
728 else if (strcmp(fieldName, varName) == 0)
732 assert(!varField.isNull() && "Can't find byref variable in Block struct");
733 assert(!forwardingField.isNull()
734 && "Can't find forwarding field in Block struct");
736 // Get the offsets for the forwarding field and the variable field.
737 unsigned int forwardingFieldOffset =
738 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
739 unsigned int varFieldOffset =
740 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
742 // Decode the original location, and use that as the start of the byref
743 // variable's location.
744 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
745 DIEBlock *Block = new DIEBlock();
747 if (Location.isReg()) {
749 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
751 Reg = Reg - dwarf::DW_OP_reg0;
752 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
753 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
757 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
759 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
760 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
763 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
766 // If we started with a pointer to the __Block_byref... struct, then
767 // the first thing we need to do is dereference the pointer (DW_OP_deref).
769 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
771 // Next add the offset for the '__forwarding' field:
772 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
773 // adding the offset if it's 0.
774 if (forwardingFieldOffset > 0) {
775 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
776 AddUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
779 // Now dereference the __forwarding field to get to the real __Block_byref
780 // struct: DW_OP_deref.
781 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
783 // Now that we've got the real __Block_byref... struct, add the offset
784 // for the variable's field to get to the location of the actual variable:
785 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
786 if (varFieldOffset > 0) {
787 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
788 AddUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
791 // Now attach the location information to the DIE.
792 AddBlock(Die, Attribute, 0, Block);
795 /// AddAddress - Add an address attribute to a die based on the location
797 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
798 const MachineLocation &Location) {
799 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
800 DIEBlock *Block = new DIEBlock();
802 if (Location.isReg()) {
804 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
806 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
807 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
811 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
813 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
814 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
817 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
820 AddBlock(Die, Attribute, 0, Block);
823 /// AddType - Add a new type attribute to the specified entity.
824 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
828 // Check for pre-existence.
829 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getNode());
831 // If it exists then use the existing value.
833 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
838 Slot = CreateDIEEntry();
841 DIE Buffer(dwarf::DW_TAG_base_type);
842 if (Ty.isBasicType())
843 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getNode()));
844 else if (Ty.isCompositeType())
845 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getNode()));
847 assert(Ty.isDerivedType() && "Unknown kind of DIType");
848 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getNode()));
851 // Add debug information entry to entity and appropriate context.
853 DIDescriptor Context = Ty.getContext();
854 if (!Context.isNull())
855 Die = DW_Unit->getDieMapSlotFor(Context.getNode());
858 DIE *Child = new DIE(Buffer);
859 Die->AddChild(Child);
861 SetDIEEntry(Slot, Child);
863 Die = DW_Unit->AddDie(Buffer);
864 SetDIEEntry(Slot, Die);
867 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
870 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
871 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
873 // Get core information.
874 const char *Name = BTy.getName();
875 Buffer.setTag(dwarf::DW_TAG_base_type);
876 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
879 // Add name if not anonymous or intermediate type.
881 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
882 uint64_t Size = BTy.getSizeInBits() >> 3;
883 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
886 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
887 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
889 // Get core information.
890 const char *Name = DTy.getName();
891 uint64_t Size = DTy.getSizeInBits() >> 3;
892 unsigned Tag = DTy.getTag();
894 // FIXME - Workaround for templates.
895 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
899 // Map to main type, void will not have a type.
900 DIType FromTy = DTy.getTypeDerivedFrom();
901 AddType(DW_Unit, &Buffer, FromTy);
903 // Add name if not anonymous or intermediate type.
905 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
907 // Add size if non-zero (derived types might be zero-sized.)
909 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
911 // Add source line info if available and TyDesc is not a forward declaration.
912 if (!DTy.isForwardDecl())
913 AddSourceLine(&Buffer, &DTy);
916 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
917 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
918 DICompositeType CTy) {
919 // Get core information.
920 const char *Name = CTy.getName();
922 uint64_t Size = CTy.getSizeInBits() >> 3;
923 unsigned Tag = CTy.getTag();
927 case dwarf::DW_TAG_vector_type:
928 case dwarf::DW_TAG_array_type:
929 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
931 case dwarf::DW_TAG_enumeration_type: {
932 DIArray Elements = CTy.getTypeArray();
934 // Add enumerators to enumeration type.
935 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
937 DIEnumerator Enum(Elements.getElement(i).getNode());
938 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
939 Buffer.AddChild(ElemDie);
943 case dwarf::DW_TAG_subroutine_type: {
945 DIArray Elements = CTy.getTypeArray();
946 DIDescriptor RTy = Elements.getElement(0);
947 AddType(DW_Unit, &Buffer, DIType(RTy.getNode()));
949 // Add prototype flag.
950 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
953 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
954 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
955 DIDescriptor Ty = Elements.getElement(i);
956 AddType(DW_Unit, Arg, DIType(Ty.getNode()));
957 Buffer.AddChild(Arg);
961 case dwarf::DW_TAG_structure_type:
962 case dwarf::DW_TAG_union_type:
963 case dwarf::DW_TAG_class_type: {
964 // Add elements to structure type.
965 DIArray Elements = CTy.getTypeArray();
967 // A forward struct declared type may not have elements available.
968 if (Elements.isNull())
971 // Add elements to structure type.
972 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
973 DIDescriptor Element = Elements.getElement(i);
974 if (Element.isNull())
977 if (Element.getTag() == dwarf::DW_TAG_subprogram)
978 ElemDie = CreateSubprogramDIE(DW_Unit,
979 DISubprogram(Element.getNode()));
981 ElemDie = CreateMemberDIE(DW_Unit,
982 DIDerivedType(Element.getNode()));
983 Buffer.AddChild(ElemDie);
986 if (CTy.isAppleBlockExtension())
987 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
989 unsigned RLang = CTy.getRunTimeLang();
991 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
992 dwarf::DW_FORM_data1, RLang);
999 // Add name if not anonymous or intermediate type.
1001 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1003 if (Tag == dwarf::DW_TAG_enumeration_type ||
1004 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1005 // Add size if non-zero (derived types might be zero-sized.)
1007 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1009 // Add zero size if it is not a forward declaration.
1010 if (CTy.isForwardDecl())
1011 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1013 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1016 // Add source line info if available.
1017 if (!CTy.isForwardDecl())
1018 AddSourceLine(&Buffer, &CTy);
1022 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1023 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1024 int64_t L = SR.getLo();
1025 int64_t H = SR.getHi();
1026 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1028 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1030 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1032 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1034 Buffer.AddChild(DW_Subrange);
1037 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1038 void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1039 DICompositeType *CTy) {
1040 Buffer.setTag(dwarf::DW_TAG_array_type);
1041 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1042 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1044 // Emit derived type.
1045 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1046 DIArray Elements = CTy->getTypeArray();
1048 // Construct an anonymous type for index type.
1049 DIE IdxBuffer(dwarf::DW_TAG_base_type);
1050 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1051 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1052 dwarf::DW_ATE_signed);
1053 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1055 // Add subranges to array type.
1056 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1057 DIDescriptor Element = Elements.getElement(i);
1058 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1059 ConstructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IndexTy);
1063 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1064 DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1065 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1066 const char *Name = ETy->getName();
1067 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1068 int64_t Value = ETy->getEnumValue();
1069 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1073 /// CreateGlobalVariableDIE - Create new DIE using GV.
1074 DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
1075 const DIGlobalVariable &GV) {
1076 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1077 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1078 GV.getDisplayName());
1080 const char *LinkageName = GV.getLinkageName();
1082 // Skip special LLVM prefix that is used to inform the asm printer to not
1083 // emit usual symbol prefix before the symbol name. This happens for
1084 // Objective-C symbol names and symbol whose name is replaced using GCC's
1085 // __asm__ attribute.
1086 if (LinkageName[0] == 1)
1087 LinkageName = &LinkageName[1];
1088 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1091 AddType(DW_Unit, GVDie, GV.getType());
1092 if (!GV.isLocalToUnit())
1093 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1094 AddSourceLine(GVDie, &GV);
1098 /// CreateMemberDIE - Create new member DIE.
1099 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
1100 DIE *MemberDie = new DIE(DT.getTag());
1101 if (const char *Name = DT.getName())
1102 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1104 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1106 AddSourceLine(MemberDie, &DT);
1108 uint64_t Size = DT.getSizeInBits();
1109 uint64_t FieldSize = DT.getOriginalTypeSize();
1111 if (Size != FieldSize) {
1113 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1114 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1116 uint64_t Offset = DT.getOffsetInBits();
1117 uint64_t FieldOffset = Offset;
1118 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1119 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1120 FieldOffset = (HiMark - FieldSize);
1121 Offset -= FieldOffset;
1123 // Maybe we need to work from the other end.
1124 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1125 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1128 DIEBlock *Block = new DIEBlock();
1129 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1130 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1131 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
1133 if (DT.isProtected())
1134 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1135 dwarf::DW_ACCESS_protected);
1136 else if (DT.isPrivate())
1137 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1138 dwarf::DW_ACCESS_private);
1143 /// CreateSubprogramDIE - Create new DIE using SP.
1144 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
1145 const DISubprogram &SP,
1148 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1150 const char * Name = SP.getName();
1151 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1153 const char *LinkageName = SP.getLinkageName();
1155 // Skip special LLVM prefix that is used to inform the asm printer to not emit
1156 // usual symbol prefix before the symbol name. This happens for Objective-C
1157 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
1158 if (LinkageName[0] == 1)
1159 LinkageName = &LinkageName[1];
1160 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1163 AddSourceLine(SPDie, &SP);
1165 DICompositeType SPTy = SP.getType();
1166 DIArray Args = SPTy.getTypeArray();
1168 // Add prototyped tag, if C or ObjC.
1169 unsigned Lang = SP.getCompileUnit().getLanguage();
1170 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1171 Lang == dwarf::DW_LANG_ObjC)
1172 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1175 unsigned SPTag = SPTy.getTag();
1176 if (!IsConstructor) {
1177 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1178 AddType(DW_Unit, SPDie, SPTy);
1180 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
1183 if (!SP.isDefinition()) {
1184 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1186 // Add arguments. Do not add arguments for subprogram definition. They will
1187 // be handled through RecordVariable.
1188 if (SPTag == dwarf::DW_TAG_subroutine_type)
1189 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1190 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1191 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1192 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1193 SPDie->AddChild(Arg);
1197 if (!SP.isLocalToUnit() && !IsInlined)
1198 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1200 // DW_TAG_inlined_subroutine may refer to this DIE.
1201 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getNode());
1206 /// FindCompileUnit - Get the compile unit for the given descriptor.
1208 CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
1209 DenseMap<Value *, CompileUnit *>::const_iterator I =
1210 CompileUnitMap.find(Unit.getNode());
1211 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1215 /// CreateDbgScopeVariable - Create a new scope variable.
1217 DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1218 // Get the descriptor.
1219 const DIVariable &VD = DV->getVariable();
1221 // Translate tag to proper Dwarf tag. The result variable is dropped for
1224 switch (VD.getTag()) {
1225 case dwarf::DW_TAG_return_variable:
1227 case dwarf::DW_TAG_arg_variable:
1228 Tag = dwarf::DW_TAG_formal_parameter;
1230 case dwarf::DW_TAG_auto_variable: // fall thru
1232 Tag = dwarf::DW_TAG_variable;
1236 // Define variable debug information entry.
1237 DIE *VariableDie = new DIE(Tag);
1238 const char *Name = VD.getName();
1239 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1241 // Add source line info if available.
1242 AddSourceLine(VariableDie, &VD);
1244 // Add variable type.
1245 // FIXME: isBlockByrefVariable should be reformulated in terms of complex addresses instead.
1246 if (VD.isBlockByrefVariable())
1247 AddType(Unit, VariableDie, GetBlockByrefType(VD.getType(), Name));
1249 AddType(Unit, VariableDie, VD.getType());
1251 // Add variable address.
1252 if (!DV->isInlinedFnVar()) {
1253 // Variables for abstract instances of inlined functions don't get a
1255 MachineLocation Location;
1256 Location.set(RI->getFrameRegister(*MF),
1257 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1260 if (VD.hasComplexAddress())
1261 AddComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1262 else if (VD.isBlockByrefVariable())
1263 AddBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1265 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
1271 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1273 DbgScope *DwarfDebug::getOrCreateScope(MDNode *N) {
1274 DbgScope *&Slot = DbgScopeMap[N];
1275 if (Slot) return Slot;
1277 DbgScope *Parent = NULL;
1278 DILexicalBlock Block(N);
1280 // Don't create a new scope if we already created one for an inlined function.
1281 DenseMap<const MDNode *, DbgScope *>::iterator
1282 II = AbstractInstanceRootMap.find(N);
1283 if (II != AbstractInstanceRootMap.end())
1284 return LexicalScopeStack.back();
1286 if (!Block.isNull()) {
1287 DIDescriptor ParentDesc = Block.getContext();
1289 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getNode());
1292 Slot = new DbgScope(Parent, DIDescriptor(N));
1295 Parent->AddScope(Slot);
1297 // First function is top level function.
1298 FunctionDbgScope = Slot;
1303 /// ConstructDbgScope - Construct the components of a scope.
1305 void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1306 unsigned ParentStartID,
1307 unsigned ParentEndID,
1308 DIE *ParentDie, CompileUnit *Unit) {
1309 // Add variables to scope.
1310 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1311 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1312 DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
1313 if (VariableDie) ParentDie->AddChild(VariableDie);
1316 // Add concrete instances to scope.
1317 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1318 ParentScope->getConcreteInsts();
1319 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1320 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1321 DIE *Die = ConcreteInst->getDie();
1323 unsigned StartID = ConcreteInst->getStartLabelID();
1324 unsigned EndID = ConcreteInst->getEndLabelID();
1326 // Add the scope bounds.
1328 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1329 DWLabel("label", StartID));
1331 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1332 DWLabel("func_begin", SubprogramCount));
1335 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1336 DWLabel("label", EndID));
1338 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1339 DWLabel("func_end", SubprogramCount));
1341 ParentDie->AddChild(Die);
1344 // Add nested scopes.
1345 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1346 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1347 // Define the Scope debug information entry.
1348 DbgScope *Scope = Scopes[j];
1350 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1351 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1353 // Ignore empty scopes.
1354 if (StartID == EndID && StartID != 0) continue;
1356 // Do not ignore inlined scopes even if they don't have any variables or
1358 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1359 Scope->getConcreteInsts().empty())
1362 if (StartID == ParentStartID && EndID == ParentEndID) {
1363 // Just add stuff to the parent scope.
1364 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1366 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1368 // Add the scope bounds.
1370 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1371 DWLabel("label", StartID));
1373 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1374 DWLabel("func_begin", SubprogramCount));
1377 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1378 DWLabel("label", EndID));
1380 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1381 DWLabel("func_end", SubprogramCount));
1383 // Add the scope's contents.
1384 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1385 ParentDie->AddChild(ScopeDie);
1390 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1392 void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
1393 bool AbstractScope) {
1394 // Exit if there is no root scope.
1395 if (!RootScope) return;
1396 DIDescriptor Desc = RootScope->getDesc();
1400 // Get the subprogram debug information entry.
1401 DISubprogram SPD(Desc.getNode());
1403 // Get the subprogram die.
1404 DIE *SPDie = ModuleCU->getDieMapSlotFor(SPD.getNode());
1405 assert(SPDie && "Missing subprogram descriptor");
1407 if (!AbstractScope) {
1408 // Add the function bounds.
1409 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1410 DWLabel("func_begin", SubprogramCount));
1411 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1412 DWLabel("func_end", SubprogramCount));
1413 MachineLocation Location(RI->getFrameRegister(*MF));
1414 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1417 ConstructDbgScope(RootScope, 0, 0, SPDie, ModuleCU);
1420 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1422 void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1423 StringMap<DIE*> &Globals = ModuleCU->getGlobals();
1424 StringMap<DIE*>::iterator GI = Globals.find(MF->getFunction()->getName());
1425 if (GI != Globals.end()) {
1426 DIE *SPDie = GI->second;
1428 // Add the function bounds.
1429 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1430 DWLabel("func_begin", SubprogramCount));
1431 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1432 DWLabel("func_end", SubprogramCount));
1434 MachineLocation Location(RI->getFrameRegister(*MF));
1435 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1439 /// GetOrCreateSourceID - Look up the source id with the given directory and
1440 /// source file names. If none currently exists, create a new id and insert it
1441 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1443 unsigned DwarfDebug::GetOrCreateSourceID(const char *DirName,
1444 const char *FileName) {
1446 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1447 if (DI != DirectoryIdMap.end()) {
1448 DId = DI->getValue();
1450 DId = DirectoryNames.size() + 1;
1451 DirectoryIdMap[DirName] = DId;
1452 DirectoryNames.push_back(DirName);
1456 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1457 if (FI != SourceFileIdMap.end()) {
1458 FId = FI->getValue();
1460 FId = SourceFileNames.size() + 1;
1461 SourceFileIdMap[FileName] = FId;
1462 SourceFileNames.push_back(FileName);
1465 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1466 SourceIdMap.find(std::make_pair(DId, FId));
1467 if (SI != SourceIdMap.end())
1470 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1471 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1472 SourceIds.push_back(std::make_pair(DId, FId));
1477 void DwarfDebug::ConstructCompileUnit(MDNode *N) {
1478 DICompileUnit DIUnit(N);
1479 const char *FN = DIUnit.getFilename();
1480 const char *Dir = DIUnit.getDirectory();
1481 unsigned ID = GetOrCreateSourceID(Dir, FN);
1483 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1484 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1485 DWLabel("section_line", 0), DWLabel("section_line", 0),
1487 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1488 DIUnit.getProducer());
1489 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1490 DIUnit.getLanguage());
1491 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1494 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1495 if (DIUnit.isOptimized())
1496 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1498 if (const char *Flags = DIUnit.getFlags())
1499 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1501 unsigned RVer = DIUnit.getRunTimeVersion();
1503 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1504 dwarf::DW_FORM_data1, RVer);
1506 CompileUnit *Unit = new CompileUnit(ID, Die);
1507 if (!ModuleCU && DIUnit.isMain()) {
1508 // Use first compile unit marked as isMain as the compile unit
1513 CompileUnitMap[DIUnit.getNode()] = Unit;
1514 CompileUnits.push_back(Unit);
1517 void DwarfDebug::ConstructGlobalVariableDIE(MDNode *N) {
1518 DIGlobalVariable DI_GV(N);
1520 // If debug information is malformed then ignore it.
1521 if (DI_GV.Verify() == false)
1524 // Check for pre-existence.
1525 DIE *&Slot = ModuleCU->getDieMapSlotFor(DI_GV.getNode());
1529 DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
1532 DIEBlock *Block = new DIEBlock();
1533 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1534 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1535 Asm->Mang->getMangledName(DI_GV.getGlobal()));
1536 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1541 // Add to context owner.
1542 ModuleCU->getDie()->AddChild(VariableDie);
1544 // Expose as global. FIXME - need to check external flag.
1545 ModuleCU->AddGlobal(DI_GV.getName(), VariableDie);
1549 void DwarfDebug::ConstructSubprogram(MDNode *N) {
1552 // Check for pre-existence.
1553 DIE *&Slot = ModuleCU->getDieMapSlotFor(N);
1557 if (!SP.isDefinition())
1558 // This is a method declaration which will be handled while constructing
1562 DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
1565 Slot = SubprogramDie;
1567 // Add to context owner.
1568 ModuleCU->getDie()->AddChild(SubprogramDie);
1570 // Expose as global.
1571 ModuleCU->AddGlobal(SP.getName(), SubprogramDie);
1575 /// BeginModule - Emit all Dwarf sections that should come prior to the
1576 /// content. Create global DIEs and emit initial debug info sections.
1577 /// This is inovked by the target AsmPrinter.
1578 void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
1581 if (TimePassesIsEnabled)
1582 DebugTimer->startTimer();
1584 DebugInfoFinder DbgFinder;
1585 DbgFinder.processModule(*M);
1587 // Create all the compile unit DIEs.
1588 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1589 E = DbgFinder.compile_unit_end(); I != E; ++I)
1590 ConstructCompileUnit(*I);
1592 if (CompileUnits.empty()) {
1593 if (TimePassesIsEnabled)
1594 DebugTimer->stopTimer();
1599 // If main compile unit for this module is not seen than randomly
1600 // select first compile unit.
1602 ModuleCU = CompileUnits[0];
1604 // If there is not any debug info available for any global variables and any
1605 // subprograms then there is not any debug info to emit.
1606 if (DbgFinder.global_variable_count() == 0
1607 && DbgFinder.subprogram_count() == 0) {
1608 if (TimePassesIsEnabled)
1609 DebugTimer->stopTimer();
1613 // Create DIEs for each of the externally visible global variables.
1614 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1615 E = DbgFinder.global_variable_end(); I != E; ++I)
1616 ConstructGlobalVariableDIE(*I);
1618 // Create DIEs for each of the externally visible subprograms.
1619 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1620 E = DbgFinder.subprogram_end(); I != E; ++I)
1621 ConstructSubprogram(*I);
1625 MMI->setDebugInfoAvailability(true);
1627 // Prime section data.
1628 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1630 // Print out .file directives to specify files for .loc directives. These are
1631 // printed out early so that they precede any .loc directives.
1632 if (MAI->hasDotLocAndDotFile()) {
1633 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1634 // Remember source id starts at 1.
1635 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1636 sys::Path FullPath(getSourceDirectoryName(Id.first));
1638 FullPath.appendComponent(getSourceFileName(Id.second));
1639 assert(AppendOk && "Could not append filename to directory!");
1641 Asm->EmitFile(i, FullPath.str());
1646 // Emit initial sections
1649 if (TimePassesIsEnabled)
1650 DebugTimer->stopTimer();
1653 /// EndModule - Emit all Dwarf sections that should come after the content.
1655 void DwarfDebug::EndModule() {
1656 if (!ShouldEmitDwarfDebug())
1659 if (TimePassesIsEnabled)
1660 DebugTimer->startTimer();
1662 // Standard sections final addresses.
1663 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1664 EmitLabel("text_end", 0);
1665 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1666 EmitLabel("data_end", 0);
1668 // End text sections.
1669 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1670 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1671 EmitLabel("section_end", i);
1674 // Emit common frame information.
1675 EmitCommonDebugFrame();
1677 // Emit function debug frame information
1678 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1679 E = DebugFrames.end(); I != E; ++I)
1680 EmitFunctionDebugFrame(*I);
1682 // Compute DIE offsets and sizes.
1685 // Emit all the DIEs into a debug info section
1688 // Corresponding abbreviations into a abbrev section.
1689 EmitAbbreviations();
1691 // Emit source line correspondence into a debug line section.
1694 // Emit info into a debug pubnames section.
1695 EmitDebugPubNames();
1697 // Emit info into a debug str section.
1700 // Emit info into a debug loc section.
1703 // Emit info into a debug aranges section.
1706 // Emit info into a debug ranges section.
1709 // Emit info into a debug macinfo section.
1712 // Emit inline info.
1713 EmitDebugInlineInfo();
1715 if (TimePassesIsEnabled)
1716 DebugTimer->stopTimer();
1719 /// BeginFunction - Gather pre-function debug information. Assumes being
1720 /// emitted immediately after the function entry point.
1721 void DwarfDebug::BeginFunction(MachineFunction *MF) {
1724 if (!ShouldEmitDwarfDebug()) return;
1726 if (TimePassesIsEnabled)
1727 DebugTimer->startTimer();
1729 // Begin accumulating function debug information.
1730 MMI->BeginFunction(MF);
1732 // Assumes in correct section after the entry point.
1733 EmitLabel("func_begin", ++SubprogramCount);
1735 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1737 DebugLoc FDL = MF->getDefaultDebugLoc();
1738 if (!FDL.isUnknown()) {
1739 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1740 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col, DLT.CompileUnit);
1741 Asm->printLabel(LabelID);
1745 if (TimePassesIsEnabled)
1746 DebugTimer->stopTimer();
1749 /// EndFunction - Gather and emit post-function debug information.
1751 void DwarfDebug::EndFunction(MachineFunction *MF) {
1752 if (!ShouldEmitDwarfDebug()) return;
1754 if (TimePassesIsEnabled)
1755 DebugTimer->startTimer();
1757 // Define end label for subprogram.
1758 EmitLabel("func_end", SubprogramCount);
1760 // Get function line info.
1761 if (!Lines.empty()) {
1762 // Get section line info.
1763 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
1764 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
1765 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
1766 // Append the function info to section info.
1767 SectionLineInfos.insert(SectionLineInfos.end(),
1768 Lines.begin(), Lines.end());
1771 // Construct the DbgScope for abstract instances.
1772 for (SmallVector<DbgScope *, 32>::iterator
1773 I = AbstractInstanceRootList.begin(),
1774 E = AbstractInstanceRootList.end(); I != E; ++I)
1775 ConstructFunctionDbgScope(*I);
1777 // Construct scopes for subprogram.
1778 if (FunctionDbgScope)
1779 ConstructFunctionDbgScope(FunctionDbgScope);
1781 // FIXME: This is wrong. We are essentially getting past a problem with
1782 // debug information not being able to handle unreachable blocks that have
1783 // debug information in them. In particular, those unreachable blocks that
1784 // have "region end" info in them. That situation results in the "root
1785 // scope" not being created. If that's the case, then emit a "default"
1786 // scope, i.e., one that encompasses the whole function. This isn't
1787 // desirable. And a better way of handling this (and all of the debugging
1788 // information) needs to be explored.
1789 ConstructDefaultDbgScope(MF);
1791 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
1792 MMI->getFrameMoves()));
1795 if (FunctionDbgScope) {
1796 delete FunctionDbgScope;
1797 DbgScopeMap.clear();
1798 DbgAbstractScopeMap.clear();
1799 DbgConcreteScopeMap.clear();
1800 FunctionDbgScope = NULL;
1801 LexicalScopeStack.clear();
1802 AbstractInstanceRootList.clear();
1803 AbstractInstanceRootMap.clear();
1808 if (TimePassesIsEnabled)
1809 DebugTimer->stopTimer();
1812 /// RecordSourceLine - Records location information and associates it with a
1813 /// label. Returns a unique label ID used to generate a label and provide
1814 /// correspondence to the source line list.
1815 unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
1816 if (TimePassesIsEnabled)
1817 DebugTimer->startTimer();
1819 CompileUnit *Unit = CompileUnitMap[V];
1820 assert(Unit && "Unable to find CompileUnit");
1821 unsigned ID = MMI->NextLabelID();
1822 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
1824 if (TimePassesIsEnabled)
1825 DebugTimer->stopTimer();
1830 /// RecordSourceLine - Records location information and associates it with a
1831 /// label. Returns a unique label ID used to generate a label and provide
1832 /// correspondence to the source line list.
1833 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
1838 if (TimePassesIsEnabled)
1839 DebugTimer->startTimer();
1841 DICompileUnit CU(Scope);
1842 unsigned Src = GetOrCreateSourceID(CU.getDirectory(),
1844 unsigned ID = MMI->NextLabelID();
1845 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
1847 if (TimePassesIsEnabled)
1848 DebugTimer->stopTimer();
1853 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
1854 /// timed. Look up the source id with the given directory and source file
1855 /// names. If none currently exists, create a new id and insert it in the
1856 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
1858 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
1859 const std::string &FileName) {
1860 if (TimePassesIsEnabled)
1861 DebugTimer->startTimer();
1863 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
1865 if (TimePassesIsEnabled)
1866 DebugTimer->stopTimer();
1871 /// RecordRegionStart - Indicate the start of a region.
1872 unsigned DwarfDebug::RecordRegionStart(MDNode *N) {
1873 if (TimePassesIsEnabled)
1874 DebugTimer->startTimer();
1876 DbgScope *Scope = getOrCreateScope(N);
1877 unsigned ID = MMI->NextLabelID();
1878 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1879 LexicalScopeStack.push_back(Scope);
1881 if (TimePassesIsEnabled)
1882 DebugTimer->stopTimer();
1887 /// RecordRegionEnd - Indicate the end of a region.
1888 unsigned DwarfDebug::RecordRegionEnd(MDNode *N) {
1889 if (TimePassesIsEnabled)
1890 DebugTimer->startTimer();
1892 DbgScope *Scope = getOrCreateScope(N);
1893 unsigned ID = MMI->NextLabelID();
1894 Scope->setEndLabelID(ID);
1895 // FIXME : region.end() may not be in the last basic block.
1896 // For now, do not pop last lexical scope because next basic
1897 // block may start new inlined function's body.
1898 unsigned LSSize = LexicalScopeStack.size();
1899 if (LSSize != 0 && LSSize != 1)
1900 LexicalScopeStack.pop_back();
1902 if (TimePassesIsEnabled)
1903 DebugTimer->stopTimer();
1908 /// RecordVariable - Indicate the declaration of a local variable.
1909 void DwarfDebug::RecordVariable(MDNode *N, unsigned FrameIndex) {
1910 if (TimePassesIsEnabled)
1911 DebugTimer->startTimer();
1913 DIDescriptor Desc(N);
1914 DbgScope *Scope = NULL;
1915 bool InlinedFnVar = false;
1917 if (Desc.getTag() == dwarf::DW_TAG_variable)
1918 Scope = getOrCreateScope(DIGlobalVariable(N).getContext().getNode());
1920 bool InlinedVar = false;
1921 MDNode *Context = DIVariable(N).getContext().getNode();
1922 DISubprogram SP(Context);
1924 // SP is inserted into DbgAbstractScopeMap when inlined function
1925 // start was recorded by RecordInlineFnStart.
1926 DenseMap<MDNode *, DbgScope *>::iterator
1927 I = DbgAbstractScopeMap.find(SP.getNode());
1928 if (I != DbgAbstractScopeMap.end()) {
1934 Scope = getOrCreateScope(Context);
1937 assert(Scope && "Unable to find the variable's scope");
1938 DbgVariable *DV = new DbgVariable(DIVariable(N), FrameIndex, InlinedFnVar);
1939 Scope->AddVariable(DV);
1941 if (TimePassesIsEnabled)
1942 DebugTimer->stopTimer();
1945 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
1946 unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
1947 unsigned Line, unsigned Col) {
1948 unsigned LabelID = MMI->NextLabelID();
1950 if (!MAI->doesDwarfUsesInlineInfoSection())
1953 if (TimePassesIsEnabled)
1954 DebugTimer->startTimer();
1956 MDNode *Node = SP.getNode();
1957 DenseMap<const MDNode *, DbgScope *>::iterator
1958 II = AbstractInstanceRootMap.find(Node);
1960 if (II == AbstractInstanceRootMap.end()) {
1961 // Create an abstract instance entry for this inlined function if it doesn't
1963 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(Node));
1965 // Get the compile unit context.
1966 DIE *SPDie = ModuleCU->getDieMapSlotFor(Node);
1968 SPDie = CreateSubprogramDIE(ModuleCU, SP, false, true);
1970 // Mark as being inlined. This makes this subprogram entry an abstract
1972 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
1973 // that it's defined. That probably won't change in the future. However,
1974 // this could be more elegant.
1975 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
1977 // Keep track of the abstract scope for this function.
1978 DbgAbstractScopeMap[Node] = Scope;
1980 AbstractInstanceRootMap[Node] = Scope;
1981 AbstractInstanceRootList.push_back(Scope);
1984 // Create a concrete inlined instance for this inlined function.
1985 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(Node));
1986 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
1987 ScopeDie->setAbstractCompileUnit(ModuleCU);
1989 DIE *Origin = ModuleCU->getDieMapSlotFor(Node);
1990 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
1991 dwarf::DW_FORM_ref4, Origin);
1992 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1993 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
1994 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
1996 ConcreteScope->setDie(ScopeDie);
1997 ConcreteScope->setStartLabelID(LabelID);
1998 MMI->RecordUsedDbgLabel(LabelID);
2000 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
2002 // Keep track of the concrete scope that's inlined into this function.
2003 DenseMap<MDNode *, SmallVector<DbgScope *, 8> >::iterator
2004 SI = DbgConcreteScopeMap.find(Node);
2006 if (SI == DbgConcreteScopeMap.end())
2007 DbgConcreteScopeMap[Node].push_back(ConcreteScope);
2009 SI->second.push_back(ConcreteScope);
2011 // Track the start label for this inlined function.
2012 DenseMap<MDNode *, SmallVector<unsigned, 4> >::iterator
2013 I = InlineInfo.find(Node);
2015 if (I == InlineInfo.end())
2016 InlineInfo[Node].push_back(LabelID);
2018 I->second.push_back(LabelID);
2020 if (TimePassesIsEnabled)
2021 DebugTimer->stopTimer();
2026 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2027 unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
2028 if (!MAI->doesDwarfUsesInlineInfoSection())
2031 if (TimePassesIsEnabled)
2032 DebugTimer->startTimer();
2034 MDNode *Node = SP.getNode();
2035 DenseMap<MDNode *, SmallVector<DbgScope *, 8> >::iterator
2036 I = DbgConcreteScopeMap.find(Node);
2038 if (I == DbgConcreteScopeMap.end()) {
2039 // FIXME: Can this situation actually happen? And if so, should it?
2040 if (TimePassesIsEnabled)
2041 DebugTimer->stopTimer();
2046 SmallVector<DbgScope *, 8> &Scopes = I->second;
2047 if (Scopes.empty()) {
2048 // Returned ID is 0 if this is unbalanced "end of inlined
2049 // scope". This could happen if optimizer eats dbg intrinsics
2050 // or "beginning of inlined scope" is not recoginized due to
2051 // missing location info. In such cases, ignore this region.end.
2055 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
2056 unsigned ID = MMI->NextLabelID();
2057 MMI->RecordUsedDbgLabel(ID);
2058 Scope->setEndLabelID(ID);
2060 if (TimePassesIsEnabled)
2061 DebugTimer->stopTimer();
2066 //===----------------------------------------------------------------------===//
2068 //===----------------------------------------------------------------------===//
2070 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2072 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2073 // Get the children.
2074 const std::vector<DIE *> &Children = Die->getChildren();
2076 // If not last sibling and has children then add sibling offset attribute.
2077 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2079 // Record the abbreviation.
2080 AssignAbbrevNumber(Die->getAbbrev());
2082 // Get the abbreviation for this DIE.
2083 unsigned AbbrevNumber = Die->getAbbrevNumber();
2084 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2087 Die->setOffset(Offset);
2089 // Start the size with the size of abbreviation code.
2090 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2092 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2093 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2095 // Size the DIE attribute values.
2096 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2097 // Size attribute value.
2098 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2100 // Size the DIE children if any.
2101 if (!Children.empty()) {
2102 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2103 "Children flag not set");
2105 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2106 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2108 // End of children marker.
2109 Offset += sizeof(int8_t);
2112 Die->setSize(Offset - Die->getOffset());
2116 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2118 void DwarfDebug::SizeAndOffsets() {
2119 // Compute size of compile unit header.
2120 static unsigned Offset =
2121 sizeof(int32_t) + // Length of Compilation Unit Info
2122 sizeof(int16_t) + // DWARF version number
2123 sizeof(int32_t) + // Offset Into Abbrev. Section
2124 sizeof(int8_t); // Pointer Size (in bytes)
2126 SizeAndOffsetDie(ModuleCU->getDie(), Offset, true);
2127 CompileUnitOffsets[ModuleCU] = 0;
2130 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2131 /// tools to recognize the object file contains Dwarf information.
2132 void DwarfDebug::EmitInitial() {
2133 // Check to see if we already emitted intial headers.
2134 if (didInitial) return;
2137 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2139 // Dwarf sections base addresses.
2140 if (MAI->doesDwarfRequireFrameSection()) {
2141 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2142 EmitLabel("section_debug_frame", 0);
2145 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2146 EmitLabel("section_info", 0);
2147 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2148 EmitLabel("section_abbrev", 0);
2149 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2150 EmitLabel("section_aranges", 0);
2152 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2153 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2154 EmitLabel("section_macinfo", 0);
2157 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2158 EmitLabel("section_line", 0);
2159 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2160 EmitLabel("section_loc", 0);
2161 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2162 EmitLabel("section_pubnames", 0);
2163 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2164 EmitLabel("section_str", 0);
2165 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2166 EmitLabel("section_ranges", 0);
2168 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2169 EmitLabel("text_begin", 0);
2170 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2171 EmitLabel("data_begin", 0);
2174 /// EmitDIE - Recusively Emits a debug information entry.
2176 void DwarfDebug::EmitDIE(DIE *Die) {
2177 // Get the abbreviation for this DIE.
2178 unsigned AbbrevNumber = Die->getAbbrevNumber();
2179 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2183 // Emit the code (index) for the abbreviation.
2184 Asm->EmitULEB128Bytes(AbbrevNumber);
2186 if (Asm->isVerbose())
2187 Asm->EOL(std::string("Abbrev [" +
2188 utostr(AbbrevNumber) +
2189 "] 0x" + utohexstr(Die->getOffset()) +
2190 ":0x" + utohexstr(Die->getSize()) + " " +
2191 dwarf::TagString(Abbrev->getTag())));
2195 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2196 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2198 // Emit the DIE attribute values.
2199 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2200 unsigned Attr = AbbrevData[i].getAttribute();
2201 unsigned Form = AbbrevData[i].getForm();
2202 assert(Form && "Too many attributes for DIE (check abbreviation)");
2205 case dwarf::DW_AT_sibling:
2206 Asm->EmitInt32(Die->SiblingOffset());
2208 case dwarf::DW_AT_abstract_origin: {
2209 DIEEntry *E = cast<DIEEntry>(Values[i]);
2210 DIE *Origin = E->getEntry();
2212 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
2213 Origin->getOffset();
2215 Asm->EmitInt32(Addr);
2219 // Emit an attribute using the defined form.
2220 Values[i]->EmitValue(this, Form);
2224 Asm->EOL(dwarf::AttributeString(Attr));
2227 // Emit the DIE children if any.
2228 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2229 const std::vector<DIE *> &Children = Die->getChildren();
2231 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2232 EmitDIE(Children[j]);
2234 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2238 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2240 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
2241 DIE *Die = Unit->getDie();
2243 // Emit the compile units header.
2244 EmitLabel("info_begin", Unit->getID());
2246 // Emit size of content not including length itself
2247 unsigned ContentSize = Die->getSize() +
2248 sizeof(int16_t) + // DWARF version number
2249 sizeof(int32_t) + // Offset Into Abbrev. Section
2250 sizeof(int8_t) + // Pointer Size (in bytes)
2251 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2253 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2254 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2255 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2256 Asm->EOL("Offset Into Abbrev. Section");
2257 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2260 // FIXME - extra padding for gdb bug.
2261 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2262 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2263 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2264 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2265 EmitLabel("info_end", Unit->getID());
2270 void DwarfDebug::EmitDebugInfo() {
2271 // Start debug info section.
2272 Asm->OutStreamer.SwitchSection(
2273 Asm->getObjFileLowering().getDwarfInfoSection());
2275 EmitDebugInfoPerCU(ModuleCU);
2278 /// EmitAbbreviations - Emit the abbreviation section.
2280 void DwarfDebug::EmitAbbreviations() const {
2281 // Check to see if it is worth the effort.
2282 if (!Abbreviations.empty()) {
2283 // Start the debug abbrev section.
2284 Asm->OutStreamer.SwitchSection(
2285 Asm->getObjFileLowering().getDwarfAbbrevSection());
2287 EmitLabel("abbrev_begin", 0);
2289 // For each abbrevation.
2290 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2291 // Get abbreviation data
2292 const DIEAbbrev *Abbrev = Abbreviations[i];
2294 // Emit the abbrevations code (base 1 index.)
2295 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2296 Asm->EOL("Abbreviation Code");
2298 // Emit the abbreviations data.
2304 // Mark end of abbreviations.
2305 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2307 EmitLabel("abbrev_end", 0);
2312 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2313 /// the line matrix.
2315 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2316 // Define last address of section.
2317 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2318 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2319 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2320 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2322 // Mark end of matrix.
2323 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2324 Asm->EmitULEB128Bytes(1); Asm->EOL();
2325 Asm->EmitInt8(1); Asm->EOL();
2328 /// EmitDebugLines - Emit source line information.
2330 void DwarfDebug::EmitDebugLines() {
2331 // If the target is using .loc/.file, the assembler will be emitting the
2332 // .debug_line table automatically.
2333 if (MAI->hasDotLocAndDotFile())
2336 // Minimum line delta, thus ranging from -10..(255-10).
2337 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2338 // Maximum line delta, thus ranging from -10..(255-10).
2339 const int MaxLineDelta = 255 + MinLineDelta;
2341 // Start the dwarf line section.
2342 Asm->OutStreamer.SwitchSection(
2343 Asm->getObjFileLowering().getDwarfLineSection());
2345 // Construct the section header.
2346 EmitDifference("line_end", 0, "line_begin", 0, true);
2347 Asm->EOL("Length of Source Line Info");
2348 EmitLabel("line_begin", 0);
2350 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2352 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2353 Asm->EOL("Prolog Length");
2354 EmitLabel("line_prolog_begin", 0);
2356 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2358 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2360 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2362 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2364 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2366 // Line number standard opcode encodings argument count
2367 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2368 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2369 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2370 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2371 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2372 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2373 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2374 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2375 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2377 // Emit directories.
2378 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2379 Asm->EmitString(getSourceDirectoryName(DI));
2380 Asm->EOL("Directory");
2383 Asm->EmitInt8(0); Asm->EOL("End of directories");
2386 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2387 // Remember source id starts at 1.
2388 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2389 Asm->EmitString(getSourceFileName(Id.second));
2391 Asm->EmitULEB128Bytes(Id.first);
2392 Asm->EOL("Directory #");
2393 Asm->EmitULEB128Bytes(0);
2394 Asm->EOL("Mod date");
2395 Asm->EmitULEB128Bytes(0);
2396 Asm->EOL("File size");
2399 Asm->EmitInt8(0); Asm->EOL("End of files");
2401 EmitLabel("line_prolog_end", 0);
2403 // A sequence for each text section.
2404 unsigned SecSrcLinesSize = SectionSourceLines.size();
2406 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2407 // Isolate current sections line info.
2408 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2410 /*if (Asm->isVerbose()) {
2411 const MCSection *S = SectionMap[j + 1];
2412 O << '\t' << MAI->getCommentString() << " Section"
2413 << S->getName() << '\n';
2417 // Dwarf assumes we start with first line of first source file.
2418 unsigned Source = 1;
2421 // Construct rows of the address, source, line, column matrix.
2422 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2423 const SrcLineInfo &LineInfo = LineInfos[i];
2424 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2425 if (!LabelID) continue;
2427 if (LineInfo.getLine() == 0) continue;
2429 if (!Asm->isVerbose())
2432 std::pair<unsigned, unsigned> SourceID =
2433 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2434 O << '\t' << MAI->getCommentString() << ' '
2435 << getSourceDirectoryName(SourceID.first) << ' '
2436 << getSourceFileName(SourceID.second)
2437 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2440 // Define the line address.
2441 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2442 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2443 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2444 EmitReference("label", LabelID); Asm->EOL("Location label");
2446 // If change of source, then switch to the new source.
2447 if (Source != LineInfo.getSourceID()) {
2448 Source = LineInfo.getSourceID();
2449 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2450 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2453 // If change of line.
2454 if (Line != LineInfo.getLine()) {
2455 // Determine offset.
2456 int Offset = LineInfo.getLine() - Line;
2457 int Delta = Offset - MinLineDelta;
2460 Line = LineInfo.getLine();
2462 // If delta is small enough and in range...
2463 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2464 // ... then use fast opcode.
2465 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2467 // ... otherwise use long hand.
2468 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2469 Asm->EOL("DW_LNS_advance_line");
2470 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2471 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2474 // Copy the previous row (different address or source)
2475 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2479 EmitEndOfLineMatrix(j + 1);
2482 if (SecSrcLinesSize == 0)
2483 // Because we're emitting a debug_line section, we still need a line
2484 // table. The linker and friends expect it to exist. If there's nothing to
2485 // put into it, emit an empty table.
2486 EmitEndOfLineMatrix(1);
2488 EmitLabel("line_end", 0);
2492 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2494 void DwarfDebug::EmitCommonDebugFrame() {
2495 if (!MAI->doesDwarfRequireFrameSection())
2499 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2500 TargetFrameInfo::StackGrowsUp ?
2501 TD->getPointerSize() : -TD->getPointerSize();
2503 // Start the dwarf frame section.
2504 Asm->OutStreamer.SwitchSection(
2505 Asm->getObjFileLowering().getDwarfFrameSection());
2507 EmitLabel("debug_frame_common", 0);
2508 EmitDifference("debug_frame_common_end", 0,
2509 "debug_frame_common_begin", 0, true);
2510 Asm->EOL("Length of Common Information Entry");
2512 EmitLabel("debug_frame_common_begin", 0);
2513 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2514 Asm->EOL("CIE Identifier Tag");
2515 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2516 Asm->EOL("CIE Version");
2517 Asm->EmitString("");
2518 Asm->EOL("CIE Augmentation");
2519 Asm->EmitULEB128Bytes(1);
2520 Asm->EOL("CIE Code Alignment Factor");
2521 Asm->EmitSLEB128Bytes(stackGrowth);
2522 Asm->EOL("CIE Data Alignment Factor");
2523 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2524 Asm->EOL("CIE RA Column");
2526 std::vector<MachineMove> Moves;
2527 RI->getInitialFrameState(Moves);
2529 EmitFrameMoves(NULL, 0, Moves, false);
2531 Asm->EmitAlignment(2, 0, 0, false);
2532 EmitLabel("debug_frame_common_end", 0);
2537 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2540 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2541 if (!MAI->doesDwarfRequireFrameSection())
2544 // Start the dwarf frame section.
2545 Asm->OutStreamer.SwitchSection(
2546 Asm->getObjFileLowering().getDwarfFrameSection());
2548 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2549 "debug_frame_begin", DebugFrameInfo.Number, true);
2550 Asm->EOL("Length of Frame Information Entry");
2552 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2554 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2556 Asm->EOL("FDE CIE offset");
2558 EmitReference("func_begin", DebugFrameInfo.Number);
2559 Asm->EOL("FDE initial location");
2560 EmitDifference("func_end", DebugFrameInfo.Number,
2561 "func_begin", DebugFrameInfo.Number);
2562 Asm->EOL("FDE address range");
2564 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2567 Asm->EmitAlignment(2, 0, 0, false);
2568 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2573 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2574 EmitDifference("pubnames_end", Unit->getID(),
2575 "pubnames_begin", Unit->getID(), true);
2576 Asm->EOL("Length of Public Names Info");
2578 EmitLabel("pubnames_begin", Unit->getID());
2580 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2582 EmitSectionOffset("info_begin", "section_info",
2583 Unit->getID(), 0, true, false);
2584 Asm->EOL("Offset of Compilation Unit Info");
2586 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2588 Asm->EOL("Compilation Unit Length");
2590 StringMap<DIE*> &Globals = Unit->getGlobals();
2591 for (StringMap<DIE*>::const_iterator
2592 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2593 const char *Name = GI->getKeyData();
2594 DIE * Entity = GI->second;
2596 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2597 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2600 Asm->EmitInt32(0); Asm->EOL("End Mark");
2601 EmitLabel("pubnames_end", Unit->getID());
2606 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2608 void DwarfDebug::EmitDebugPubNames() {
2609 // Start the dwarf pubnames section.
2610 Asm->OutStreamer.SwitchSection(
2611 Asm->getObjFileLowering().getDwarfPubNamesSection());
2613 EmitDebugPubNamesPerCU(ModuleCU);
2616 /// EmitDebugStr - Emit visible names into a debug str section.
2618 void DwarfDebug::EmitDebugStr() {
2619 // Check to see if it is worth the effort.
2620 if (!StringPool.empty()) {
2621 // Start the dwarf str section.
2622 Asm->OutStreamer.SwitchSection(
2623 Asm->getObjFileLowering().getDwarfStrSection());
2625 // For each of strings in the string pool.
2626 for (unsigned StringID = 1, N = StringPool.size();
2627 StringID <= N; ++StringID) {
2628 // Emit a label for reference from debug information entries.
2629 EmitLabel("string", StringID);
2631 // Emit the string itself.
2632 const std::string &String = StringPool[StringID];
2633 Asm->EmitString(String); Asm->EOL();
2640 /// EmitDebugLoc - Emit visible names into a debug loc section.
2642 void DwarfDebug::EmitDebugLoc() {
2643 // Start the dwarf loc section.
2644 Asm->OutStreamer.SwitchSection(
2645 Asm->getObjFileLowering().getDwarfLocSection());
2649 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2651 void DwarfDebug::EmitDebugARanges() {
2652 // Start the dwarf aranges section.
2653 Asm->OutStreamer.SwitchSection(
2654 Asm->getObjFileLowering().getDwarfARangesSection());
2658 CompileUnit *Unit = GetBaseCompileUnit();
2660 // Don't include size of length
2661 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2663 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2665 EmitReference("info_begin", Unit->getID());
2666 Asm->EOL("Offset of Compilation Unit Info");
2668 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2670 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2672 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2673 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2676 EmitReference("text_begin", 0); Asm->EOL("Address");
2677 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2679 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2680 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2686 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2688 void DwarfDebug::EmitDebugRanges() {
2689 // Start the dwarf ranges section.
2690 Asm->OutStreamer.SwitchSection(
2691 Asm->getObjFileLowering().getDwarfRangesSection());
2695 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2697 void DwarfDebug::EmitDebugMacInfo() {
2698 if (const MCSection *LineInfo =
2699 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2700 // Start the dwarf macinfo section.
2701 Asm->OutStreamer.SwitchSection(LineInfo);
2706 /// EmitDebugInlineInfo - Emit inline info using following format.
2708 /// 1. length of section
2709 /// 2. Dwarf version number
2710 /// 3. address size.
2712 /// Entries (one "entry" for each function that was inlined):
2714 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2715 /// otherwise offset into __debug_str for regular function name.
2716 /// 2. offset into __debug_str section for regular function name.
2717 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2718 /// instances for the function.
2720 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2721 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2722 /// __debug_info section, and the low_pc is the starting address for the
2723 /// inlining instance.
2724 void DwarfDebug::EmitDebugInlineInfo() {
2725 if (!MAI->doesDwarfUsesInlineInfoSection())
2731 Asm->OutStreamer.SwitchSection(
2732 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2734 EmitDifference("debug_inlined_end", 1,
2735 "debug_inlined_begin", 1, true);
2736 Asm->EOL("Length of Debug Inlined Information Entry");
2738 EmitLabel("debug_inlined_begin", 1);
2740 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2741 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2743 for (DenseMap<MDNode *, SmallVector<unsigned, 4> >::iterator
2744 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2745 MDNode *Node = I->first;
2746 SmallVector<unsigned, 4> &Labels = I->second;
2747 DISubprogram SP(Node);
2748 const char *LName = SP.getLinkageName();
2749 const char *Name = SP.getName();
2752 Asm->EmitString(Name);
2754 // Skip special LLVM prefix that is used to inform the asm printer to not
2755 // emit usual symbol prefix before the symbol name. This happens for
2756 // Objective-C symbol names and symbol whose name is replaced using GCC's
2757 // __asm__ attribute.
2760 Asm->EmitString(LName);
2762 Asm->EOL("MIPS linkage name");
2764 Asm->EmitString(Name); Asm->EOL("Function name");
2766 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2768 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2769 LE = Labels.end(); LI != LE; ++LI) {
2770 DIE *SP = ModuleCU->getDieMapSlotFor(Node);
2771 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2773 if (TD->getPointerSize() == sizeof(int32_t))
2774 O << MAI->getData32bitsDirective();
2776 O << MAI->getData64bitsDirective();
2778 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2782 EmitLabel("debug_inlined_end", 1);