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 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Target/Mangler.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Target/TargetLoweringObjectFile.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Analysis/DebugInfo.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/System/Path.h"
44 static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
45 cl::desc("Print DbgScope information for each machine instruction"));
47 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
48 cl::desc("Disable debug info printing"));
51 const char *DWARFGroupName = "DWARF Emission";
52 const char *DbgTimerName = "DWARF Debug Writer";
53 } // end anonymous namespace
55 //===----------------------------------------------------------------------===//
57 /// Configuration values for initial hash set sizes (log2).
59 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
63 //===----------------------------------------------------------------------===//
64 /// CompileUnit - This dwarf writer support class manages information associate
65 /// with a source file.
67 /// ID - File identifier for source.
71 /// Die - Compile unit debug information entry.
73 const OwningPtr<DIE> CUDie;
75 /// IndexTyDie - An anonymous type for index type. Owned by CUDie.
78 /// GVToDieMap - Tracks the mapping of unit level debug informaton
79 /// variables to debug information entries.
80 /// FIXME : Rename GVToDieMap -> NodeToDieMap
81 DenseMap<MDNode *, DIE *> GVToDieMap;
83 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
84 /// descriptors to debug information entries using a DIEEntry proxy.
86 DenseMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
88 /// Globals - A map of globally visible named entities for this unit.
90 StringMap<DIE*> Globals;
92 /// GlobalTypes - A map of globally visible types for this unit.
94 StringMap<DIE*> GlobalTypes;
97 CompileUnit(unsigned I, DIE *D)
98 : ID(I), CUDie(D), IndexTyDie(0) {}
101 unsigned getID() const { return ID; }
102 DIE* getCUDie() const { return CUDie.get(); }
103 const StringMap<DIE*> &getGlobals() const { return Globals; }
104 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
106 /// hasContent - Return true if this compile unit has something to write out.
108 bool hasContent() const { return !CUDie->getChildren().empty(); }
110 /// addGlobal - Add a new global entity to the compile unit.
112 void addGlobal(StringRef Name, DIE *Die) { Globals[Name] = Die; }
114 /// addGlobalType - Add a new global type to the compile unit.
116 void addGlobalType(StringRef Name, DIE *Die) {
117 GlobalTypes[Name] = Die;
120 /// getDIE - Returns the debug information entry map slot for the
121 /// specified debug variable.
122 DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
124 /// insertDIE - Insert DIE into the map.
125 void insertDIE(MDNode *N, DIE *D) {
126 GVToDieMap.insert(std::make_pair(N, D));
129 /// getDIEEntry - Returns the debug information entry for the speciefied
131 DIEEntry *getDIEEntry(MDNode *N) {
132 DenseMap<MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
133 if (I == GVToDIEEntryMap.end())
138 /// insertDIEEntry - Insert debug information entry into the map.
139 void insertDIEEntry(MDNode *N, DIEEntry *E) {
140 GVToDIEEntryMap.insert(std::make_pair(N, E));
143 /// addDie - Adds or interns the DIE to the compile unit.
145 void addDie(DIE *Buffer) {
146 this->CUDie->addChild(Buffer);
149 // getIndexTyDie - Get an anonymous type for index type.
150 DIE *getIndexTyDie() {
154 // setIndexTyDie - Set D as anonymous type for index which can be reused
156 void setIndexTyDie(DIE *D) {
162 //===----------------------------------------------------------------------===//
163 /// DbgVariable - This class is used to track local variable information.
166 DIVariable Var; // Variable Descriptor.
167 unsigned FrameIndex; // Variable frame index.
168 const MachineInstr *DbgValueMInsn; // DBG_VALUE
169 // DbgValueLabel - DBG_VALUE is effective from this label.
170 MCSymbol *DbgValueLabel;
171 DbgVariable *const AbstractVar; // Abstract variable for this variable.
174 // AbsVar may be NULL.
175 DbgVariable(DIVariable V, unsigned I, DbgVariable *AbsVar)
176 : Var(V), FrameIndex(I), DbgValueMInsn(0),
177 DbgValueLabel(0), AbstractVar(AbsVar), TheDIE(0) {}
178 DbgVariable(DIVariable V, const MachineInstr *MI, DbgVariable *AbsVar)
179 : Var(V), FrameIndex(0), DbgValueMInsn(MI), DbgValueLabel(0),
180 AbstractVar(AbsVar), TheDIE(0)
184 DIVariable getVariable() const { return Var; }
185 unsigned getFrameIndex() const { return FrameIndex; }
186 const MachineInstr *getDbgValue() const { return DbgValueMInsn; }
187 MCSymbol *getDbgValueLabel() const { return DbgValueLabel; }
188 void setDbgValueLabel(MCSymbol *L) { DbgValueLabel = L; }
189 DbgVariable *getAbstractVariable() const { return AbstractVar; }
190 void setDIE(DIE *D) { TheDIE = D; }
191 DIE *getDIE() const { return TheDIE; }
194 //===----------------------------------------------------------------------===//
195 /// DbgRange - This is used to track range of instructions with identical
196 /// debug info scope.
198 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
200 //===----------------------------------------------------------------------===//
201 /// DbgScope - This class is used to track scope information.
204 DbgScope *Parent; // Parent to this scope.
205 DIDescriptor Desc; // Debug info descriptor for scope.
206 // Location at which this scope is inlined.
207 AssertingVH<MDNode> InlinedAtLocation;
208 bool AbstractScope; // Abstract Scope
209 const MachineInstr *LastInsn; // Last instruction of this scope.
210 const MachineInstr *FirstInsn; // First instruction of this scope.
211 unsigned DFSIn, DFSOut;
212 // Scopes defined in scope. Contents not owned.
213 SmallVector<DbgScope *, 4> Scopes;
214 // Variables declared in scope. Contents owned.
215 SmallVector<DbgVariable *, 8> Variables;
216 SmallVector<DbgRange, 4> Ranges;
217 // Private state for dump()
218 mutable unsigned IndentLevel;
220 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
221 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
222 LastInsn(0), FirstInsn(0),
223 DFSIn(0), DFSOut(0), IndentLevel(0) {}
227 DbgScope *getParent() const { return Parent; }
228 void setParent(DbgScope *P) { Parent = P; }
229 DIDescriptor getDesc() const { return Desc; }
230 MDNode *getInlinedAt() const { return InlinedAtLocation; }
231 MDNode *getScopeNode() const { return Desc.getNode(); }
232 const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
233 const SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
234 const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
236 /// openInsnRange - This scope covers instruction range starting from MI.
237 void openInsnRange(const MachineInstr *MI) {
242 Parent->openInsnRange(MI);
245 /// extendInsnRange - Extend the current instruction range covered by
247 void extendInsnRange(const MachineInstr *MI) {
248 assert (FirstInsn && "MI Range is not open!");
251 Parent->extendInsnRange(MI);
254 /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
255 /// until now. This is used when a new scope is encountered while walking
256 /// machine instructions.
257 void closeInsnRange(DbgScope *NewScope = NULL) {
258 assert (LastInsn && "Last insn missing!");
259 Ranges.push_back(DbgRange(FirstInsn, LastInsn));
262 // If Parent dominates NewScope then do not close Parent's instruction
264 if (Parent && (!NewScope || !Parent->dominates(NewScope)))
265 Parent->closeInsnRange(NewScope);
268 void setAbstractScope() { AbstractScope = true; }
269 bool isAbstractScope() const { return AbstractScope; }
271 // Depth First Search support to walk and mainpluate DbgScope hierarchy.
272 unsigned getDFSOut() const { return DFSOut; }
273 void setDFSOut(unsigned O) { DFSOut = O; }
274 unsigned getDFSIn() const { return DFSIn; }
275 void setDFSIn(unsigned I) { DFSIn = I; }
276 bool dominates(const DbgScope *S) {
279 if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
284 /// addScope - Add a scope to the scope.
286 void addScope(DbgScope *S) { Scopes.push_back(S); }
288 /// addVariable - Add a variable to the scope.
290 void addVariable(DbgVariable *V) { Variables.push_back(V); }
297 } // end llvm namespace
300 void DbgScope::dump() const {
301 raw_ostream &err = dbgs();
302 err.indent(IndentLevel);
303 MDNode *N = Desc.getNode();
306 err << "Abstract Scope\n";
310 err << "Children ...\n";
311 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
312 if (Scopes[i] != this)
319 DbgScope::~DbgScope() {
320 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
324 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
325 : Asm(A), MMI(Asm->MMI), ModuleCU(0),
326 AbbreviationsSet(InitAbbreviationsSetSize),
327 CurrentFnDbgScope(0), PrevLabel(NULL) {
328 NextStringPoolNumber = 0;
330 DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
331 DwarfStrSectionSym = TextSectionSym = 0;
332 DwarfDebugRangeSectionSym = 0;
333 FunctionBeginSym = 0;
334 if (TimePassesIsEnabled) {
335 NamedRegionTimer T(DbgTimerName, DWARFGroupName);
341 DwarfDebug::~DwarfDebug() {
342 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
343 DIEBlocks[j]->~DIEBlock();
346 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
347 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
348 if (Entry.first) return Entry.first;
350 Entry.second = NextStringPoolNumber++;
351 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
355 /// assignAbbrevNumber - Define a unique number for the abbreviation.
357 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
358 // Profile the node so that we can make it unique.
362 // Check the set for priors.
363 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
365 // If it's newly added.
366 if (InSet == &Abbrev) {
367 // Add to abbreviation list.
368 Abbreviations.push_back(&Abbrev);
370 // Assign the vector position + 1 as its number.
371 Abbrev.setNumber(Abbreviations.size());
373 // Assign existing abbreviation number.
374 Abbrev.setNumber(InSet->getNumber());
378 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
379 /// information entry.
380 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
381 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
385 /// addUInt - Add an unsigned integer attribute data and value.
387 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
388 unsigned Form, uint64_t Integer) {
389 if (!Form) Form = DIEInteger::BestForm(false, Integer);
390 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
391 Die->addValue(Attribute, Form, Value);
394 /// addSInt - Add an signed integer attribute data and value.
396 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
397 unsigned Form, int64_t Integer) {
398 if (!Form) Form = DIEInteger::BestForm(true, Integer);
399 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
400 Die->addValue(Attribute, Form, Value);
403 /// addString - Add a string attribute data and value. DIEString only
404 /// keeps string reference.
405 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
407 DIEValue *Value = new (DIEValueAllocator) DIEString(String);
408 Die->addValue(Attribute, Form, Value);
411 /// addLabel - Add a Dwarf label attribute data and value.
413 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
414 const MCSymbol *Label) {
415 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
416 Die->addValue(Attribute, Form, Value);
419 /// addDelta - Add a label delta attribute data and value.
421 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
422 const MCSymbol *Hi, const MCSymbol *Lo) {
423 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
424 Die->addValue(Attribute, Form, Value);
427 /// addDIEEntry - Add a DIE attribute data and value.
429 void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
431 Die->addValue(Attribute, Form, createDIEEntry(Entry));
435 /// addBlock - Add block data.
437 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
439 Block->ComputeSize(Asm);
440 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
441 Die->addValue(Attribute, Block->BestForm(), Block);
444 /// addSourceLine - Add location information to specified debug information
446 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
447 // If there is no compile unit specified, don't add a line #.
448 if (!V->getCompileUnit().Verify())
451 unsigned Line = V->getLineNumber();
452 unsigned FileID = GetOrCreateSourceID(V->getContext().getDirectory(),
453 V->getContext().getFilename());
454 assert(FileID && "Invalid file id");
455 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
456 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
459 /// addSourceLine - Add location information to specified debug information
461 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
462 // If there is no compile unit specified, don't add a line #.
463 if (!G->getCompileUnit().Verify())
466 unsigned Line = G->getLineNumber();
467 unsigned FileID = GetOrCreateSourceID(G->getContext().getDirectory(),
468 G->getContext().getFilename());
469 assert(FileID && "Invalid file id");
470 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
471 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
474 /// addSourceLine - Add location information to specified debug information
476 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
477 // If there is no compile unit specified, don't add a line #.
478 if (!SP->getCompileUnit().Verify())
480 // If the line number is 0, don't add it.
481 if (SP->getLineNumber() == 0)
484 unsigned Line = SP->getLineNumber();
485 if (!SP->getContext().Verify())
487 unsigned FileID = GetOrCreateSourceID(SP->getDirectory(),
489 assert(FileID && "Invalid file id");
490 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
491 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
494 /// addSourceLine - Add location information to specified debug information
496 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
497 // If there is no compile unit specified, don't add a line #.
498 DICompileUnit CU = Ty->getCompileUnit();
502 unsigned Line = Ty->getLineNumber();
503 if (!Ty->getContext().Verify())
505 unsigned FileID = GetOrCreateSourceID(Ty->getContext().getDirectory(),
506 Ty->getContext().getFilename());
507 assert(FileID && "Invalid file id");
508 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
509 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
512 /// addSourceLine - Add location information to specified debug information
514 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
515 // If there is no compile unit specified, don't add a line #.
516 if (!NS->getCompileUnit().Verify())
519 unsigned Line = NS->getLineNumber();
520 StringRef FN = NS->getFilename();
521 StringRef Dir = NS->getDirectory();
523 unsigned FileID = GetOrCreateSourceID(Dir, FN);
524 assert(FileID && "Invalid file id");
525 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
526 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
529 /* Byref variables, in Blocks, are declared by the programmer as
530 "SomeType VarName;", but the compiler creates a
531 __Block_byref_x_VarName struct, and gives the variable VarName
532 either the struct, or a pointer to the struct, as its type. This
533 is necessary for various behind-the-scenes things the compiler
534 needs to do with by-reference variables in blocks.
536 However, as far as the original *programmer* is concerned, the
537 variable should still have type 'SomeType', as originally declared.
539 The following function dives into the __Block_byref_x_VarName
540 struct to find the original type of the variable. This will be
541 passed back to the code generating the type for the Debug
542 Information Entry for the variable 'VarName'. 'VarName' will then
543 have the original type 'SomeType' in its debug information.
545 The original type 'SomeType' will be the type of the field named
546 'VarName' inside the __Block_byref_x_VarName struct.
548 NOTE: In order for this to not completely fail on the debugger
549 side, the Debug Information Entry for the variable VarName needs to
550 have a DW_AT_location that tells the debugger how to unwind through
551 the pointers and __Block_byref_x_VarName struct to find the actual
552 value of the variable. The function addBlockByrefType does this. */
554 /// Find the type the programmer originally declared the variable to be
555 /// and return that type.
557 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
560 unsigned tag = Ty.getTag();
562 if (tag == dwarf::DW_TAG_pointer_type) {
563 DIDerivedType DTy = DIDerivedType(Ty.getNode());
564 subType = DTy.getTypeDerivedFrom();
567 DICompositeType blockStruct = DICompositeType(subType.getNode());
568 DIArray Elements = blockStruct.getTypeArray();
570 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
571 DIDescriptor Element = Elements.getElement(i);
572 DIDerivedType DT = DIDerivedType(Element.getNode());
573 if (Name == DT.getName())
574 return (DT.getTypeDerivedFrom());
580 /// addComplexAddress - Start with the address based on the location provided,
581 /// and generate the DWARF information necessary to find the actual variable
582 /// given the extra address information encoded in the DIVariable, starting from
583 /// the starting location. Add the DWARF information to the die.
585 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
587 const MachineLocation &Location) {
588 const DIVariable &VD = DV->getVariable();
589 DIType Ty = VD.getType();
591 // Decode the original location, and use that as the start of the byref
592 // variable's location.
593 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
594 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
595 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
597 if (Location.isReg()) {
599 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
601 Reg = Reg - dwarf::DW_OP_reg0;
602 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
603 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
607 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
609 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
610 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
613 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
616 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
617 uint64_t Element = VD.getAddrElement(i);
619 if (Element == DIFactory::OpPlus) {
620 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
621 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
622 } else if (Element == DIFactory::OpDeref) {
623 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
624 } else llvm_unreachable("unknown DIFactory Opcode");
627 // Now attach the location information to the DIE.
628 addBlock(Die, Attribute, 0, Block);
631 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
632 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
633 gives the variable VarName either the struct, or a pointer to the struct, as
634 its type. This is necessary for various behind-the-scenes things the
635 compiler needs to do with by-reference variables in Blocks.
637 However, as far as the original *programmer* is concerned, the variable
638 should still have type 'SomeType', as originally declared.
640 The function getBlockByrefType dives into the __Block_byref_x_VarName
641 struct to find the original type of the variable, which is then assigned to
642 the variable's Debug Information Entry as its real type. So far, so good.
643 However now the debugger will expect the variable VarName to have the type
644 SomeType. So we need the location attribute for the variable to be an
645 expression that explains to the debugger how to navigate through the
646 pointers and struct to find the actual variable of type SomeType.
648 The following function does just that. We start by getting
649 the "normal" location for the variable. This will be the location
650 of either the struct __Block_byref_x_VarName or the pointer to the
651 struct __Block_byref_x_VarName.
653 The struct will look something like:
655 struct __Block_byref_x_VarName {
657 struct __Block_byref_x_VarName *forwarding;
658 ... <various other fields>
660 ... <maybe more fields>
663 If we are given the struct directly (as our starting point) we
664 need to tell the debugger to:
666 1). Add the offset of the forwarding field.
668 2). Follow that pointer to get the real __Block_byref_x_VarName
669 struct to use (the real one may have been copied onto the heap).
671 3). Add the offset for the field VarName, to find the actual variable.
673 If we started with a pointer to the struct, then we need to
674 dereference that pointer first, before the other steps.
675 Translating this into DWARF ops, we will need to append the following
676 to the current location description for the variable:
678 DW_OP_deref -- optional, if we start with a pointer
679 DW_OP_plus_uconst <forward_fld_offset>
681 DW_OP_plus_uconst <varName_fld_offset>
683 That is what this function does. */
685 /// addBlockByrefAddress - Start with the address based on the location
686 /// provided, and generate the DWARF information necessary to find the
687 /// actual Block variable (navigating the Block struct) based on the
688 /// starting location. Add the DWARF information to the die. For
689 /// more information, read large comment just above here.
691 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
693 const MachineLocation &Location) {
694 const DIVariable &VD = DV->getVariable();
695 DIType Ty = VD.getType();
697 unsigned Tag = Ty.getTag();
698 bool isPointer = false;
700 StringRef varName = VD.getName();
702 if (Tag == dwarf::DW_TAG_pointer_type) {
703 DIDerivedType DTy = DIDerivedType(Ty.getNode());
704 TmpTy = DTy.getTypeDerivedFrom();
708 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
710 // Find the __forwarding field and the variable field in the __Block_byref
712 DIArray Fields = blockStruct.getTypeArray();
713 DIDescriptor varField = DIDescriptor();
714 DIDescriptor forwardingField = DIDescriptor();
716 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
717 DIDescriptor Element = Fields.getElement(i);
718 DIDerivedType DT = DIDerivedType(Element.getNode());
719 StringRef fieldName = DT.getName();
720 if (fieldName == "__forwarding")
721 forwardingField = Element;
722 else if (fieldName == varName)
726 // Get the offsets for the forwarding field and the variable field.
727 unsigned forwardingFieldOffset =
728 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
729 unsigned varFieldOffset =
730 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
732 // Decode the original location, and use that as the start of the byref
733 // variable's location.
734 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
735 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
736 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
738 if (Location.isReg()) {
740 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
742 Reg = Reg - dwarf::DW_OP_reg0;
743 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
744 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
748 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
750 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
751 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
754 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
757 // If we started with a pointer to the __Block_byref... struct, then
758 // the first thing we need to do is dereference the pointer (DW_OP_deref).
760 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
762 // Next add the offset for the '__forwarding' field:
763 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
764 // adding the offset if it's 0.
765 if (forwardingFieldOffset > 0) {
766 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
767 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
770 // Now dereference the __forwarding field to get to the real __Block_byref
771 // struct: DW_OP_deref.
772 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
774 // Now that we've got the real __Block_byref... struct, add the offset
775 // for the variable's field to get to the location of the actual variable:
776 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
777 if (varFieldOffset > 0) {
778 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
779 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
782 // Now attach the location information to the DIE.
783 addBlock(Die, Attribute, 0, Block);
786 /// addAddress - Add an address attribute to a die based on the location
788 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
789 const MachineLocation &Location) {
790 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
791 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
792 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
794 if (Location.isReg()) {
796 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
798 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
799 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
803 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
805 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
806 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
809 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
812 addBlock(Die, Attribute, 0, Block);
815 /// addToContextOwner - Add Die into the list of its context owner's children.
816 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
817 if (Context.isType()) {
818 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
819 ContextDIE->addChild(Die);
820 } else if (Context.isNameSpace()) {
821 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
822 ContextDIE->addChild(Die);
823 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
824 ContextDIE->addChild(Die);
826 ModuleCU->addDie(Die);
829 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
831 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
832 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
837 TyDIE = new DIE(dwarf::DW_TAG_base_type);
838 ModuleCU->insertDIE(Ty.getNode(), TyDIE);
839 if (Ty.isBasicType())
840 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
841 else if (Ty.isCompositeType())
842 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
844 assert(Ty.isDerivedType() && "Unknown kind of DIType");
845 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
848 addToContextOwner(TyDIE, Ty.getContext());
852 /// addType - Add a new type attribute to the specified entity.
853 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
857 // Check for pre-existence.
858 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
859 // If it exists then use the existing value.
861 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
866 DIE *Buffer = getOrCreateTypeDIE(Ty);
869 Entry = createDIEEntry(Buffer);
870 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
872 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
875 /// constructTypeDIE - Construct basic type die from DIBasicType.
876 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
877 // Get core information.
878 StringRef Name = BTy.getName();
879 Buffer.setTag(dwarf::DW_TAG_base_type);
880 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
883 // Add name if not anonymous or intermediate type.
885 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
886 uint64_t Size = BTy.getSizeInBits() >> 3;
887 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
890 /// constructTypeDIE - Construct derived type die from DIDerivedType.
891 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
892 // Get core information.
893 StringRef Name = DTy.getName();
894 uint64_t Size = DTy.getSizeInBits() >> 3;
895 unsigned Tag = DTy.getTag();
897 // FIXME - Workaround for templates.
898 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
902 // Map to main type, void will not have a type.
903 DIType FromTy = DTy.getTypeDerivedFrom();
904 addType(&Buffer, FromTy);
906 // Add name if not anonymous or intermediate type.
908 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
910 // Add size if non-zero (derived types might be zero-sized.)
912 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
914 // Add source line info if available and TyDesc is not a forward declaration.
915 if (!DTy.isForwardDecl())
916 addSourceLine(&Buffer, &DTy);
919 /// constructTypeDIE - Construct type DIE from DICompositeType.
920 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
921 // Get core information.
922 StringRef Name = CTy.getName();
924 uint64_t Size = CTy.getSizeInBits() >> 3;
925 unsigned Tag = CTy.getTag();
929 case dwarf::DW_TAG_vector_type:
930 case dwarf::DW_TAG_array_type:
931 constructArrayTypeDIE(Buffer, &CTy);
933 case dwarf::DW_TAG_enumeration_type: {
934 DIArray Elements = CTy.getTypeArray();
936 // Add enumerators to enumeration type.
937 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
939 DIDescriptor Enum(Elements.getElement(i).getNode());
940 if (Enum.isEnumerator()) {
941 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode()));
942 Buffer.addChild(ElemDie);
947 case dwarf::DW_TAG_subroutine_type: {
949 DIArray Elements = CTy.getTypeArray();
950 DIDescriptor RTy = Elements.getElement(0);
951 addType(&Buffer, DIType(RTy.getNode()));
953 // Add prototype flag.
954 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
957 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
958 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
959 DIDescriptor Ty = Elements.getElement(i);
960 addType(Arg, DIType(Ty.getNode()));
961 Buffer.addChild(Arg);
965 case dwarf::DW_TAG_structure_type:
966 case dwarf::DW_TAG_union_type:
967 case dwarf::DW_TAG_class_type: {
968 // Add elements to structure type.
969 DIArray Elements = CTy.getTypeArray();
971 // A forward struct declared type may not have elements available.
972 unsigned N = Elements.getNumElements();
976 // Add elements to structure type.
977 for (unsigned i = 0; i < N; ++i) {
978 DIDescriptor Element = Elements.getElement(i);
980 if (Element.isSubprogram())
981 ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
982 else if (Element.isVariable()) {
983 DIVariable DV(Element.getNode());
984 ElemDie = new DIE(dwarf::DW_TAG_variable);
985 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
987 addType(ElemDie, DV.getType());
988 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
989 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
990 addSourceLine(ElemDie, &DV);
991 } else if (Element.isDerivedType())
992 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
995 Buffer.addChild(ElemDie);
998 if (CTy.isAppleBlockExtension())
999 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1001 unsigned RLang = CTy.getRunTimeLang();
1003 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1004 dwarf::DW_FORM_data1, RLang);
1006 DICompositeType ContainingType = CTy.getContainingType();
1007 if (DIDescriptor(ContainingType.getNode()).isCompositeType())
1008 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1009 getOrCreateTypeDIE(DIType(ContainingType.getNode())));
1016 // Add name if not anonymous or intermediate type.
1018 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1020 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
1021 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1022 // Add size if non-zero (derived types might be zero-sized.)
1024 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1026 // Add zero size if it is not a forward declaration.
1027 if (CTy.isForwardDecl())
1028 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1030 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1033 // Add source line info if available.
1034 if (!CTy.isForwardDecl())
1035 addSourceLine(&Buffer, &CTy);
1039 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1040 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1041 int64_t L = SR.getLo();
1042 int64_t H = SR.getHi();
1043 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1045 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1047 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1048 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1050 Buffer.addChild(DW_Subrange);
1053 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1054 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1055 DICompositeType *CTy) {
1056 Buffer.setTag(dwarf::DW_TAG_array_type);
1057 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1058 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1060 // Emit derived type.
1061 addType(&Buffer, CTy->getTypeDerivedFrom());
1062 DIArray Elements = CTy->getTypeArray();
1064 // Get an anonymous type for index type.
1065 DIE *IdxTy = ModuleCU->getIndexTyDie();
1067 // Construct an anonymous type for index type.
1068 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1069 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1070 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1071 dwarf::DW_ATE_signed);
1072 ModuleCU->addDie(IdxTy);
1073 ModuleCU->setIndexTyDie(IdxTy);
1076 // Add subranges to array type.
1077 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1078 DIDescriptor Element = Elements.getElement(i);
1079 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1080 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1084 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1085 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1086 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1087 StringRef Name = ETy.getName();
1088 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1089 int64_t Value = ETy.getEnumValue();
1090 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1094 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1095 /// printer to not emit usual symbol prefix before the symbol name is used then
1096 /// return linkage name after skipping this special LLVM prefix.
1097 static StringRef getRealLinkageName(StringRef LinkageName) {
1099 if (LinkageName.startswith(StringRef(&One, 1)))
1100 return LinkageName.substr(1);
1104 /// createGlobalVariableDIE - Create new DIE using GV.
1105 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1106 // If the global variable was optmized out then no need to create debug info
1108 if (!GV.getGlobal()) return NULL;
1109 if (GV.getDisplayName().empty()) return NULL;
1111 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1112 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1113 GV.getDisplayName());
1115 StringRef LinkageName = GV.getLinkageName();
1116 if (!LinkageName.empty())
1117 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1118 getRealLinkageName(LinkageName));
1120 addType(GVDie, GV.getType());
1121 if (!GV.isLocalToUnit())
1122 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1123 addSourceLine(GVDie, &GV);
1128 /// createMemberDIE - Create new member DIE.
1129 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1130 DIE *MemberDie = new DIE(DT.getTag());
1131 StringRef Name = DT.getName();
1133 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1135 addType(MemberDie, DT.getTypeDerivedFrom());
1137 addSourceLine(MemberDie, &DT);
1139 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1140 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1142 uint64_t Size = DT.getSizeInBits();
1143 uint64_t FieldSize = DT.getOriginalTypeSize();
1145 if (Size != FieldSize) {
1147 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1148 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1150 uint64_t Offset = DT.getOffsetInBits();
1151 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1152 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1153 uint64_t FieldOffset = (HiMark - FieldSize);
1154 Offset -= FieldOffset;
1156 // Maybe we need to work from the other end.
1157 if (Asm->getTargetData().isLittleEndian())
1158 Offset = FieldSize - (Offset + Size);
1159 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1161 // Here WD_AT_data_member_location points to the anonymous
1162 // field that includes this bit field.
1163 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1166 // This is not a bitfield.
1167 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1169 if (DT.getTag() == dwarf::DW_TAG_inheritance
1170 && DT.isVirtual()) {
1172 // For C++, virtual base classes are not at fixed offset. Use following
1173 // expression to extract appropriate offset from vtable.
1174 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1176 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1177 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1178 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1179 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1180 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1181 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1182 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1183 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1185 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1188 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1190 if (DT.isProtected())
1191 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1192 dwarf::DW_ACCESS_protected);
1193 else if (DT.isPrivate())
1194 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1195 dwarf::DW_ACCESS_private);
1196 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1197 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1198 dwarf::DW_ACCESS_public);
1200 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1201 dwarf::DW_VIRTUALITY_virtual);
1205 /// createSubprogramDIE - Create new DIE using SP.
1206 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1207 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1211 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1212 // Constructors and operators for anonymous aggregates do not have names.
1213 if (!SP.getName().empty())
1214 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1216 StringRef LinkageName = SP.getLinkageName();
1217 if (!LinkageName.empty())
1218 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1219 getRealLinkageName(LinkageName));
1221 addSourceLine(SPDie, &SP);
1223 // Add prototyped tag, if C or ObjC.
1224 unsigned Lang = SP.getCompileUnit().getLanguage();
1225 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1226 Lang == dwarf::DW_LANG_ObjC)
1227 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1230 DICompositeType SPTy = SP.getType();
1231 DIArray Args = SPTy.getTypeArray();
1232 unsigned SPTag = SPTy.getTag();
1234 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1235 addType(SPDie, SPTy);
1237 addType(SPDie, DIType(Args.getElement(0).getNode()));
1239 unsigned VK = SP.getVirtuality();
1241 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1242 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1243 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1244 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1245 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1246 ContainingTypeMap.insert(std::make_pair(SPDie,
1247 SP.getContainingType().getNode()));
1250 if (MakeDecl || !SP.isDefinition()) {
1251 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1253 // Add arguments. Do not add arguments for subprogram definition. They will
1254 // be handled while processing variables.
1255 DICompositeType SPTy = SP.getType();
1256 DIArray Args = SPTy.getTypeArray();
1257 unsigned SPTag = SPTy.getTag();
1259 if (SPTag == dwarf::DW_TAG_subroutine_type)
1260 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1261 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1262 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1264 if (ATy.isArtificial())
1265 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1266 SPDie->addChild(Arg);
1270 if (SP.isArtificial())
1271 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1273 // DW_TAG_inlined_subroutine may refer to this DIE.
1274 ModuleCU->insertDIE(SP.getNode(), SPDie);
1276 if (!DisableFramePointerElim(*Asm->MF))
1277 addUInt(SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr, dwarf::DW_FORM_flag, 1);
1282 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1283 assert(N && "Invalid Scope encoding!");
1285 DbgScope *AScope = AbstractScopes.lookup(N);
1289 DbgScope *Parent = NULL;
1291 DIDescriptor Scope(N);
1292 if (Scope.isLexicalBlock()) {
1293 DILexicalBlock DB(N);
1294 DIDescriptor ParentDesc = DB.getContext();
1295 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1298 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1301 Parent->addScope(AScope);
1302 AScope->setAbstractScope();
1303 AbstractScopes[N] = AScope;
1304 if (DIDescriptor(N).isSubprogram())
1305 AbstractScopesList.push_back(AScope);
1309 /// isSubprogramContext - Return true if Context is either a subprogram
1310 /// or another context nested inside a subprogram.
1311 static bool isSubprogramContext(MDNode *Context) {
1314 DIDescriptor D(Context);
1315 if (D.isSubprogram())
1318 return isSubprogramContext(DIType(Context).getContext().getNode());
1322 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1323 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1324 /// If there are global variables in this scope then create and insert
1325 /// DIEs for these variables.
1326 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1327 DIE *SPDie = ModuleCU->getDIE(SPNode);
1328 assert(SPDie && "Unable to find subprogram DIE!");
1329 DISubprogram SP(SPNode);
1331 // There is not any need to generate specification DIE for a function
1332 // defined at compile unit level. If a function is defined inside another
1333 // function then gdb prefers the definition at top level and but does not
1334 // expect specification DIE in parent function. So avoid creating
1335 // specification DIE for a function defined inside a function.
1336 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1337 !SP.getContext().isFile() &&
1338 !isSubprogramContext(SP.getContext().getNode())) {
1339 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1342 DICompositeType SPTy = SP.getType();
1343 DIArray Args = SPTy.getTypeArray();
1344 unsigned SPTag = SPTy.getTag();
1345 if (SPTag == dwarf::DW_TAG_subroutine_type)
1346 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1347 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1348 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1350 if (ATy.isArtificial())
1351 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1352 SPDie->addChild(Arg);
1354 DIE *SPDeclDie = SPDie;
1355 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1356 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1358 ModuleCU->addDie(SPDie);
1361 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1362 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1363 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1364 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1365 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1366 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1367 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1369 if (!DISubprogram(SPNode).isLocalToUnit())
1370 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1375 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1376 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1377 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1379 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1380 if (Scope->isAbstractScope())
1383 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1387 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1388 if (Ranges.size() > 1) {
1389 // .debug_range section has not been laid out yet. Emit offset in
1390 // .debug_range as a uint, size 4, for now. emitDIE will handle
1391 // DW_AT_ranges appropriately.
1392 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1393 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1394 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1395 RE = Ranges.end(); RI != RE; ++RI) {
1396 DebugRangeSymbols.push_back(LabelsBeforeInsn.lookup(RI->first));
1397 DebugRangeSymbols.push_back(LabelsAfterInsn.lookup(RI->second));
1399 DebugRangeSymbols.push_back(NULL);
1400 DebugRangeSymbols.push_back(NULL);
1404 MCSymbol *Start = LabelsBeforeInsn.lookup(RI->first);
1405 MCSymbol *End = LabelsAfterInsn.lookup(RI->second);
1407 if (Start == 0 || End == 0) return 0;
1409 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1410 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1412 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1413 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1418 /// constructInlinedScopeDIE - This scope represents inlined body of
1419 /// a function. Construct DIE to represent this concrete inlined copy
1420 /// of the function.
1421 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1423 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1424 assert (Ranges.empty() == false
1425 && "DbgScope does not have instruction markers!");
1427 // FIXME : .debug_inlined section specification does not clearly state how
1428 // to emit inlined scope that is split into multiple instruction ranges.
1429 // For now, use first instruction range and emit low_pc/high_pc pair and
1430 // corresponding .debug_inlined section entry for this pair.
1431 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1432 MCSymbol *StartLabel = LabelsBeforeInsn.lookup(RI->first);
1433 MCSymbol *EndLabel = LabelsAfterInsn.lookup(RI->second);
1435 if (StartLabel == 0 || EndLabel == 0) {
1436 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1439 assert(StartLabel->isDefined() &&
1440 "Invalid starting label for an inlined scope!");
1441 assert(EndLabel->isDefined() &&
1442 "Invalid end label for an inlined scope!");
1444 if (!Scope->getScopeNode())
1446 DIScope DS(Scope->getScopeNode());
1447 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1449 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1450 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1451 assert(OriginDIE && "Unable to find Origin DIE!");
1452 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1453 dwarf::DW_FORM_ref4, OriginDIE);
1455 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1456 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1458 InlinedSubprogramDIEs.insert(OriginDIE);
1460 // Track the start label for this inlined function.
1461 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1462 I = InlineInfo.find(InlinedSP.getNode());
1464 if (I == InlineInfo.end()) {
1465 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel,
1467 InlinedSPNodes.push_back(InlinedSP.getNode());
1469 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1471 DILocation DL(Scope->getInlinedAt());
1472 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1473 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1479 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1480 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1481 // Get the descriptor.
1482 const DIVariable &VD = DV->getVariable();
1483 StringRef Name = VD.getName();
1487 // Translate tag to proper Dwarf tag. The result variable is dropped for
1490 switch (VD.getTag()) {
1491 case dwarf::DW_TAG_return_variable:
1493 case dwarf::DW_TAG_arg_variable:
1494 Tag = dwarf::DW_TAG_formal_parameter;
1496 case dwarf::DW_TAG_auto_variable: // fall thru
1498 Tag = dwarf::DW_TAG_variable;
1502 // Define variable debug information entry.
1503 DIE *VariableDie = new DIE(Tag);
1507 if (DbgVariable *AV = DV->getAbstractVariable())
1508 AbsDIE = AV->getDIE();
1511 DIScope DS(Scope->getScopeNode());
1512 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1513 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1515 assert(OriginSPDIE && "Unable to find Origin DIE for the SP!");
1516 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1517 assert(AbsDIE && "Unable to find Origin DIE for the Variable!");
1518 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1519 dwarf::DW_FORM_ref4, AbsDIE);
1522 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1523 addSourceLine(VariableDie, &VD);
1525 // Add variable type.
1526 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1527 // addresses instead.
1528 if (VD.isBlockByrefVariable())
1529 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1531 addType(VariableDie, VD.getType());
1534 // Add variable address.
1535 if (!Scope->isAbstractScope()) {
1536 // Check if variable is described by DBG_VALUE instruction.
1537 if (const MachineInstr *DbgValueInsn = DV->getDbgValue()) {
1538 if (DbgValueInsn->getNumOperands() == 3) {
1539 // FIXME : Handle getNumOperands != 3
1540 if (DbgValueInsn->getOperand(0).isReg() &&
1541 DbgValueInsn->getOperand(0).getReg()) {
1542 MachineLocation Location;
1543 Location.set(DbgValueInsn->getOperand(0).getReg());
1544 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1545 if (MCSymbol *VS = DV->getDbgValueLabel())
1546 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1548 } else if (DbgValueInsn->getOperand(0).isImm()) {
1549 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1550 unsigned Imm = DbgValueInsn->getOperand(0).getImm();
1551 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
1552 addBlock(VariableDie, dwarf::DW_AT_const_value, 0, Block);
1553 if (MCSymbol *VS = DV->getDbgValueLabel())
1554 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1556 } else if (DbgValueInsn->getOperand(0).isFPImm()) {
1557 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1558 APFloat FPImm = DbgValueInsn->getOperand(0).getFPImm()->getValueAPF();
1560 // Get the raw data form of the floating point.
1561 const APInt FltVal = FPImm.bitcastToAPInt();
1562 const char *FltPtr = (const char*)FltVal.getRawData();
1564 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
1565 bool LittleEndian = Asm->getTargetData().isLittleEndian();
1566 int Incr = (LittleEndian ? 1 : -1);
1567 int Start = (LittleEndian ? 0 : NumBytes - 1);
1568 int Stop = (LittleEndian ? NumBytes : -1);
1570 // Output the constant to DWARF one byte at a time.
1571 for (; Start != Stop; Start += Incr)
1572 addUInt(Block, 0, dwarf::DW_FORM_data1,
1573 (unsigned char)0xFF & FltPtr[Start]);
1575 addBlock(VariableDie, dwarf::DW_AT_const_value, 0, Block);
1577 if (MCSymbol *VS = DV->getDbgValueLabel())
1578 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1581 //FIXME : Handle other operand types.
1587 MachineLocation Location;
1589 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1590 int Offset = RI->getFrameIndexReference(*Asm->MF, DV->getFrameIndex(),
1592 Location.set(FrameReg, Offset);
1594 if (VD.hasComplexAddress())
1595 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1596 else if (VD.isBlockByrefVariable())
1597 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1599 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1603 if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1604 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1605 DV->setDIE(VariableDie);
1610 void DwarfDebug::addPubTypes(DISubprogram SP) {
1611 DICompositeType SPTy = SP.getType();
1612 unsigned SPTag = SPTy.getTag();
1613 if (SPTag != dwarf::DW_TAG_subroutine_type)
1616 DIArray Args = SPTy.getTypeArray();
1617 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1618 DIType ATy(Args.getElement(i).getNode());
1621 DICompositeType CATy = getDICompositeType(ATy);
1622 if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty()
1623 && !CATy.isForwardDecl()) {
1624 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1625 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1630 /// constructScopeDIE - Construct a DIE for this scope.
1631 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1632 if (!Scope || !Scope->getScopeNode())
1635 DIScope DS(Scope->getScopeNode());
1636 DIE *ScopeDIE = NULL;
1637 if (Scope->getInlinedAt())
1638 ScopeDIE = constructInlinedScopeDIE(Scope);
1639 else if (DS.isSubprogram()) {
1640 if (Scope->isAbstractScope())
1641 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1643 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1646 ScopeDIE = constructLexicalScopeDIE(Scope);
1647 if (!ScopeDIE) return NULL;
1649 // Add variables to scope.
1650 const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1651 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1652 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1654 ScopeDIE->addChild(VariableDIE);
1657 // Add nested scopes.
1658 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1659 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1660 // Define the Scope debug information entry.
1661 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1663 ScopeDIE->addChild(NestedDIE);
1666 if (DS.isSubprogram())
1667 addPubTypes(DISubprogram(DS.getNode()));
1672 /// GetOrCreateSourceID - Look up the source id with the given directory and
1673 /// source file names. If none currently exists, create a new id and insert it
1674 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1676 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1678 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1679 if (DI != DirectoryIdMap.end()) {
1680 DId = DI->getValue();
1682 DId = DirectoryNames.size() + 1;
1683 DirectoryIdMap[DirName] = DId;
1684 DirectoryNames.push_back(DirName);
1688 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1689 if (FI != SourceFileIdMap.end()) {
1690 FId = FI->getValue();
1692 FId = SourceFileNames.size() + 1;
1693 SourceFileIdMap[FileName] = FId;
1694 SourceFileNames.push_back(FileName);
1697 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1698 SourceIdMap.find(std::make_pair(DId, FId));
1699 if (SI != SourceIdMap.end())
1702 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1703 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1704 SourceIds.push_back(std::make_pair(DId, FId));
1709 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1710 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1711 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1714 NDie = new DIE(dwarf::DW_TAG_namespace);
1715 ModuleCU->insertDIE(NS.getNode(), NDie);
1716 if (!NS.getName().empty())
1717 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1718 addSourceLine(NDie, &NS);
1719 addToContextOwner(NDie, NS.getContext());
1723 void DwarfDebug::constructCompileUnit(MDNode *N) {
1724 DICompileUnit DIUnit(N);
1725 // Use first compile unit marked as isMain as the compile unit for this
1727 if (ModuleCU || !DIUnit.isMain())
1729 StringRef FN = DIUnit.getFilename();
1730 StringRef Dir = DIUnit.getDirectory();
1731 unsigned ID = GetOrCreateSourceID(Dir, FN);
1733 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1734 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1735 DIUnit.getProducer());
1736 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1737 DIUnit.getLanguage());
1738 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1739 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1740 // simplifies debug range entries.
1741 addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_data4, 0);
1742 // DW_AT_stmt_list is a offset of line number information for this
1743 // compile unit in debug_line section. It is always zero when only one
1744 // compile unit is emitted in one object file.
1745 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1748 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1749 if (DIUnit.isOptimized())
1750 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1752 StringRef Flags = DIUnit.getFlags();
1754 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1756 unsigned RVer = DIUnit.getRunTimeVersion();
1758 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1759 dwarf::DW_FORM_data1, RVer);
1762 "ModuleCU assigned since the top of constructCompileUnit");
1763 ModuleCU = new CompileUnit(ID, Die);
1766 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1767 DIGlobalVariable DI_GV(N);
1769 // If debug information is malformed then ignore it.
1770 if (DI_GV.Verify() == false)
1773 // Check for pre-existence.
1774 if (ModuleCU->getDIE(DI_GV.getNode()))
1777 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1782 ModuleCU->insertDIE(N, VariableDie);
1784 // Add to context owner.
1785 DIDescriptor GVContext = DI_GV.getContext();
1786 // Do not create specification DIE if context is either compile unit
1788 if (DI_GV.isDefinition() && !GVContext.isCompileUnit() &&
1789 !GVContext.isFile() &&
1790 !isSubprogramContext(GVContext.getNode())) {
1791 // Create specification DIE.
1792 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1793 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1794 dwarf::DW_FORM_ref4, VariableDie);
1795 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1796 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1797 addLabel(Block, 0, dwarf::DW_FORM_udata,
1798 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1799 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1800 addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1801 ModuleCU->addDie(VariableSpecDIE);
1803 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1804 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1805 addLabel(Block, 0, dwarf::DW_FORM_udata,
1806 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1807 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1809 addToContextOwner(VariableDie, GVContext);
1811 // Expose as global. FIXME - need to check external flag.
1812 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1814 DIType GTy = DI_GV.getType();
1815 if (GTy.isCompositeType() && !GTy.getName().empty()
1816 && !GTy.isForwardDecl()) {
1817 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1818 assert(Entry && "Missing global type!");
1819 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1824 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1827 // Check for pre-existence.
1828 if (ModuleCU->getDIE(N))
1831 if (!SP.isDefinition())
1832 // This is a method declaration which will be handled while constructing
1836 DIE *SubprogramDie = createSubprogramDIE(SP);
1839 ModuleCU->insertDIE(N, SubprogramDie);
1841 // Add to context owner.
1842 addToContextOwner(SubprogramDie, SP.getContext());
1844 // Expose as global.
1845 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1850 /// beginModule - Emit all Dwarf sections that should come prior to the
1851 /// content. Create global DIEs and emit initial debug info sections.
1852 /// This is inovked by the target AsmPrinter.
1853 void DwarfDebug::beginModule(Module *M) {
1854 if (DisableDebugInfoPrinting)
1857 DebugInfoFinder DbgFinder;
1858 DbgFinder.processModule(*M);
1860 bool HasDebugInfo = false;
1862 // Scan all the compile-units to see if there are any marked as the main unit.
1863 // if not, we do not generate debug info.
1864 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1865 E = DbgFinder.compile_unit_end(); I != E; ++I) {
1866 if (DICompileUnit(*I).isMain()) {
1867 HasDebugInfo = true;
1872 if (!HasDebugInfo) return;
1874 // Tell MMI that we have debug info.
1875 MMI->setDebugInfoAvailability(true);
1877 // Emit initial sections.
1878 EmitSectionLabels();
1880 // Create all the compile unit DIEs.
1881 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1882 E = DbgFinder.compile_unit_end(); I != E; ++I)
1883 constructCompileUnit(*I);
1885 // Create DIEs for each subprogram.
1886 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1887 E = DbgFinder.subprogram_end(); I != E; ++I)
1888 constructSubprogramDIE(*I);
1890 // Create DIEs for each global variable.
1891 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1892 E = DbgFinder.global_variable_end(); I != E; ++I)
1893 constructGlobalVariableDIE(*I);
1895 // Prime section data.
1896 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1898 // Print out .file directives to specify files for .loc directives. These are
1899 // printed out early so that they precede any .loc directives.
1900 if (Asm->MAI->hasDotLocAndDotFile()) {
1901 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1902 // Remember source id starts at 1.
1903 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1904 // FIXME: don't use sys::path for this! This should not depend on the
1906 sys::Path FullPath(getSourceDirectoryName(Id.first));
1908 FullPath.appendComponent(getSourceFileName(Id.second));
1909 assert(AppendOk && "Could not append filename to directory!");
1911 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1916 /// endModule - Emit all Dwarf sections that should come after the content.
1918 void DwarfDebug::endModule() {
1919 if (!ModuleCU) return;
1921 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1922 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1923 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1925 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1928 for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
1929 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1930 DIE *SPDie = CI->first;
1931 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1933 DIE *NDie = ModuleCU->getDIE(N);
1934 if (!NDie) continue;
1935 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1938 // Standard sections final addresses.
1939 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1940 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1941 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1942 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1944 // End text sections.
1945 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1946 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1947 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1950 // Emit common frame information.
1951 emitCommonDebugFrame();
1953 // Emit function debug frame information
1954 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1955 E = DebugFrames.end(); I != E; ++I)
1956 emitFunctionDebugFrame(*I);
1958 // Compute DIE offsets and sizes.
1959 computeSizeAndOffsets();
1961 // Emit all the DIEs into a debug info section
1964 // Corresponding abbreviations into a abbrev section.
1965 emitAbbreviations();
1967 // Emit source line correspondence into a debug line section.
1970 // Emit info into a debug pubnames section.
1971 emitDebugPubNames();
1973 // Emit info into a debug pubtypes section.
1974 emitDebugPubTypes();
1976 // Emit info into a debug loc section.
1979 // Emit info into a debug aranges section.
1982 // Emit info into a debug ranges section.
1985 // Emit info into a debug macinfo section.
1988 // Emit inline info.
1989 emitDebugInlineInfo();
1991 // Emit info into a debug str section.
1995 ModuleCU = NULL; // Reset for the next Module, if any.
1998 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1999 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2001 DebugLoc ScopeLoc) {
2003 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2005 return AbsDbgVariable;
2007 LLVMContext &Ctx = Var.getNode()->getContext();
2008 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2012 AbsDbgVariable = new DbgVariable(Var, FrameIdx,
2013 NULL /* No more-abstract variable*/);
2014 Scope->addVariable(AbsDbgVariable);
2015 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2016 return AbsDbgVariable;
2019 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2020 /// FIXME : Refactor findAbstractVariable.
2021 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2022 const MachineInstr *MI,
2023 DebugLoc ScopeLoc) {
2025 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2027 return AbsDbgVariable;
2029 LLVMContext &Ctx = Var.getNode()->getContext();
2030 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2034 AbsDbgVariable = new DbgVariable(Var, MI,
2035 NULL /* No more-abstract variable*/);
2036 Scope->addVariable(AbsDbgVariable);
2037 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2038 DbgValueStartMap[MI] = AbsDbgVariable;
2039 return AbsDbgVariable;
2042 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2043 void DwarfDebug::collectVariableInfo() {
2044 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2046 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2047 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2048 VE = VMap.end(); VI != VE; ++VI) {
2049 MDNode *Var = VI->first;
2052 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2054 DbgScope *Scope = 0;
2055 if (MDNode *IA = VP.second.getInlinedAt(Ctx))
2056 Scope = ConcreteScopes.lookup(IA);
2058 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2060 // If variable scope is not found then skip this variable.
2064 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, VP.second);
2065 DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
2066 Scope->addVariable(RegVar);
2069 // Collect variable information from DBG_VALUE machine instructions;
2070 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2072 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2074 const MachineInstr *MInsn = II;
2075 if (!MInsn->isDebugValue())
2078 // FIXME : Lift this restriction.
2079 if (MInsn->getNumOperands() != 3)
2082 // Ignore Undef values.
2083 if (MInsn->getOperand(0).isReg() && !MInsn->getOperand(0).getReg())
2087 const_cast<MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1)
2089 if (DV.getTag() == dwarf::DW_TAG_arg_variable) {
2090 // FIXME Handle inlined subroutine arguments.
2091 DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL);
2092 CurrentFnDbgScope->addVariable(ArgVar);
2093 DbgValueStartMap[MInsn] = ArgVar;
2097 DebugLoc DL = MInsn->getDebugLoc();
2098 if (DL.isUnknown()) continue;
2099 DbgScope *Scope = 0;
2100 if (MDNode *IA = DL.getInlinedAt(Ctx))
2101 Scope = ConcreteScopes.lookup(IA);
2103 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2105 // If variable scope is not found then skip this variable.
2109 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL);
2110 DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable);
2111 DbgValueStartMap[MInsn] = RegVar;
2112 Scope->addVariable(RegVar);
2117 /// beginScope - Process beginning of a scope.
2118 void DwarfDebug::beginScope(const MachineInstr *MI) {
2120 DebugLoc DL = MI->getDebugLoc();
2124 MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2126 // FIXME: Should only verify each scope once!
2127 if (!DIScope(Scope).Verify())
2130 // DBG_VALUE instruction establishes new value.
2131 if (MI->isDebugValue()) {
2132 DenseMap<const MachineInstr *, DbgVariable *>::iterator DI
2133 = DbgValueStartMap.find(MI);
2134 if (DI != DbgValueStartMap.end()) {
2135 MCSymbol *Label = NULL;
2136 if (DL == PrevInstLoc)
2139 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2143 DI->second->setDbgValueLabel(Label);
2148 // Emit a label to indicate location change. This is used for line
2149 // table even if this instruction does not start a new scope.
2150 MCSymbol *Label = NULL;
2151 if (DL == PrevInstLoc)
2154 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2159 // If this instruction begins a scope then note down corresponding label.
2160 if (InsnsBeginScopeSet.count(MI) != 0)
2161 LabelsBeforeInsn[MI] = Label;
2164 /// endScope - Process end of a scope.
2165 void DwarfDebug::endScope(const MachineInstr *MI) {
2166 if (InsnsEndScopeSet.count(MI) != 0) {
2167 // Emit a label if this instruction ends a scope.
2168 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2169 Asm->OutStreamer.EmitLabel(Label);
2170 LabelsAfterInsn[MI] = Label;
2174 /// getOrCreateDbgScope - Create DbgScope for the scope.
2175 DbgScope *DwarfDebug::getOrCreateDbgScope(MDNode *Scope, MDNode *InlinedAt) {
2177 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2180 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2181 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2182 if (DIDescriptor(Scope).isLexicalBlock()) {
2184 getOrCreateDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2185 WScope->setParent(Parent);
2186 Parent->addScope(WScope);
2189 if (!WScope->getParent()) {
2190 StringRef SPName = DISubprogram(Scope).getLinkageName();
2191 if (SPName == Asm->MF->getFunction()->getName())
2192 CurrentFnDbgScope = WScope;
2198 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2202 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2203 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2204 DILocation DL(InlinedAt);
2206 getOrCreateDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2207 WScope->setParent(Parent);
2208 Parent->addScope(WScope);
2210 ConcreteScopes[InlinedAt] = WScope;
2211 getOrCreateAbstractScope(Scope);
2216 /// hasValidLocation - Return true if debug location entry attached with
2217 /// machine instruction encodes valid location info.
2218 static bool hasValidLocation(LLVMContext &Ctx,
2219 const MachineInstr *MInsn,
2220 MDNode *&Scope, MDNode *&InlinedAt) {
2221 if (MInsn->isDebugValue())
2223 DebugLoc DL = MInsn->getDebugLoc();
2224 if (DL.isUnknown()) return false;
2226 MDNode *S = DL.getScope(Ctx);
2228 // There is no need to create another DIE for compile unit. For all
2229 // other scopes, create one DbgScope now. This will be translated
2230 // into a scope DIE at the end.
2231 if (DIScope(S).isCompileUnit()) return false;
2234 InlinedAt = DL.getInlinedAt(Ctx);
2238 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2240 static void calculateDominanceGraph(DbgScope *Scope) {
2241 assert (Scope && "Unable to calculate scop edominance graph!");
2242 SmallVector<DbgScope *, 4> WorkStack;
2243 WorkStack.push_back(Scope);
2244 unsigned Counter = 0;
2245 while (!WorkStack.empty()) {
2246 DbgScope *WS = WorkStack.back();
2247 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2248 bool visitedChildren = false;
2249 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2250 SE = Children.end(); SI != SE; ++SI) {
2251 DbgScope *ChildScope = *SI;
2252 if (!ChildScope->getDFSOut()) {
2253 WorkStack.push_back(ChildScope);
2254 visitedChildren = true;
2255 ChildScope->setDFSIn(++Counter);
2259 if (!visitedChildren) {
2260 WorkStack.pop_back();
2261 WS->setDFSOut(++Counter);
2266 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2268 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2269 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2272 unsigned PrevDFSIn = 0;
2273 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2275 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2277 const MachineInstr *MInsn = II;
2278 MDNode *Scope = NULL;
2279 MDNode *InlinedAt = NULL;
2281 // Check if instruction has valid location information.
2282 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2286 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2287 MI2ScopeMap.find(MInsn);
2288 if (DI != MI2ScopeMap.end()) {
2289 DbgScope *S = DI->second;
2290 dbgs() << S->getDFSIn();
2291 PrevDFSIn = S->getDFSIn();
2293 dbgs() << PrevDFSIn;
2295 dbgs() << " [ x" << PrevDFSIn;
2303 /// extractScopeInformation - Scan machine instructions in this function
2304 /// and collect DbgScopes. Return true, if at least one scope was found.
2305 bool DwarfDebug::extractScopeInformation() {
2306 // If scope information was extracted using .dbg intrinsics then there is not
2307 // any need to extract these information by scanning each instruction.
2308 if (!DbgScopeMap.empty())
2311 // Scan each instruction and create scopes. First build working set of scopes.
2312 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2313 SmallVector<DbgRange, 4> MIRanges;
2314 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2315 MDNode *PrevScope = NULL;
2316 MDNode *PrevInlinedAt = NULL;
2317 const MachineInstr *RangeBeginMI = NULL;
2318 const MachineInstr *PrevMI = NULL;
2319 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2321 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2323 const MachineInstr *MInsn = II;
2324 MDNode *Scope = NULL;
2325 MDNode *InlinedAt = NULL;
2327 // Check if instruction has valid location information.
2328 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2333 // If scope has not changed then skip this instruction.
2334 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2340 // If we have alread seen a beginning of a instruction range and
2341 // current instruction scope does not match scope of first instruction
2342 // in this range then create a new instruction range.
2343 DbgRange R(RangeBeginMI, PrevMI);
2344 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2345 MIRanges.push_back(R);
2348 // This is a beginning of a new instruction range.
2349 RangeBeginMI = MInsn;
2351 // Reset previous markers.
2354 PrevInlinedAt = InlinedAt;
2358 // Create last instruction range.
2359 if (RangeBeginMI && PrevMI && PrevScope) {
2360 DbgRange R(RangeBeginMI, PrevMI);
2361 MIRanges.push_back(R);
2362 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2365 if (!CurrentFnDbgScope)
2368 calculateDominanceGraph(CurrentFnDbgScope);
2370 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2372 // Find ranges of instructions covered by each DbgScope;
2373 DbgScope *PrevDbgScope = NULL;
2374 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2375 RE = MIRanges.end(); RI != RE; ++RI) {
2376 const DbgRange &R = *RI;
2377 DbgScope *S = MI2ScopeMap.lookup(R.first);
2378 assert (S && "Lost DbgScope for a machine instruction!");
2379 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2380 PrevDbgScope->closeInsnRange(S);
2381 S->openInsnRange(R.first);
2382 S->extendInsnRange(R.second);
2387 PrevDbgScope->closeInsnRange();
2389 identifyScopeMarkers();
2391 return !DbgScopeMap.empty();
2394 /// identifyScopeMarkers() -
2395 /// Each DbgScope has first instruction and last instruction to mark beginning
2396 /// and end of a scope respectively. Create an inverse map that list scopes
2397 /// starts (and ends) with an instruction. One instruction may start (or end)
2398 /// multiple scopes. Ignore scopes that are not reachable.
2399 void DwarfDebug::identifyScopeMarkers() {
2400 SmallVector<DbgScope *, 4> WorkList;
2401 WorkList.push_back(CurrentFnDbgScope);
2402 while (!WorkList.empty()) {
2403 DbgScope *S = WorkList.pop_back_val();
2405 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2406 if (!Children.empty())
2407 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2408 SE = Children.end(); SI != SE; ++SI)
2409 WorkList.push_back(*SI);
2411 if (S->isAbstractScope())
2414 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2417 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2418 RE = Ranges.end(); RI != RE; ++RI) {
2419 assert(RI->first && "DbgRange does not have first instruction!");
2420 assert(RI->second && "DbgRange does not have second instruction!");
2421 InsnsBeginScopeSet.insert(RI->first);
2422 InsnsEndScopeSet.insert(RI->second);
2427 /// FindFirstDebugLoc - Find the first debug location in the function. This
2428 /// is intended to be an approximation for the source position of the
2429 /// beginning of the function.
2430 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2431 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2433 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2434 MBBI != MBBE; ++MBBI) {
2435 DebugLoc DL = MBBI->getDebugLoc();
2436 if (!DL.isUnknown())
2442 /// beginFunction - Gather pre-function debug information. Assumes being
2443 /// emitted immediately after the function entry point.
2444 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2445 if (!MMI->hasDebugInfo()) return;
2446 if (!extractScopeInformation()) return;
2448 collectVariableInfo();
2450 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2451 Asm->getFunctionNumber());
2452 // Assumes in correct section after the entry point.
2453 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2455 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2457 DebugLoc FDL = FindFirstDebugLoc(MF);
2458 if (FDL.isUnknown()) return;
2460 MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2462 DISubprogram SP = getDISubprogram(Scope);
2465 Line = SP.getLineNumber();
2468 Line = FDL.getLine();
2472 recordSourceLine(Line, Col, Scope);
2475 /// endFunction - Gather and emit post-function debug information.
2477 void DwarfDebug::endFunction(const MachineFunction *MF) {
2478 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2480 if (CurrentFnDbgScope) {
2481 // Define end label for subprogram.
2482 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end",
2483 Asm->getFunctionNumber()));
2485 // Get function line info.
2486 if (!Lines.empty()) {
2487 // Get section line info.
2488 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2489 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2490 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2491 // Append the function info to section info.
2492 SectionLineInfos.insert(SectionLineInfos.end(),
2493 Lines.begin(), Lines.end());
2496 // Construct abstract scopes.
2497 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2498 AE = AbstractScopesList.end(); AI != AE; ++AI)
2499 constructScopeDIE(*AI);
2501 constructScopeDIE(CurrentFnDbgScope);
2503 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2504 MMI->getFrameMoves()));
2508 CurrentFnDbgScope = NULL;
2509 DeleteContainerSeconds(DbgScopeMap);
2510 InsnsBeginScopeSet.clear();
2511 InsnsEndScopeSet.clear();
2512 DbgValueStartMap.clear();
2513 ConcreteScopes.clear();
2514 DeleteContainerSeconds(AbstractScopes);
2515 AbstractScopesList.clear();
2516 AbstractVariables.clear();
2517 LabelsBeforeInsn.clear();
2518 LabelsAfterInsn.clear();
2523 /// recordSourceLine - Register a source line with debug info. Returns the
2524 /// unique label that was emitted and which provides correspondence to
2525 /// the source line list.
2526 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) {
2530 DIDescriptor Scope(S);
2531 if (Scope.isCompileUnit()) {
2532 DICompileUnit CU(S);
2533 Dir = CU.getDirectory();
2534 Fn = CU.getFilename();
2535 } else if (Scope.isSubprogram()) {
2537 Dir = SP.getDirectory();
2538 Fn = SP.getFilename();
2539 } else if (Scope.isLexicalBlock()) {
2540 DILexicalBlock DB(S);
2541 Dir = DB.getDirectory();
2542 Fn = DB.getFilename();
2544 assert(0 && "Unexpected scope info");
2546 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2547 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2548 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2550 Asm->OutStreamer.EmitLabel(Label);
2554 //===----------------------------------------------------------------------===//
2556 //===----------------------------------------------------------------------===//
2558 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2561 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2562 // Get the children.
2563 const std::vector<DIE *> &Children = Die->getChildren();
2565 // If not last sibling and has children then add sibling offset attribute.
2566 if (!Last && !Children.empty())
2567 Die->addSiblingOffset(DIEValueAllocator);
2569 // Record the abbreviation.
2570 assignAbbrevNumber(Die->getAbbrev());
2572 // Get the abbreviation for this DIE.
2573 unsigned AbbrevNumber = Die->getAbbrevNumber();
2574 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2577 Die->setOffset(Offset);
2579 // Start the size with the size of abbreviation code.
2580 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2582 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2583 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2585 // Size the DIE attribute values.
2586 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2587 // Size attribute value.
2588 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2590 // Size the DIE children if any.
2591 if (!Children.empty()) {
2592 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2593 "Children flag not set");
2595 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2596 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2598 // End of children marker.
2599 Offset += sizeof(int8_t);
2602 Die->setSize(Offset - Die->getOffset());
2606 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2608 void DwarfDebug::computeSizeAndOffsets() {
2609 // Compute size of compile unit header.
2610 static unsigned Offset =
2611 sizeof(int32_t) + // Length of Compilation Unit Info
2612 sizeof(int16_t) + // DWARF version number
2613 sizeof(int32_t) + // Offset Into Abbrev. Section
2614 sizeof(int8_t); // Pointer Size (in bytes)
2616 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2619 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2620 /// temporary label to it if SymbolStem is specified.
2621 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2622 const char *SymbolStem = 0) {
2623 Asm->OutStreamer.SwitchSection(Section);
2624 if (!SymbolStem) return 0;
2626 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2627 Asm->OutStreamer.EmitLabel(TmpSym);
2631 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2632 /// the start of each one.
2633 void DwarfDebug::EmitSectionLabels() {
2634 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2636 // Dwarf sections base addresses.
2637 if (Asm->MAI->doesDwarfRequireFrameSection()) {
2638 DwarfFrameSectionSym =
2639 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2642 DwarfInfoSectionSym =
2643 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2644 DwarfAbbrevSectionSym =
2645 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2646 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2648 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2649 EmitSectionSym(Asm, MacroInfo);
2651 EmitSectionSym(Asm, TLOF.getDwarfLineSection());
2652 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2653 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2654 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2655 DwarfStrSectionSym =
2656 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2657 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2660 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2661 EmitSectionSym(Asm, TLOF.getDataSection());
2664 /// emitDIE - Recusively Emits a debug information entry.
2666 void DwarfDebug::emitDIE(DIE *Die) {
2667 // Get the abbreviation for this DIE.
2668 unsigned AbbrevNumber = Die->getAbbrevNumber();
2669 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2671 // Emit the code (index) for the abbreviation.
2672 if (Asm->isVerbose())
2673 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2674 Twine::utohexstr(Die->getOffset()) + ":0x" +
2675 Twine::utohexstr(Die->getSize()) + " " +
2676 dwarf::TagString(Abbrev->getTag()));
2677 Asm->EmitULEB128(AbbrevNumber);
2679 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2680 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2682 // Emit the DIE attribute values.
2683 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2684 unsigned Attr = AbbrevData[i].getAttribute();
2685 unsigned Form = AbbrevData[i].getForm();
2686 assert(Form && "Too many attributes for DIE (check abbreviation)");
2688 if (Asm->isVerbose())
2689 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2692 case dwarf::DW_AT_sibling:
2693 Asm->EmitInt32(Die->getSiblingOffset());
2695 case dwarf::DW_AT_abstract_origin: {
2696 DIEEntry *E = cast<DIEEntry>(Values[i]);
2697 DIE *Origin = E->getEntry();
2698 unsigned Addr = Origin->getOffset();
2699 Asm->EmitInt32(Addr);
2702 case dwarf::DW_AT_ranges: {
2703 // DW_AT_range Value encodes offset in debug_range section.
2704 DIEInteger *V = cast<DIEInteger>(Values[i]);
2705 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2707 DwarfDebugRangeSectionSym,
2712 // Emit an attribute using the defined form.
2713 Values[i]->EmitValue(Asm, Form);
2718 // Emit the DIE children if any.
2719 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2720 const std::vector<DIE *> &Children = Die->getChildren();
2722 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2723 emitDIE(Children[j]);
2725 if (Asm->isVerbose())
2726 Asm->OutStreamer.AddComment("End Of Children Mark");
2731 /// emitDebugInfo - Emit the debug info section.
2733 void DwarfDebug::emitDebugInfo() {
2734 // Start debug info section.
2735 Asm->OutStreamer.SwitchSection(
2736 Asm->getObjFileLowering().getDwarfInfoSection());
2737 DIE *Die = ModuleCU->getCUDie();
2739 // Emit the compile units header.
2740 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2741 ModuleCU->getID()));
2743 // Emit size of content not including length itself
2744 unsigned ContentSize = Die->getSize() +
2745 sizeof(int16_t) + // DWARF version number
2746 sizeof(int32_t) + // Offset Into Abbrev. Section
2747 sizeof(int8_t) + // Pointer Size (in bytes)
2748 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2750 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2751 Asm->EmitInt32(ContentSize);
2752 Asm->OutStreamer.AddComment("DWARF version number");
2753 Asm->EmitInt16(dwarf::DWARF_VERSION);
2754 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2755 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2756 DwarfAbbrevSectionSym);
2757 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2758 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2761 // FIXME - extra padding for gdb bug.
2762 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2767 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", ModuleCU->getID()));
2770 /// emitAbbreviations - Emit the abbreviation section.
2772 void DwarfDebug::emitAbbreviations() const {
2773 // Check to see if it is worth the effort.
2774 if (!Abbreviations.empty()) {
2775 // Start the debug abbrev section.
2776 Asm->OutStreamer.SwitchSection(
2777 Asm->getObjFileLowering().getDwarfAbbrevSection());
2779 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2781 // For each abbrevation.
2782 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2783 // Get abbreviation data
2784 const DIEAbbrev *Abbrev = Abbreviations[i];
2786 // Emit the abbrevations code (base 1 index.)
2787 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2789 // Emit the abbreviations data.
2793 // Mark end of abbreviations.
2794 Asm->EmitULEB128(0, "EOM(3)");
2796 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2800 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2801 /// the line matrix.
2803 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2804 // Define last address of section.
2805 Asm->OutStreamer.AddComment("Extended Op");
2808 Asm->OutStreamer.AddComment("Op size");
2809 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2810 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2811 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2813 Asm->OutStreamer.AddComment("Section end label");
2815 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2816 Asm->getTargetData().getPointerSize(),
2819 // Mark end of matrix.
2820 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2826 /// emitDebugLines - Emit source line information.
2828 void DwarfDebug::emitDebugLines() {
2829 // If the target is using .loc/.file, the assembler will be emitting the
2830 // .debug_line table automatically.
2831 if (Asm->MAI->hasDotLocAndDotFile())
2834 // Minimum line delta, thus ranging from -10..(255-10).
2835 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2836 // Maximum line delta, thus ranging from -10..(255-10).
2837 const int MaxLineDelta = 255 + MinLineDelta;
2839 // Start the dwarf line section.
2840 Asm->OutStreamer.SwitchSection(
2841 Asm->getObjFileLowering().getDwarfLineSection());
2843 // Construct the section header.
2844 Asm->OutStreamer.AddComment("Length of Source Line Info");
2845 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
2846 Asm->GetTempSymbol("line_begin"), 4);
2847 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
2849 Asm->OutStreamer.AddComment("DWARF version number");
2850 Asm->EmitInt16(dwarf::DWARF_VERSION);
2852 Asm->OutStreamer.AddComment("Prolog Length");
2853 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
2854 Asm->GetTempSymbol("line_prolog_begin"), 4);
2855 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
2857 Asm->OutStreamer.AddComment("Minimum Instruction Length");
2859 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2861 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2862 Asm->EmitInt8(MinLineDelta);
2863 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2864 Asm->EmitInt8(MaxLineDelta);
2865 Asm->OutStreamer.AddComment("Special Opcode Base");
2866 Asm->EmitInt8(-MinLineDelta);
2868 // Line number standard opcode encodings argument count
2869 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2871 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2873 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2875 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2877 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2879 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2881 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2883 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2885 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2888 // Emit directories.
2889 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2890 const std::string &Dir = getSourceDirectoryName(DI);
2891 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
2892 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2895 Asm->OutStreamer.AddComment("End of directories");
2899 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2900 // Remember source id starts at 1.
2901 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2902 const std::string &FN = getSourceFileName(Id.second);
2903 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
2904 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2906 Asm->EmitULEB128(Id.first, "Directory #");
2907 Asm->EmitULEB128(0, "Mod date");
2908 Asm->EmitULEB128(0, "File size");
2911 Asm->OutStreamer.AddComment("End of files");
2914 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
2916 // A sequence for each text section.
2917 unsigned SecSrcLinesSize = SectionSourceLines.size();
2919 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2920 // Isolate current sections line info.
2921 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2923 // Dwarf assumes we start with first line of first source file.
2924 unsigned Source = 1;
2927 // Construct rows of the address, source, line, column matrix.
2928 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2929 const SrcLineInfo &LineInfo = LineInfos[i];
2930 MCSymbol *Label = LineInfo.getLabel();
2931 if (!Label->isDefined()) continue; // Not emitted, in dead code.
2933 if (LineInfo.getLine() == 0) continue;
2935 if (Asm->isVerbose()) {
2936 std::pair<unsigned, unsigned> SrcID =
2937 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2938 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
2940 Twine(getSourceFileName(SrcID.second)) +
2941 ":" + Twine(LineInfo.getLine()));
2944 // Define the line address.
2945 Asm->OutStreamer.AddComment("Extended Op");
2947 Asm->OutStreamer.AddComment("Op size");
2948 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2950 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2951 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2953 Asm->OutStreamer.AddComment("Location label");
2954 Asm->OutStreamer.EmitSymbolValue(Label,
2955 Asm->getTargetData().getPointerSize(),
2958 // If change of source, then switch to the new source.
2959 if (Source != LineInfo.getSourceID()) {
2960 Source = LineInfo.getSourceID();
2961 Asm->OutStreamer.AddComment("DW_LNS_set_file");
2962 Asm->EmitInt8(dwarf::DW_LNS_set_file);
2963 Asm->EmitULEB128(Source, "New Source");
2966 // If change of line.
2967 if (Line != LineInfo.getLine()) {
2968 // Determine offset.
2969 int Offset = LineInfo.getLine() - Line;
2970 int Delta = Offset - MinLineDelta;
2973 Line = LineInfo.getLine();
2975 // If delta is small enough and in range...
2976 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2977 // ... then use fast opcode.
2978 Asm->OutStreamer.AddComment("Line Delta");
2979 Asm->EmitInt8(Delta - MinLineDelta);
2981 // ... otherwise use long hand.
2982 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
2983 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2984 Asm->EmitSLEB128(Offset, "Line Offset");
2985 Asm->OutStreamer.AddComment("DW_LNS_copy");
2986 Asm->EmitInt8(dwarf::DW_LNS_copy);
2989 // Copy the previous row (different address or source)
2990 Asm->OutStreamer.AddComment("DW_LNS_copy");
2991 Asm->EmitInt8(dwarf::DW_LNS_copy);
2995 emitEndOfLineMatrix(j + 1);
2998 if (SecSrcLinesSize == 0)
2999 // Because we're emitting a debug_line section, we still need a line
3000 // table. The linker and friends expect it to exist. If there's nothing to
3001 // put into it, emit an empty table.
3002 emitEndOfLineMatrix(1);
3004 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3007 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3009 void DwarfDebug::emitCommonDebugFrame() {
3010 if (!Asm->MAI->doesDwarfRequireFrameSection())
3013 int stackGrowth = Asm->getTargetData().getPointerSize();
3014 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3015 TargetFrameInfo::StackGrowsDown)
3018 // Start the dwarf frame section.
3019 Asm->OutStreamer.SwitchSection(
3020 Asm->getObjFileLowering().getDwarfFrameSection());
3022 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3023 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3024 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3025 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3027 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3028 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3029 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3030 Asm->OutStreamer.AddComment("CIE Version");
3031 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3032 Asm->OutStreamer.AddComment("CIE Augmentation");
3033 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3034 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3035 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3036 Asm->OutStreamer.AddComment("CIE RA Column");
3037 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3038 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3040 std::vector<MachineMove> Moves;
3041 RI->getInitialFrameState(Moves);
3043 Asm->EmitFrameMoves(Moves, 0, false);
3045 Asm->EmitAlignment(2, 0, 0, false);
3046 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3049 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3052 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3053 if (!Asm->MAI->doesDwarfRequireFrameSection())
3056 // Start the dwarf frame section.
3057 Asm->OutStreamer.SwitchSection(
3058 Asm->getObjFileLowering().getDwarfFrameSection());
3060 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3061 MCSymbol *DebugFrameBegin =
3062 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3063 MCSymbol *DebugFrameEnd =
3064 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3065 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3067 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3069 Asm->OutStreamer.AddComment("FDE CIE offset");
3070 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3071 DwarfFrameSectionSym);
3073 Asm->OutStreamer.AddComment("FDE initial location");
3074 MCSymbol *FuncBeginSym =
3075 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3076 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3077 Asm->getTargetData().getPointerSize(),
3081 Asm->OutStreamer.AddComment("FDE address range");
3082 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3083 FuncBeginSym, Asm->getTargetData().getPointerSize());
3085 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3087 Asm->EmitAlignment(2, 0, 0, false);
3088 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3091 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3093 void DwarfDebug::emitDebugPubNames() {
3094 // Start the dwarf pubnames section.
3095 Asm->OutStreamer.SwitchSection(
3096 Asm->getObjFileLowering().getDwarfPubNamesSection());
3098 Asm->OutStreamer.AddComment("Length of Public Names Info");
3099 Asm->EmitLabelDifference(
3100 Asm->GetTempSymbol("pubnames_end", ModuleCU->getID()),
3101 Asm->GetTempSymbol("pubnames_begin", ModuleCU->getID()), 4);
3103 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3104 ModuleCU->getID()));
3106 Asm->OutStreamer.AddComment("DWARF Version");
3107 Asm->EmitInt16(dwarf::DWARF_VERSION);
3109 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3110 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3111 DwarfInfoSectionSym);
3113 Asm->OutStreamer.AddComment("Compilation Unit Length");
3114 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3115 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3118 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
3119 for (StringMap<DIE*>::const_iterator
3120 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3121 const char *Name = GI->getKeyData();
3122 DIE *Entity = GI->second;
3124 Asm->OutStreamer.AddComment("DIE offset");
3125 Asm->EmitInt32(Entity->getOffset());
3127 if (Asm->isVerbose())
3128 Asm->OutStreamer.AddComment("External Name");
3129 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3132 Asm->OutStreamer.AddComment("End Mark");
3134 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3135 ModuleCU->getID()));
3138 void DwarfDebug::emitDebugPubTypes() {
3139 // Start the dwarf pubnames section.
3140 Asm->OutStreamer.SwitchSection(
3141 Asm->getObjFileLowering().getDwarfPubTypesSection());
3142 Asm->OutStreamer.AddComment("Length of Public Types Info");
3143 Asm->EmitLabelDifference(
3144 Asm->GetTempSymbol("pubtypes_end", ModuleCU->getID()),
3145 Asm->GetTempSymbol("pubtypes_begin", ModuleCU->getID()), 4);
3147 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3148 ModuleCU->getID()));
3150 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3151 Asm->EmitInt16(dwarf::DWARF_VERSION);
3153 Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
3154 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3155 DwarfInfoSectionSym);
3157 Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
3158 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3159 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3162 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
3163 for (StringMap<DIE*>::const_iterator
3164 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3165 const char *Name = GI->getKeyData();
3166 DIE * Entity = GI->second;
3168 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3169 Asm->EmitInt32(Entity->getOffset());
3171 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3172 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3175 Asm->OutStreamer.AddComment("End Mark");
3177 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3178 ModuleCU->getID()));
3181 /// emitDebugStr - Emit visible names into a debug str section.
3183 void DwarfDebug::emitDebugStr() {
3184 // Check to see if it is worth the effort.
3185 if (StringPool.empty()) return;
3187 // Start the dwarf str section.
3188 Asm->OutStreamer.SwitchSection(
3189 Asm->getObjFileLowering().getDwarfStrSection());
3191 // Get all of the string pool entries and put them in an array by their ID so
3192 // we can sort them.
3193 SmallVector<std::pair<unsigned,
3194 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3196 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3197 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3198 Entries.push_back(std::make_pair(I->second.second, &*I));
3200 array_pod_sort(Entries.begin(), Entries.end());
3202 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3203 // Emit a label for reference from debug information entries.
3204 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3206 // Emit the string itself.
3207 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3211 /// emitDebugLoc - Emit visible names into a debug loc section.
3213 void DwarfDebug::emitDebugLoc() {
3214 // Start the dwarf loc section.
3215 Asm->OutStreamer.SwitchSection(
3216 Asm->getObjFileLowering().getDwarfLocSection());
3219 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3221 void DwarfDebug::EmitDebugARanges() {
3222 // Start the dwarf aranges section.
3223 Asm->OutStreamer.SwitchSection(
3224 Asm->getObjFileLowering().getDwarfARangesSection());
3227 /// emitDebugRanges - Emit visible names into a debug ranges section.
3229 void DwarfDebug::emitDebugRanges() {
3230 // Start the dwarf ranges section.
3231 Asm->OutStreamer.SwitchSection(
3232 Asm->getObjFileLowering().getDwarfRangesSection());
3233 unsigned char Size = Asm->getTargetData().getPointerSize();
3234 for (SmallVector<const MCSymbol *, 8>::iterator
3235 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3238 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3240 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3244 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3246 void DwarfDebug::emitDebugMacInfo() {
3247 if (const MCSection *LineInfo =
3248 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3249 // Start the dwarf macinfo section.
3250 Asm->OutStreamer.SwitchSection(LineInfo);
3254 /// emitDebugInlineInfo - Emit inline info using following format.
3256 /// 1. length of section
3257 /// 2. Dwarf version number
3258 /// 3. address size.
3260 /// Entries (one "entry" for each function that was inlined):
3262 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3263 /// otherwise offset into __debug_str for regular function name.
3264 /// 2. offset into __debug_str section for regular function name.
3265 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3266 /// instances for the function.
3268 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3269 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3270 /// __debug_info section, and the low_pc is the starting address for the
3271 /// inlining instance.
3272 void DwarfDebug::emitDebugInlineInfo() {
3273 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3279 Asm->OutStreamer.SwitchSection(
3280 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3282 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3283 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3284 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3286 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3288 Asm->OutStreamer.AddComment("Dwarf Version");
3289 Asm->EmitInt16(dwarf::DWARF_VERSION);
3290 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3291 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3293 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3294 E = InlinedSPNodes.end(); I != E; ++I) {
3297 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3298 = InlineInfo.find(Node);
3299 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3300 DISubprogram SP(Node);
3301 StringRef LName = SP.getLinkageName();
3302 StringRef Name = SP.getName();
3304 Asm->OutStreamer.AddComment("MIPS linkage name");
3305 if (LName.empty()) {
3306 Asm->OutStreamer.EmitBytes(Name, 0);
3307 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3309 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3310 DwarfStrSectionSym);
3312 Asm->OutStreamer.AddComment("Function name");
3313 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3314 Asm->EmitULEB128(Labels.size(), "Inline count");
3316 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3317 LE = Labels.end(); LI != LE; ++LI) {
3318 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3319 Asm->EmitInt32(LI->second->getOffset());
3321 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3322 Asm->OutStreamer.EmitSymbolValue(LI->first,
3323 Asm->getTargetData().getPointerSize(),0);
3327 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));