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 /// addRegisterAddress - Add register location entry in variable DIE.
816 bool DwarfDebug::addRegisterAddress(DIE *Die, DbgVariable *DV,
817 const MachineOperand &MO) {
818 assert (MO.isReg() && "Invalid machine operand!");
821 MachineLocation Location;
822 Location.set(MO.getReg());
823 addAddress(Die, dwarf::DW_AT_location, Location);
824 if (MCSymbol *VS = DV->getDbgValueLabel())
825 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
829 /// addConstantValue - Add constant value entry in variable DIE.
830 bool DwarfDebug::addConstantValue(DIE *Die, DbgVariable *DV,
831 const MachineOperand &MO) {
832 assert (MO.isImm() && "Invalid machine operand!");
833 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
834 unsigned Imm = MO.getImm();
835 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
836 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
837 if (MCSymbol *VS = DV->getDbgValueLabel())
838 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
842 /// addConstantFPValue - Add constant value entry in variable DIE.
843 bool DwarfDebug::addConstantFPValue(DIE *Die, DbgVariable *DV,
844 const MachineOperand &MO) {
845 assert (MO.isFPImm() && "Invalid machine operand!");
846 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
847 APFloat FPImm = MO.getFPImm()->getValueAPF();
849 // Get the raw data form of the floating point.
850 const APInt FltVal = FPImm.bitcastToAPInt();
851 const char *FltPtr = (const char*)FltVal.getRawData();
853 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
854 bool LittleEndian = Asm->getTargetData().isLittleEndian();
855 int Incr = (LittleEndian ? 1 : -1);
856 int Start = (LittleEndian ? 0 : NumBytes - 1);
857 int Stop = (LittleEndian ? NumBytes : -1);
859 // Output the constant to DWARF one byte at a time.
860 for (; Start != Stop; Start += Incr)
861 addUInt(Block, 0, dwarf::DW_FORM_data1,
862 (unsigned char)0xFF & FltPtr[Start]);
864 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
866 if (MCSymbol *VS = DV->getDbgValueLabel())
867 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
873 /// addToContextOwner - Add Die into the list of its context owner's children.
874 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
875 if (Context.isType()) {
876 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
877 ContextDIE->addChild(Die);
878 } else if (Context.isNameSpace()) {
879 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
880 ContextDIE->addChild(Die);
881 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
882 ContextDIE->addChild(Die);
884 ModuleCU->addDie(Die);
887 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
889 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
890 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
895 TyDIE = new DIE(dwarf::DW_TAG_base_type);
896 ModuleCU->insertDIE(Ty.getNode(), TyDIE);
897 if (Ty.isBasicType())
898 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
899 else if (Ty.isCompositeType())
900 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
902 assert(Ty.isDerivedType() && "Unknown kind of DIType");
903 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
906 addToContextOwner(TyDIE, Ty.getContext());
910 /// addType - Add a new type attribute to the specified entity.
911 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
915 // Check for pre-existence.
916 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
917 // If it exists then use the existing value.
919 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
924 DIE *Buffer = getOrCreateTypeDIE(Ty);
927 Entry = createDIEEntry(Buffer);
928 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
930 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
933 /// constructTypeDIE - Construct basic type die from DIBasicType.
934 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
935 // Get core information.
936 StringRef Name = BTy.getName();
937 Buffer.setTag(dwarf::DW_TAG_base_type);
938 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
941 // Add name if not anonymous or intermediate type.
943 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
944 uint64_t Size = BTy.getSizeInBits() >> 3;
945 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
948 /// constructTypeDIE - Construct derived type die from DIDerivedType.
949 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
950 // Get core information.
951 StringRef Name = DTy.getName();
952 uint64_t Size = DTy.getSizeInBits() >> 3;
953 unsigned Tag = DTy.getTag();
955 // FIXME - Workaround for templates.
956 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
960 // Map to main type, void will not have a type.
961 DIType FromTy = DTy.getTypeDerivedFrom();
962 addType(&Buffer, FromTy);
964 // Add name if not anonymous or intermediate type.
966 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
968 // Add size if non-zero (derived types might be zero-sized.)
970 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
972 // Add source line info if available and TyDesc is not a forward declaration.
973 if (!DTy.isForwardDecl())
974 addSourceLine(&Buffer, &DTy);
977 /// constructTypeDIE - Construct type DIE from DICompositeType.
978 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
979 // Get core information.
980 StringRef Name = CTy.getName();
982 uint64_t Size = CTy.getSizeInBits() >> 3;
983 unsigned Tag = CTy.getTag();
987 case dwarf::DW_TAG_vector_type:
988 case dwarf::DW_TAG_array_type:
989 constructArrayTypeDIE(Buffer, &CTy);
991 case dwarf::DW_TAG_enumeration_type: {
992 DIArray Elements = CTy.getTypeArray();
994 // Add enumerators to enumeration type.
995 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
997 DIDescriptor Enum(Elements.getElement(i).getNode());
998 if (Enum.isEnumerator()) {
999 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode()));
1000 Buffer.addChild(ElemDie);
1005 case dwarf::DW_TAG_subroutine_type: {
1007 DIArray Elements = CTy.getTypeArray();
1008 DIDescriptor RTy = Elements.getElement(0);
1009 addType(&Buffer, DIType(RTy.getNode()));
1011 // Add prototype flag.
1012 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1015 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1016 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1017 DIDescriptor Ty = Elements.getElement(i);
1018 addType(Arg, DIType(Ty.getNode()));
1019 Buffer.addChild(Arg);
1023 case dwarf::DW_TAG_structure_type:
1024 case dwarf::DW_TAG_union_type:
1025 case dwarf::DW_TAG_class_type: {
1026 // Add elements to structure type.
1027 DIArray Elements = CTy.getTypeArray();
1029 // A forward struct declared type may not have elements available.
1030 unsigned N = Elements.getNumElements();
1034 // Add elements to structure type.
1035 for (unsigned i = 0; i < N; ++i) {
1036 DIDescriptor Element = Elements.getElement(i);
1037 DIE *ElemDie = NULL;
1038 if (Element.isSubprogram())
1039 ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
1040 else if (Element.isVariable()) {
1041 DIVariable DV(Element.getNode());
1042 ElemDie = new DIE(dwarf::DW_TAG_variable);
1043 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1045 addType(ElemDie, DV.getType());
1046 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1047 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1048 addSourceLine(ElemDie, &DV);
1049 } else if (Element.isDerivedType())
1050 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
1053 Buffer.addChild(ElemDie);
1056 if (CTy.isAppleBlockExtension())
1057 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1059 unsigned RLang = CTy.getRunTimeLang();
1061 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1062 dwarf::DW_FORM_data1, RLang);
1064 DICompositeType ContainingType = CTy.getContainingType();
1065 if (DIDescriptor(ContainingType.getNode()).isCompositeType())
1066 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1067 getOrCreateTypeDIE(DIType(ContainingType.getNode())));
1074 // Add name if not anonymous or intermediate type.
1076 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1078 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
1079 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1080 // Add size if non-zero (derived types might be zero-sized.)
1082 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1084 // Add zero size if it is not a forward declaration.
1085 if (CTy.isForwardDecl())
1086 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1088 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1091 // Add source line info if available.
1092 if (!CTy.isForwardDecl())
1093 addSourceLine(&Buffer, &CTy);
1097 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1098 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1099 int64_t L = SR.getLo();
1100 int64_t H = SR.getHi();
1101 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1103 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1105 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1106 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1108 Buffer.addChild(DW_Subrange);
1111 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1112 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1113 DICompositeType *CTy) {
1114 Buffer.setTag(dwarf::DW_TAG_array_type);
1115 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1116 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1118 // Emit derived type.
1119 addType(&Buffer, CTy->getTypeDerivedFrom());
1120 DIArray Elements = CTy->getTypeArray();
1122 // Get an anonymous type for index type.
1123 DIE *IdxTy = ModuleCU->getIndexTyDie();
1125 // Construct an anonymous type for index type.
1126 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1127 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1128 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1129 dwarf::DW_ATE_signed);
1130 ModuleCU->addDie(IdxTy);
1131 ModuleCU->setIndexTyDie(IdxTy);
1134 // Add subranges to array type.
1135 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1136 DIDescriptor Element = Elements.getElement(i);
1137 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1138 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1142 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1143 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1144 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1145 StringRef Name = ETy.getName();
1146 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1147 int64_t Value = ETy.getEnumValue();
1148 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1152 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1153 /// printer to not emit usual symbol prefix before the symbol name is used then
1154 /// return linkage name after skipping this special LLVM prefix.
1155 static StringRef getRealLinkageName(StringRef LinkageName) {
1157 if (LinkageName.startswith(StringRef(&One, 1)))
1158 return LinkageName.substr(1);
1162 /// createGlobalVariableDIE - Create new DIE using GV.
1163 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1164 // If the global variable was optmized out then no need to create debug info
1166 if (!GV.getGlobal()) return NULL;
1167 if (GV.getDisplayName().empty()) return NULL;
1169 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1170 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1171 GV.getDisplayName());
1173 StringRef LinkageName = GV.getLinkageName();
1174 if (!LinkageName.empty())
1175 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1176 getRealLinkageName(LinkageName));
1178 addType(GVDie, GV.getType());
1179 if (!GV.isLocalToUnit())
1180 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1181 addSourceLine(GVDie, &GV);
1186 /// createMemberDIE - Create new member DIE.
1187 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1188 DIE *MemberDie = new DIE(DT.getTag());
1189 StringRef Name = DT.getName();
1191 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1193 addType(MemberDie, DT.getTypeDerivedFrom());
1195 addSourceLine(MemberDie, &DT);
1197 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1198 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1200 uint64_t Size = DT.getSizeInBits();
1201 uint64_t FieldSize = DT.getOriginalTypeSize();
1203 if (Size != FieldSize) {
1205 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1206 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1208 uint64_t Offset = DT.getOffsetInBits();
1209 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1210 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1211 uint64_t FieldOffset = (HiMark - FieldSize);
1212 Offset -= FieldOffset;
1214 // Maybe we need to work from the other end.
1215 if (Asm->getTargetData().isLittleEndian())
1216 Offset = FieldSize - (Offset + Size);
1217 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1219 // Here WD_AT_data_member_location points to the anonymous
1220 // field that includes this bit field.
1221 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1224 // This is not a bitfield.
1225 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1227 if (DT.getTag() == dwarf::DW_TAG_inheritance
1228 && DT.isVirtual()) {
1230 // For C++, virtual base classes are not at fixed offset. Use following
1231 // expression to extract appropriate offset from vtable.
1232 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1234 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1235 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1236 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1237 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1238 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1239 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1240 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1241 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1243 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1246 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1248 if (DT.isProtected())
1249 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1250 dwarf::DW_ACCESS_protected);
1251 else if (DT.isPrivate())
1252 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1253 dwarf::DW_ACCESS_private);
1254 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1255 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1256 dwarf::DW_ACCESS_public);
1258 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1259 dwarf::DW_VIRTUALITY_virtual);
1263 /// createSubprogramDIE - Create new DIE using SP.
1264 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1265 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1269 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1270 // Constructors and operators for anonymous aggregates do not have names.
1271 if (!SP.getName().empty())
1272 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1274 StringRef LinkageName = SP.getLinkageName();
1275 if (!LinkageName.empty())
1276 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1277 getRealLinkageName(LinkageName));
1279 addSourceLine(SPDie, &SP);
1281 // Add prototyped tag, if C or ObjC.
1282 unsigned Lang = SP.getCompileUnit().getLanguage();
1283 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1284 Lang == dwarf::DW_LANG_ObjC)
1285 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1288 DICompositeType SPTy = SP.getType();
1289 DIArray Args = SPTy.getTypeArray();
1290 unsigned SPTag = SPTy.getTag();
1292 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1293 addType(SPDie, SPTy);
1295 addType(SPDie, DIType(Args.getElement(0).getNode()));
1297 unsigned VK = SP.getVirtuality();
1299 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1300 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1301 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1302 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1303 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1304 ContainingTypeMap.insert(std::make_pair(SPDie,
1305 SP.getContainingType().getNode()));
1308 if (MakeDecl || !SP.isDefinition()) {
1309 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1311 // Add arguments. Do not add arguments for subprogram definition. They will
1312 // be handled while processing variables.
1313 DICompositeType SPTy = SP.getType();
1314 DIArray Args = SPTy.getTypeArray();
1315 unsigned SPTag = SPTy.getTag();
1317 if (SPTag == dwarf::DW_TAG_subroutine_type)
1318 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1319 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1320 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1322 if (ATy.isArtificial())
1323 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1324 SPDie->addChild(Arg);
1328 if (SP.isArtificial())
1329 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1331 // DW_TAG_inlined_subroutine may refer to this DIE.
1332 ModuleCU->insertDIE(SP.getNode(), SPDie);
1334 if (!DisableFramePointerElim(*Asm->MF))
1335 addUInt(SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr, dwarf::DW_FORM_flag, 1);
1340 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1341 assert(N && "Invalid Scope encoding!");
1343 DbgScope *AScope = AbstractScopes.lookup(N);
1347 DbgScope *Parent = NULL;
1349 DIDescriptor Scope(N);
1350 if (Scope.isLexicalBlock()) {
1351 DILexicalBlock DB(N);
1352 DIDescriptor ParentDesc = DB.getContext();
1353 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1356 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1359 Parent->addScope(AScope);
1360 AScope->setAbstractScope();
1361 AbstractScopes[N] = AScope;
1362 if (DIDescriptor(N).isSubprogram())
1363 AbstractScopesList.push_back(AScope);
1367 /// isSubprogramContext - Return true if Context is either a subprogram
1368 /// or another context nested inside a subprogram.
1369 static bool isSubprogramContext(MDNode *Context) {
1372 DIDescriptor D(Context);
1373 if (D.isSubprogram())
1376 return isSubprogramContext(DIType(Context).getContext().getNode());
1380 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1381 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1382 /// If there are global variables in this scope then create and insert
1383 /// DIEs for these variables.
1384 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1385 DIE *SPDie = ModuleCU->getDIE(SPNode);
1386 assert(SPDie && "Unable to find subprogram DIE!");
1387 DISubprogram SP(SPNode);
1389 // There is not any need to generate specification DIE for a function
1390 // defined at compile unit level. If a function is defined inside another
1391 // function then gdb prefers the definition at top level and but does not
1392 // expect specification DIE in parent function. So avoid creating
1393 // specification DIE for a function defined inside a function.
1394 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1395 !SP.getContext().isFile() &&
1396 !isSubprogramContext(SP.getContext().getNode())) {
1397 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1400 DICompositeType SPTy = SP.getType();
1401 DIArray Args = SPTy.getTypeArray();
1402 unsigned SPTag = SPTy.getTag();
1403 if (SPTag == dwarf::DW_TAG_subroutine_type)
1404 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1405 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1406 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1408 if (ATy.isArtificial())
1409 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1410 SPDie->addChild(Arg);
1412 DIE *SPDeclDie = SPDie;
1413 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1414 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1416 ModuleCU->addDie(SPDie);
1419 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1420 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1421 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1422 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1423 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1424 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1425 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1427 if (!DISubprogram(SPNode).isLocalToUnit())
1428 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1433 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1434 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1435 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1437 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1438 if (Scope->isAbstractScope())
1441 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1445 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1446 if (Ranges.size() > 1) {
1447 // .debug_range section has not been laid out yet. Emit offset in
1448 // .debug_range as a uint, size 4, for now. emitDIE will handle
1449 // DW_AT_ranges appropriately.
1450 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1451 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1452 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1453 RE = Ranges.end(); RI != RE; ++RI) {
1454 DebugRangeSymbols.push_back(LabelsBeforeInsn.lookup(RI->first));
1455 DebugRangeSymbols.push_back(LabelsAfterInsn.lookup(RI->second));
1457 DebugRangeSymbols.push_back(NULL);
1458 DebugRangeSymbols.push_back(NULL);
1462 MCSymbol *Start = LabelsBeforeInsn.lookup(RI->first);
1463 MCSymbol *End = LabelsAfterInsn.lookup(RI->second);
1465 if (Start == 0 || End == 0) return 0;
1467 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1468 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1470 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1471 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1476 /// constructInlinedScopeDIE - This scope represents inlined body of
1477 /// a function. Construct DIE to represent this concrete inlined copy
1478 /// of the function.
1479 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1481 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1482 assert (Ranges.empty() == false
1483 && "DbgScope does not have instruction markers!");
1485 // FIXME : .debug_inlined section specification does not clearly state how
1486 // to emit inlined scope that is split into multiple instruction ranges.
1487 // For now, use first instruction range and emit low_pc/high_pc pair and
1488 // corresponding .debug_inlined section entry for this pair.
1489 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1490 MCSymbol *StartLabel = LabelsBeforeInsn.lookup(RI->first);
1491 MCSymbol *EndLabel = LabelsAfterInsn.lookup(RI->second);
1493 if (StartLabel == 0 || EndLabel == 0) {
1494 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1497 assert(StartLabel->isDefined() &&
1498 "Invalid starting label for an inlined scope!");
1499 assert(EndLabel->isDefined() &&
1500 "Invalid end label for an inlined scope!");
1502 if (!Scope->getScopeNode())
1504 DIScope DS(Scope->getScopeNode());
1505 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1507 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1508 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1509 assert(OriginDIE && "Unable to find Origin DIE!");
1510 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1511 dwarf::DW_FORM_ref4, OriginDIE);
1513 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1514 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1516 InlinedSubprogramDIEs.insert(OriginDIE);
1518 // Track the start label for this inlined function.
1519 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1520 I = InlineInfo.find(InlinedSP.getNode());
1522 if (I == InlineInfo.end()) {
1523 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel,
1525 InlinedSPNodes.push_back(InlinedSP.getNode());
1527 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1529 DILocation DL(Scope->getInlinedAt());
1530 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1531 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1537 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1538 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1539 // Get the descriptor.
1540 const DIVariable &VD = DV->getVariable();
1541 StringRef Name = VD.getName();
1545 // Translate tag to proper Dwarf tag. The result variable is dropped for
1548 switch (VD.getTag()) {
1549 case dwarf::DW_TAG_return_variable:
1551 case dwarf::DW_TAG_arg_variable:
1552 Tag = dwarf::DW_TAG_formal_parameter;
1554 case dwarf::DW_TAG_auto_variable: // fall thru
1556 Tag = dwarf::DW_TAG_variable;
1560 // Define variable debug information entry.
1561 DIE *VariableDie = new DIE(Tag);
1565 if (DbgVariable *AV = DV->getAbstractVariable())
1566 AbsDIE = AV->getDIE();
1569 DIScope DS(Scope->getScopeNode());
1570 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1571 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1573 assert(OriginSPDIE && "Unable to find Origin DIE for the SP!");
1574 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1575 assert(AbsDIE && "Unable to find Origin DIE for the Variable!");
1576 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1577 dwarf::DW_FORM_ref4, AbsDIE);
1580 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1581 addSourceLine(VariableDie, &VD);
1583 // Add variable type.
1584 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1585 // addresses instead.
1586 if (VD.isBlockByrefVariable())
1587 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1589 addType(VariableDie, VD.getType());
1592 // Add variable address.
1593 if (!Scope->isAbstractScope()) {
1594 // Check if variable is described by DBG_VALUE instruction.
1595 if (const MachineInstr *DVInsn = DV->getDbgValue()) {
1596 bool updated = false;
1597 // FIXME : Handle getNumOperands != 3
1598 if (DVInsn->getNumOperands() == 3) {
1599 if (DVInsn->getOperand(0).isReg())
1600 updated = addRegisterAddress(VariableDie, DV, DVInsn->getOperand(0));
1601 else if (DVInsn->getOperand(0).isImm())
1602 updated = addConstantValue(VariableDie, DV, DVInsn->getOperand(0));
1603 else if (DVInsn->getOperand(0).isFPImm())
1604 updated = addConstantFPValue(VariableDie, DV, DVInsn->getOperand(0));
1607 // If variableDie is not updated then DBG_VALUE instruction does not
1608 // have valid variable info.
1614 MachineLocation Location;
1616 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1617 int Offset = RI->getFrameIndexReference(*Asm->MF, DV->getFrameIndex(),
1619 Location.set(FrameReg, Offset);
1621 if (VD.hasComplexAddress())
1622 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1623 else if (VD.isBlockByrefVariable())
1624 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1626 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1630 if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1631 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1632 DV->setDIE(VariableDie);
1637 void DwarfDebug::addPubTypes(DISubprogram SP) {
1638 DICompositeType SPTy = SP.getType();
1639 unsigned SPTag = SPTy.getTag();
1640 if (SPTag != dwarf::DW_TAG_subroutine_type)
1643 DIArray Args = SPTy.getTypeArray();
1644 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1645 DIType ATy(Args.getElement(i).getNode());
1648 DICompositeType CATy = getDICompositeType(ATy);
1649 if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty()
1650 && !CATy.isForwardDecl()) {
1651 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1652 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1657 /// constructScopeDIE - Construct a DIE for this scope.
1658 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1659 if (!Scope || !Scope->getScopeNode())
1662 DIScope DS(Scope->getScopeNode());
1663 DIE *ScopeDIE = NULL;
1664 if (Scope->getInlinedAt())
1665 ScopeDIE = constructInlinedScopeDIE(Scope);
1666 else if (DS.isSubprogram()) {
1667 if (Scope->isAbstractScope())
1668 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1670 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1673 ScopeDIE = constructLexicalScopeDIE(Scope);
1674 if (!ScopeDIE) return NULL;
1676 // Add variables to scope.
1677 const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1678 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1679 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1681 ScopeDIE->addChild(VariableDIE);
1684 // Add nested scopes.
1685 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1686 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1687 // Define the Scope debug information entry.
1688 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1690 ScopeDIE->addChild(NestedDIE);
1693 if (DS.isSubprogram())
1694 addPubTypes(DISubprogram(DS.getNode()));
1699 /// GetOrCreateSourceID - Look up the source id with the given directory and
1700 /// source file names. If none currently exists, create a new id and insert it
1701 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1703 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1705 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1706 if (DI != DirectoryIdMap.end()) {
1707 DId = DI->getValue();
1709 DId = DirectoryNames.size() + 1;
1710 DirectoryIdMap[DirName] = DId;
1711 DirectoryNames.push_back(DirName);
1715 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1716 if (FI != SourceFileIdMap.end()) {
1717 FId = FI->getValue();
1719 FId = SourceFileNames.size() + 1;
1720 SourceFileIdMap[FileName] = FId;
1721 SourceFileNames.push_back(FileName);
1724 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1725 SourceIdMap.find(std::make_pair(DId, FId));
1726 if (SI != SourceIdMap.end())
1729 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1730 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1731 SourceIds.push_back(std::make_pair(DId, FId));
1736 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1737 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1738 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1741 NDie = new DIE(dwarf::DW_TAG_namespace);
1742 ModuleCU->insertDIE(NS.getNode(), NDie);
1743 if (!NS.getName().empty())
1744 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1745 addSourceLine(NDie, &NS);
1746 addToContextOwner(NDie, NS.getContext());
1750 void DwarfDebug::constructCompileUnit(MDNode *N) {
1751 DICompileUnit DIUnit(N);
1752 // Use first compile unit marked as isMain as the compile unit for this
1754 if (ModuleCU || !DIUnit.isMain())
1756 StringRef FN = DIUnit.getFilename();
1757 StringRef Dir = DIUnit.getDirectory();
1758 unsigned ID = GetOrCreateSourceID(Dir, FN);
1760 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1761 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1762 DIUnit.getProducer());
1763 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1764 DIUnit.getLanguage());
1765 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1766 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1767 // simplifies debug range entries.
1768 addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_data4, 0);
1769 // DW_AT_stmt_list is a offset of line number information for this
1770 // compile unit in debug_line section. It is always zero when only one
1771 // compile unit is emitted in one object file.
1772 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1775 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1776 if (DIUnit.isOptimized())
1777 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1779 StringRef Flags = DIUnit.getFlags();
1781 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1783 unsigned RVer = DIUnit.getRunTimeVersion();
1785 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1786 dwarf::DW_FORM_data1, RVer);
1789 "ModuleCU assigned since the top of constructCompileUnit");
1790 ModuleCU = new CompileUnit(ID, Die);
1793 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1794 DIGlobalVariable DI_GV(N);
1796 // If debug information is malformed then ignore it.
1797 if (DI_GV.Verify() == false)
1800 // Check for pre-existence.
1801 if (ModuleCU->getDIE(DI_GV.getNode()))
1804 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1809 ModuleCU->insertDIE(N, VariableDie);
1811 // Add to context owner.
1812 DIDescriptor GVContext = DI_GV.getContext();
1813 // Do not create specification DIE if context is either compile unit
1815 if (DI_GV.isDefinition() && !GVContext.isCompileUnit() &&
1816 !GVContext.isFile() &&
1817 !isSubprogramContext(GVContext.getNode())) {
1818 // Create specification DIE.
1819 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1820 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1821 dwarf::DW_FORM_ref4, VariableDie);
1822 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1823 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1824 addLabel(Block, 0, dwarf::DW_FORM_udata,
1825 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1826 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1827 addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1828 ModuleCU->addDie(VariableSpecDIE);
1830 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1831 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1832 addLabel(Block, 0, dwarf::DW_FORM_udata,
1833 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1834 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1836 addToContextOwner(VariableDie, GVContext);
1838 // Expose as global. FIXME - need to check external flag.
1839 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1841 DIType GTy = DI_GV.getType();
1842 if (GTy.isCompositeType() && !GTy.getName().empty()
1843 && !GTy.isForwardDecl()) {
1844 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1845 assert(Entry && "Missing global type!");
1846 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1851 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1854 // Check for pre-existence.
1855 if (ModuleCU->getDIE(N))
1858 if (!SP.isDefinition())
1859 // This is a method declaration which will be handled while constructing
1863 DIE *SubprogramDie = createSubprogramDIE(SP);
1866 ModuleCU->insertDIE(N, SubprogramDie);
1868 // Add to context owner.
1869 addToContextOwner(SubprogramDie, SP.getContext());
1871 // Expose as global.
1872 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1877 /// beginModule - Emit all Dwarf sections that should come prior to the
1878 /// content. Create global DIEs and emit initial debug info sections.
1879 /// This is inovked by the target AsmPrinter.
1880 void DwarfDebug::beginModule(Module *M) {
1881 if (DisableDebugInfoPrinting)
1884 DebugInfoFinder DbgFinder;
1885 DbgFinder.processModule(*M);
1887 bool HasDebugInfo = false;
1889 // Scan all the compile-units to see if there are any marked as the main unit.
1890 // if not, we do not generate debug info.
1891 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1892 E = DbgFinder.compile_unit_end(); I != E; ++I) {
1893 if (DICompileUnit(*I).isMain()) {
1894 HasDebugInfo = true;
1899 if (!HasDebugInfo) return;
1901 // Tell MMI that we have debug info.
1902 MMI->setDebugInfoAvailability(true);
1904 // Emit initial sections.
1905 EmitSectionLabels();
1907 // Create all the compile unit DIEs.
1908 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1909 E = DbgFinder.compile_unit_end(); I != E; ++I)
1910 constructCompileUnit(*I);
1912 // Create DIEs for each subprogram.
1913 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1914 E = DbgFinder.subprogram_end(); I != E; ++I)
1915 constructSubprogramDIE(*I);
1917 // Create DIEs for each global variable.
1918 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1919 E = DbgFinder.global_variable_end(); I != E; ++I)
1920 constructGlobalVariableDIE(*I);
1922 // Prime section data.
1923 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1925 // Print out .file directives to specify files for .loc directives. These are
1926 // printed out early so that they precede any .loc directives.
1927 if (Asm->MAI->hasDotLocAndDotFile()) {
1928 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1929 // Remember source id starts at 1.
1930 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1931 // FIXME: don't use sys::path for this! This should not depend on the
1933 sys::Path FullPath(getSourceDirectoryName(Id.first));
1935 FullPath.appendComponent(getSourceFileName(Id.second));
1936 assert(AppendOk && "Could not append filename to directory!");
1938 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1943 /// endModule - Emit all Dwarf sections that should come after the content.
1945 void DwarfDebug::endModule() {
1946 if (!ModuleCU) return;
1948 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1949 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1950 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1952 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1955 for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
1956 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1957 DIE *SPDie = CI->first;
1958 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1960 DIE *NDie = ModuleCU->getDIE(N);
1961 if (!NDie) continue;
1962 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1965 // Standard sections final addresses.
1966 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1967 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1968 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1969 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1971 // End text sections.
1972 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1973 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1974 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1977 // Emit common frame information.
1978 emitCommonDebugFrame();
1980 // Emit function debug frame information
1981 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1982 E = DebugFrames.end(); I != E; ++I)
1983 emitFunctionDebugFrame(*I);
1985 // Compute DIE offsets and sizes.
1986 computeSizeAndOffsets();
1988 // Emit all the DIEs into a debug info section
1991 // Corresponding abbreviations into a abbrev section.
1992 emitAbbreviations();
1994 // Emit source line correspondence into a debug line section.
1997 // Emit info into a debug pubnames section.
1998 emitDebugPubNames();
2000 // Emit info into a debug pubtypes section.
2001 emitDebugPubTypes();
2003 // Emit info into a debug loc section.
2006 // Emit info into a debug aranges section.
2009 // Emit info into a debug ranges section.
2012 // Emit info into a debug macinfo section.
2015 // Emit inline info.
2016 emitDebugInlineInfo();
2018 // Emit info into a debug str section.
2022 ModuleCU = NULL; // Reset for the next Module, if any.
2025 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2026 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2028 DebugLoc ScopeLoc) {
2030 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2032 return AbsDbgVariable;
2034 LLVMContext &Ctx = Var.getNode()->getContext();
2035 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2039 AbsDbgVariable = new DbgVariable(Var, FrameIdx,
2040 NULL /* No more-abstract variable*/);
2041 Scope->addVariable(AbsDbgVariable);
2042 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2043 return AbsDbgVariable;
2046 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2047 /// FIXME : Refactor findAbstractVariable.
2048 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2049 const MachineInstr *MI,
2050 DebugLoc ScopeLoc) {
2052 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2054 return AbsDbgVariable;
2056 LLVMContext &Ctx = Var.getNode()->getContext();
2057 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2061 AbsDbgVariable = new DbgVariable(Var, MI,
2062 NULL /* No more-abstract variable*/);
2063 Scope->addVariable(AbsDbgVariable);
2064 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2065 DbgValueStartMap[MI] = AbsDbgVariable;
2066 return AbsDbgVariable;
2069 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2070 void DwarfDebug::collectVariableInfo() {
2071 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2073 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2074 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2075 VE = VMap.end(); VI != VE; ++VI) {
2076 MDNode *Var = VI->first;
2079 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2081 DbgScope *Scope = 0;
2082 if (MDNode *IA = VP.second.getInlinedAt(Ctx))
2083 Scope = ConcreteScopes.lookup(IA);
2085 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2087 // If variable scope is not found then skip this variable.
2091 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, VP.second);
2092 DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
2093 Scope->addVariable(RegVar);
2096 // Collect variable information from DBG_VALUE machine instructions;
2097 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2099 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2101 const MachineInstr *MInsn = II;
2102 if (!MInsn->isDebugValue())
2105 // FIXME : Lift this restriction.
2106 if (MInsn->getNumOperands() != 3)
2109 // Ignore Undef values.
2110 if (MInsn->getOperand(0).isReg() && !MInsn->getOperand(0).getReg())
2114 const_cast<MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1)
2116 if (DV.getTag() == dwarf::DW_TAG_arg_variable) {
2117 // FIXME Handle inlined subroutine arguments.
2118 DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL);
2119 CurrentFnDbgScope->addVariable(ArgVar);
2120 DbgValueStartMap[MInsn] = ArgVar;
2124 DebugLoc DL = MInsn->getDebugLoc();
2125 if (DL.isUnknown()) continue;
2126 DbgScope *Scope = 0;
2127 if (MDNode *IA = DL.getInlinedAt(Ctx))
2128 Scope = ConcreteScopes.lookup(IA);
2130 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2132 // If variable scope is not found then skip this variable.
2136 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL);
2137 DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable);
2138 DbgValueStartMap[MInsn] = RegVar;
2139 Scope->addVariable(RegVar);
2144 /// beginScope - Process beginning of a scope.
2145 void DwarfDebug::beginScope(const MachineInstr *MI) {
2147 DebugLoc DL = MI->getDebugLoc();
2151 MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2153 // FIXME: Should only verify each scope once!
2154 if (!DIScope(Scope).Verify())
2157 // DBG_VALUE instruction establishes new value.
2158 if (MI->isDebugValue()) {
2159 DenseMap<const MachineInstr *, DbgVariable *>::iterator DI
2160 = DbgValueStartMap.find(MI);
2161 if (DI != DbgValueStartMap.end()) {
2162 MCSymbol *Label = NULL;
2163 if (DL == PrevInstLoc)
2166 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2170 DI->second->setDbgValueLabel(Label);
2175 // Emit a label to indicate location change. This is used for line
2176 // table even if this instruction does not start a new scope.
2177 MCSymbol *Label = NULL;
2178 if (DL == PrevInstLoc)
2181 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2186 // If this instruction begins a scope then note down corresponding label.
2187 if (InsnsBeginScopeSet.count(MI) != 0)
2188 LabelsBeforeInsn[MI] = Label;
2191 /// endScope - Process end of a scope.
2192 void DwarfDebug::endScope(const MachineInstr *MI) {
2193 if (InsnsEndScopeSet.count(MI) != 0) {
2194 // Emit a label if this instruction ends a scope.
2195 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2196 Asm->OutStreamer.EmitLabel(Label);
2197 LabelsAfterInsn[MI] = Label;
2201 /// getOrCreateDbgScope - Create DbgScope for the scope.
2202 DbgScope *DwarfDebug::getOrCreateDbgScope(MDNode *Scope, MDNode *InlinedAt) {
2204 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2207 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2208 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2209 if (DIDescriptor(Scope).isLexicalBlock()) {
2211 getOrCreateDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2212 WScope->setParent(Parent);
2213 Parent->addScope(WScope);
2216 if (!WScope->getParent()) {
2217 StringRef SPName = DISubprogram(Scope).getLinkageName();
2218 if (SPName == Asm->MF->getFunction()->getName())
2219 CurrentFnDbgScope = WScope;
2225 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2229 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2230 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2231 DILocation DL(InlinedAt);
2233 getOrCreateDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2234 WScope->setParent(Parent);
2235 Parent->addScope(WScope);
2237 ConcreteScopes[InlinedAt] = WScope;
2238 getOrCreateAbstractScope(Scope);
2243 /// hasValidLocation - Return true if debug location entry attached with
2244 /// machine instruction encodes valid location info.
2245 static bool hasValidLocation(LLVMContext &Ctx,
2246 const MachineInstr *MInsn,
2247 MDNode *&Scope, MDNode *&InlinedAt) {
2248 if (MInsn->isDebugValue())
2250 DebugLoc DL = MInsn->getDebugLoc();
2251 if (DL.isUnknown()) return false;
2253 MDNode *S = DL.getScope(Ctx);
2255 // There is no need to create another DIE for compile unit. For all
2256 // other scopes, create one DbgScope now. This will be translated
2257 // into a scope DIE at the end.
2258 if (DIScope(S).isCompileUnit()) return false;
2261 InlinedAt = DL.getInlinedAt(Ctx);
2265 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2267 static void calculateDominanceGraph(DbgScope *Scope) {
2268 assert (Scope && "Unable to calculate scop edominance graph!");
2269 SmallVector<DbgScope *, 4> WorkStack;
2270 WorkStack.push_back(Scope);
2271 unsigned Counter = 0;
2272 while (!WorkStack.empty()) {
2273 DbgScope *WS = WorkStack.back();
2274 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2275 bool visitedChildren = false;
2276 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2277 SE = Children.end(); SI != SE; ++SI) {
2278 DbgScope *ChildScope = *SI;
2279 if (!ChildScope->getDFSOut()) {
2280 WorkStack.push_back(ChildScope);
2281 visitedChildren = true;
2282 ChildScope->setDFSIn(++Counter);
2286 if (!visitedChildren) {
2287 WorkStack.pop_back();
2288 WS->setDFSOut(++Counter);
2293 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2295 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2296 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2299 unsigned PrevDFSIn = 0;
2300 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2302 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2304 const MachineInstr *MInsn = II;
2305 MDNode *Scope = NULL;
2306 MDNode *InlinedAt = NULL;
2308 // Check if instruction has valid location information.
2309 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2313 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2314 MI2ScopeMap.find(MInsn);
2315 if (DI != MI2ScopeMap.end()) {
2316 DbgScope *S = DI->second;
2317 dbgs() << S->getDFSIn();
2318 PrevDFSIn = S->getDFSIn();
2320 dbgs() << PrevDFSIn;
2322 dbgs() << " [ x" << PrevDFSIn;
2330 /// extractScopeInformation - Scan machine instructions in this function
2331 /// and collect DbgScopes. Return true, if at least one scope was found.
2332 bool DwarfDebug::extractScopeInformation() {
2333 // If scope information was extracted using .dbg intrinsics then there is not
2334 // any need to extract these information by scanning each instruction.
2335 if (!DbgScopeMap.empty())
2338 // Scan each instruction and create scopes. First build working set of scopes.
2339 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2340 SmallVector<DbgRange, 4> MIRanges;
2341 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2342 MDNode *PrevScope = NULL;
2343 MDNode *PrevInlinedAt = NULL;
2344 const MachineInstr *RangeBeginMI = NULL;
2345 const MachineInstr *PrevMI = NULL;
2346 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2348 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2350 const MachineInstr *MInsn = II;
2351 MDNode *Scope = NULL;
2352 MDNode *InlinedAt = NULL;
2354 // Check if instruction has valid location information.
2355 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2360 // If scope has not changed then skip this instruction.
2361 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2367 // If we have alread seen a beginning of a instruction range and
2368 // current instruction scope does not match scope of first instruction
2369 // in this range then create a new instruction range.
2370 DbgRange R(RangeBeginMI, PrevMI);
2371 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2372 MIRanges.push_back(R);
2375 // This is a beginning of a new instruction range.
2376 RangeBeginMI = MInsn;
2378 // Reset previous markers.
2381 PrevInlinedAt = InlinedAt;
2385 // Create last instruction range.
2386 if (RangeBeginMI && PrevMI && PrevScope) {
2387 DbgRange R(RangeBeginMI, PrevMI);
2388 MIRanges.push_back(R);
2389 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2392 if (!CurrentFnDbgScope)
2395 calculateDominanceGraph(CurrentFnDbgScope);
2397 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2399 // Find ranges of instructions covered by each DbgScope;
2400 DbgScope *PrevDbgScope = NULL;
2401 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2402 RE = MIRanges.end(); RI != RE; ++RI) {
2403 const DbgRange &R = *RI;
2404 DbgScope *S = MI2ScopeMap.lookup(R.first);
2405 assert (S && "Lost DbgScope for a machine instruction!");
2406 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2407 PrevDbgScope->closeInsnRange(S);
2408 S->openInsnRange(R.first);
2409 S->extendInsnRange(R.second);
2414 PrevDbgScope->closeInsnRange();
2416 identifyScopeMarkers();
2418 return !DbgScopeMap.empty();
2421 /// identifyScopeMarkers() -
2422 /// Each DbgScope has first instruction and last instruction to mark beginning
2423 /// and end of a scope respectively. Create an inverse map that list scopes
2424 /// starts (and ends) with an instruction. One instruction may start (or end)
2425 /// multiple scopes. Ignore scopes that are not reachable.
2426 void DwarfDebug::identifyScopeMarkers() {
2427 SmallVector<DbgScope *, 4> WorkList;
2428 WorkList.push_back(CurrentFnDbgScope);
2429 while (!WorkList.empty()) {
2430 DbgScope *S = WorkList.pop_back_val();
2432 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2433 if (!Children.empty())
2434 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2435 SE = Children.end(); SI != SE; ++SI)
2436 WorkList.push_back(*SI);
2438 if (S->isAbstractScope())
2441 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2444 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2445 RE = Ranges.end(); RI != RE; ++RI) {
2446 assert(RI->first && "DbgRange does not have first instruction!");
2447 assert(RI->second && "DbgRange does not have second instruction!");
2448 InsnsBeginScopeSet.insert(RI->first);
2449 InsnsEndScopeSet.insert(RI->second);
2454 /// FindFirstDebugLoc - Find the first debug location in the function. This
2455 /// is intended to be an approximation for the source position of the
2456 /// beginning of the function.
2457 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2458 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2460 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2461 MBBI != MBBE; ++MBBI) {
2462 DebugLoc DL = MBBI->getDebugLoc();
2463 if (!DL.isUnknown())
2469 /// beginFunction - Gather pre-function debug information. Assumes being
2470 /// emitted immediately after the function entry point.
2471 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2472 if (!MMI->hasDebugInfo()) return;
2473 if (!extractScopeInformation()) return;
2475 collectVariableInfo();
2477 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2478 Asm->getFunctionNumber());
2479 // Assumes in correct section after the entry point.
2480 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2482 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2484 DebugLoc FDL = FindFirstDebugLoc(MF);
2485 if (FDL.isUnknown()) return;
2487 MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2489 DISubprogram SP = getDISubprogram(Scope);
2492 Line = SP.getLineNumber();
2495 Line = FDL.getLine();
2499 recordSourceLine(Line, Col, Scope);
2502 /// endFunction - Gather and emit post-function debug information.
2504 void DwarfDebug::endFunction(const MachineFunction *MF) {
2505 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2507 if (CurrentFnDbgScope) {
2508 // Define end label for subprogram.
2509 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end",
2510 Asm->getFunctionNumber()));
2512 // Get function line info.
2513 if (!Lines.empty()) {
2514 // Get section line info.
2515 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2516 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2517 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2518 // Append the function info to section info.
2519 SectionLineInfos.insert(SectionLineInfos.end(),
2520 Lines.begin(), Lines.end());
2523 // Construct abstract scopes.
2524 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2525 AE = AbstractScopesList.end(); AI != AE; ++AI)
2526 constructScopeDIE(*AI);
2528 constructScopeDIE(CurrentFnDbgScope);
2530 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2531 MMI->getFrameMoves()));
2535 CurrentFnDbgScope = NULL;
2536 DeleteContainerSeconds(DbgScopeMap);
2537 InsnsBeginScopeSet.clear();
2538 InsnsEndScopeSet.clear();
2539 DbgValueStartMap.clear();
2540 ConcreteScopes.clear();
2541 DeleteContainerSeconds(AbstractScopes);
2542 AbstractScopesList.clear();
2543 AbstractVariables.clear();
2544 LabelsBeforeInsn.clear();
2545 LabelsAfterInsn.clear();
2550 /// recordSourceLine - Register a source line with debug info. Returns the
2551 /// unique label that was emitted and which provides correspondence to
2552 /// the source line list.
2553 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) {
2557 DIDescriptor Scope(S);
2558 if (Scope.isCompileUnit()) {
2559 DICompileUnit CU(S);
2560 Dir = CU.getDirectory();
2561 Fn = CU.getFilename();
2562 } else if (Scope.isSubprogram()) {
2564 Dir = SP.getDirectory();
2565 Fn = SP.getFilename();
2566 } else if (Scope.isLexicalBlock()) {
2567 DILexicalBlock DB(S);
2568 Dir = DB.getDirectory();
2569 Fn = DB.getFilename();
2571 assert(0 && "Unexpected scope info");
2573 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2574 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2575 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2577 Asm->OutStreamer.EmitLabel(Label);
2581 //===----------------------------------------------------------------------===//
2583 //===----------------------------------------------------------------------===//
2585 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2588 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2589 // Get the children.
2590 const std::vector<DIE *> &Children = Die->getChildren();
2592 // If not last sibling and has children then add sibling offset attribute.
2593 if (!Last && !Children.empty())
2594 Die->addSiblingOffset(DIEValueAllocator);
2596 // Record the abbreviation.
2597 assignAbbrevNumber(Die->getAbbrev());
2599 // Get the abbreviation for this DIE.
2600 unsigned AbbrevNumber = Die->getAbbrevNumber();
2601 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2604 Die->setOffset(Offset);
2606 // Start the size with the size of abbreviation code.
2607 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2609 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2610 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2612 // Size the DIE attribute values.
2613 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2614 // Size attribute value.
2615 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2617 // Size the DIE children if any.
2618 if (!Children.empty()) {
2619 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2620 "Children flag not set");
2622 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2623 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2625 // End of children marker.
2626 Offset += sizeof(int8_t);
2629 Die->setSize(Offset - Die->getOffset());
2633 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2635 void DwarfDebug::computeSizeAndOffsets() {
2636 // Compute size of compile unit header.
2637 static unsigned Offset =
2638 sizeof(int32_t) + // Length of Compilation Unit Info
2639 sizeof(int16_t) + // DWARF version number
2640 sizeof(int32_t) + // Offset Into Abbrev. Section
2641 sizeof(int8_t); // Pointer Size (in bytes)
2643 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2646 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2647 /// temporary label to it if SymbolStem is specified.
2648 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2649 const char *SymbolStem = 0) {
2650 Asm->OutStreamer.SwitchSection(Section);
2651 if (!SymbolStem) return 0;
2653 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2654 Asm->OutStreamer.EmitLabel(TmpSym);
2658 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2659 /// the start of each one.
2660 void DwarfDebug::EmitSectionLabels() {
2661 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2663 // Dwarf sections base addresses.
2664 if (Asm->MAI->doesDwarfRequireFrameSection()) {
2665 DwarfFrameSectionSym =
2666 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2669 DwarfInfoSectionSym =
2670 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2671 DwarfAbbrevSectionSym =
2672 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2673 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2675 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2676 EmitSectionSym(Asm, MacroInfo);
2678 EmitSectionSym(Asm, TLOF.getDwarfLineSection());
2679 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2680 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2681 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2682 DwarfStrSectionSym =
2683 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2684 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2687 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2688 EmitSectionSym(Asm, TLOF.getDataSection());
2691 /// emitDIE - Recusively Emits a debug information entry.
2693 void DwarfDebug::emitDIE(DIE *Die) {
2694 // Get the abbreviation for this DIE.
2695 unsigned AbbrevNumber = Die->getAbbrevNumber();
2696 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2698 // Emit the code (index) for the abbreviation.
2699 if (Asm->isVerbose())
2700 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2701 Twine::utohexstr(Die->getOffset()) + ":0x" +
2702 Twine::utohexstr(Die->getSize()) + " " +
2703 dwarf::TagString(Abbrev->getTag()));
2704 Asm->EmitULEB128(AbbrevNumber);
2706 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2707 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2709 // Emit the DIE attribute values.
2710 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2711 unsigned Attr = AbbrevData[i].getAttribute();
2712 unsigned Form = AbbrevData[i].getForm();
2713 assert(Form && "Too many attributes for DIE (check abbreviation)");
2715 if (Asm->isVerbose())
2716 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2719 case dwarf::DW_AT_sibling:
2720 Asm->EmitInt32(Die->getSiblingOffset());
2722 case dwarf::DW_AT_abstract_origin: {
2723 DIEEntry *E = cast<DIEEntry>(Values[i]);
2724 DIE *Origin = E->getEntry();
2725 unsigned Addr = Origin->getOffset();
2726 Asm->EmitInt32(Addr);
2729 case dwarf::DW_AT_ranges: {
2730 // DW_AT_range Value encodes offset in debug_range section.
2731 DIEInteger *V = cast<DIEInteger>(Values[i]);
2732 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2734 DwarfDebugRangeSectionSym,
2739 // Emit an attribute using the defined form.
2740 Values[i]->EmitValue(Asm, Form);
2745 // Emit the DIE children if any.
2746 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2747 const std::vector<DIE *> &Children = Die->getChildren();
2749 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2750 emitDIE(Children[j]);
2752 if (Asm->isVerbose())
2753 Asm->OutStreamer.AddComment("End Of Children Mark");
2758 /// emitDebugInfo - Emit the debug info section.
2760 void DwarfDebug::emitDebugInfo() {
2761 // Start debug info section.
2762 Asm->OutStreamer.SwitchSection(
2763 Asm->getObjFileLowering().getDwarfInfoSection());
2764 DIE *Die = ModuleCU->getCUDie();
2766 // Emit the compile units header.
2767 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2768 ModuleCU->getID()));
2770 // Emit size of content not including length itself
2771 unsigned ContentSize = Die->getSize() +
2772 sizeof(int16_t) + // DWARF version number
2773 sizeof(int32_t) + // Offset Into Abbrev. Section
2774 sizeof(int8_t) + // Pointer Size (in bytes)
2775 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2777 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2778 Asm->EmitInt32(ContentSize);
2779 Asm->OutStreamer.AddComment("DWARF version number");
2780 Asm->EmitInt16(dwarf::DWARF_VERSION);
2781 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2782 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2783 DwarfAbbrevSectionSym);
2784 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2785 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2788 // FIXME - extra padding for gdb bug.
2789 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2794 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", ModuleCU->getID()));
2797 /// emitAbbreviations - Emit the abbreviation section.
2799 void DwarfDebug::emitAbbreviations() const {
2800 // Check to see if it is worth the effort.
2801 if (!Abbreviations.empty()) {
2802 // Start the debug abbrev section.
2803 Asm->OutStreamer.SwitchSection(
2804 Asm->getObjFileLowering().getDwarfAbbrevSection());
2806 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2808 // For each abbrevation.
2809 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2810 // Get abbreviation data
2811 const DIEAbbrev *Abbrev = Abbreviations[i];
2813 // Emit the abbrevations code (base 1 index.)
2814 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2816 // Emit the abbreviations data.
2820 // Mark end of abbreviations.
2821 Asm->EmitULEB128(0, "EOM(3)");
2823 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2827 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2828 /// the line matrix.
2830 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2831 // Define last address of section.
2832 Asm->OutStreamer.AddComment("Extended Op");
2835 Asm->OutStreamer.AddComment("Op size");
2836 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2837 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2838 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2840 Asm->OutStreamer.AddComment("Section end label");
2842 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2843 Asm->getTargetData().getPointerSize(),
2846 // Mark end of matrix.
2847 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2853 /// emitDebugLines - Emit source line information.
2855 void DwarfDebug::emitDebugLines() {
2856 // If the target is using .loc/.file, the assembler will be emitting the
2857 // .debug_line table automatically.
2858 if (Asm->MAI->hasDotLocAndDotFile())
2861 // Minimum line delta, thus ranging from -10..(255-10).
2862 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2863 // Maximum line delta, thus ranging from -10..(255-10).
2864 const int MaxLineDelta = 255 + MinLineDelta;
2866 // Start the dwarf line section.
2867 Asm->OutStreamer.SwitchSection(
2868 Asm->getObjFileLowering().getDwarfLineSection());
2870 // Construct the section header.
2871 Asm->OutStreamer.AddComment("Length of Source Line Info");
2872 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
2873 Asm->GetTempSymbol("line_begin"), 4);
2874 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
2876 Asm->OutStreamer.AddComment("DWARF version number");
2877 Asm->EmitInt16(dwarf::DWARF_VERSION);
2879 Asm->OutStreamer.AddComment("Prolog Length");
2880 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
2881 Asm->GetTempSymbol("line_prolog_begin"), 4);
2882 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
2884 Asm->OutStreamer.AddComment("Minimum Instruction Length");
2886 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2888 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2889 Asm->EmitInt8(MinLineDelta);
2890 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2891 Asm->EmitInt8(MaxLineDelta);
2892 Asm->OutStreamer.AddComment("Special Opcode Base");
2893 Asm->EmitInt8(-MinLineDelta);
2895 // Line number standard opcode encodings argument count
2896 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2898 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2900 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2902 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2904 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2906 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2908 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2910 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2912 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2915 // Emit directories.
2916 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2917 const std::string &Dir = getSourceDirectoryName(DI);
2918 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
2919 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2922 Asm->OutStreamer.AddComment("End of directories");
2926 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2927 // Remember source id starts at 1.
2928 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2929 const std::string &FN = getSourceFileName(Id.second);
2930 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
2931 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2933 Asm->EmitULEB128(Id.first, "Directory #");
2934 Asm->EmitULEB128(0, "Mod date");
2935 Asm->EmitULEB128(0, "File size");
2938 Asm->OutStreamer.AddComment("End of files");
2941 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
2943 // A sequence for each text section.
2944 unsigned SecSrcLinesSize = SectionSourceLines.size();
2946 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2947 // Isolate current sections line info.
2948 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2950 // Dwarf assumes we start with first line of first source file.
2951 unsigned Source = 1;
2954 // Construct rows of the address, source, line, column matrix.
2955 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2956 const SrcLineInfo &LineInfo = LineInfos[i];
2957 MCSymbol *Label = LineInfo.getLabel();
2958 if (!Label->isDefined()) continue; // Not emitted, in dead code.
2960 if (LineInfo.getLine() == 0) continue;
2962 if (Asm->isVerbose()) {
2963 std::pair<unsigned, unsigned> SrcID =
2964 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2965 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
2967 Twine(getSourceFileName(SrcID.second)) +
2968 ":" + Twine(LineInfo.getLine()));
2971 // Define the line address.
2972 Asm->OutStreamer.AddComment("Extended Op");
2974 Asm->OutStreamer.AddComment("Op size");
2975 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2977 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2978 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2980 Asm->OutStreamer.AddComment("Location label");
2981 Asm->OutStreamer.EmitSymbolValue(Label,
2982 Asm->getTargetData().getPointerSize(),
2985 // If change of source, then switch to the new source.
2986 if (Source != LineInfo.getSourceID()) {
2987 Source = LineInfo.getSourceID();
2988 Asm->OutStreamer.AddComment("DW_LNS_set_file");
2989 Asm->EmitInt8(dwarf::DW_LNS_set_file);
2990 Asm->EmitULEB128(Source, "New Source");
2993 // If change of line.
2994 if (Line != LineInfo.getLine()) {
2995 // Determine offset.
2996 int Offset = LineInfo.getLine() - Line;
2997 int Delta = Offset - MinLineDelta;
3000 Line = LineInfo.getLine();
3002 // If delta is small enough and in range...
3003 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3004 // ... then use fast opcode.
3005 Asm->OutStreamer.AddComment("Line Delta");
3006 Asm->EmitInt8(Delta - MinLineDelta);
3008 // ... otherwise use long hand.
3009 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
3010 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
3011 Asm->EmitSLEB128(Offset, "Line Offset");
3012 Asm->OutStreamer.AddComment("DW_LNS_copy");
3013 Asm->EmitInt8(dwarf::DW_LNS_copy);
3016 // Copy the previous row (different address or source)
3017 Asm->OutStreamer.AddComment("DW_LNS_copy");
3018 Asm->EmitInt8(dwarf::DW_LNS_copy);
3022 emitEndOfLineMatrix(j + 1);
3025 if (SecSrcLinesSize == 0)
3026 // Because we're emitting a debug_line section, we still need a line
3027 // table. The linker and friends expect it to exist. If there's nothing to
3028 // put into it, emit an empty table.
3029 emitEndOfLineMatrix(1);
3031 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3034 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3036 void DwarfDebug::emitCommonDebugFrame() {
3037 if (!Asm->MAI->doesDwarfRequireFrameSection())
3040 int stackGrowth = Asm->getTargetData().getPointerSize();
3041 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3042 TargetFrameInfo::StackGrowsDown)
3045 // Start the dwarf frame section.
3046 Asm->OutStreamer.SwitchSection(
3047 Asm->getObjFileLowering().getDwarfFrameSection());
3049 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3050 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3051 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3052 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3054 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3055 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3056 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3057 Asm->OutStreamer.AddComment("CIE Version");
3058 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3059 Asm->OutStreamer.AddComment("CIE Augmentation");
3060 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3061 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3062 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3063 Asm->OutStreamer.AddComment("CIE RA Column");
3064 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3065 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3067 std::vector<MachineMove> Moves;
3068 RI->getInitialFrameState(Moves);
3070 Asm->EmitFrameMoves(Moves, 0, false);
3072 Asm->EmitAlignment(2, 0, 0, false);
3073 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3076 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3079 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3080 if (!Asm->MAI->doesDwarfRequireFrameSection())
3083 // Start the dwarf frame section.
3084 Asm->OutStreamer.SwitchSection(
3085 Asm->getObjFileLowering().getDwarfFrameSection());
3087 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3088 MCSymbol *DebugFrameBegin =
3089 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3090 MCSymbol *DebugFrameEnd =
3091 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3092 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3094 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3096 Asm->OutStreamer.AddComment("FDE CIE offset");
3097 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3098 DwarfFrameSectionSym);
3100 Asm->OutStreamer.AddComment("FDE initial location");
3101 MCSymbol *FuncBeginSym =
3102 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3103 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3104 Asm->getTargetData().getPointerSize(),
3108 Asm->OutStreamer.AddComment("FDE address range");
3109 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3110 FuncBeginSym, Asm->getTargetData().getPointerSize());
3112 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3114 Asm->EmitAlignment(2, 0, 0, false);
3115 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3118 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3120 void DwarfDebug::emitDebugPubNames() {
3121 // Start the dwarf pubnames section.
3122 Asm->OutStreamer.SwitchSection(
3123 Asm->getObjFileLowering().getDwarfPubNamesSection());
3125 Asm->OutStreamer.AddComment("Length of Public Names Info");
3126 Asm->EmitLabelDifference(
3127 Asm->GetTempSymbol("pubnames_end", ModuleCU->getID()),
3128 Asm->GetTempSymbol("pubnames_begin", ModuleCU->getID()), 4);
3130 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3131 ModuleCU->getID()));
3133 Asm->OutStreamer.AddComment("DWARF Version");
3134 Asm->EmitInt16(dwarf::DWARF_VERSION);
3136 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3137 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3138 DwarfInfoSectionSym);
3140 Asm->OutStreamer.AddComment("Compilation Unit Length");
3141 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3142 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3145 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
3146 for (StringMap<DIE*>::const_iterator
3147 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3148 const char *Name = GI->getKeyData();
3149 DIE *Entity = GI->second;
3151 Asm->OutStreamer.AddComment("DIE offset");
3152 Asm->EmitInt32(Entity->getOffset());
3154 if (Asm->isVerbose())
3155 Asm->OutStreamer.AddComment("External Name");
3156 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3159 Asm->OutStreamer.AddComment("End Mark");
3161 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3162 ModuleCU->getID()));
3165 void DwarfDebug::emitDebugPubTypes() {
3166 // Start the dwarf pubnames section.
3167 Asm->OutStreamer.SwitchSection(
3168 Asm->getObjFileLowering().getDwarfPubTypesSection());
3169 Asm->OutStreamer.AddComment("Length of Public Types Info");
3170 Asm->EmitLabelDifference(
3171 Asm->GetTempSymbol("pubtypes_end", ModuleCU->getID()),
3172 Asm->GetTempSymbol("pubtypes_begin", ModuleCU->getID()), 4);
3174 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3175 ModuleCU->getID()));
3177 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3178 Asm->EmitInt16(dwarf::DWARF_VERSION);
3180 Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
3181 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3182 DwarfInfoSectionSym);
3184 Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
3185 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3186 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3189 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
3190 for (StringMap<DIE*>::const_iterator
3191 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3192 const char *Name = GI->getKeyData();
3193 DIE * Entity = GI->second;
3195 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3196 Asm->EmitInt32(Entity->getOffset());
3198 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3199 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3202 Asm->OutStreamer.AddComment("End Mark");
3204 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3205 ModuleCU->getID()));
3208 /// emitDebugStr - Emit visible names into a debug str section.
3210 void DwarfDebug::emitDebugStr() {
3211 // Check to see if it is worth the effort.
3212 if (StringPool.empty()) return;
3214 // Start the dwarf str section.
3215 Asm->OutStreamer.SwitchSection(
3216 Asm->getObjFileLowering().getDwarfStrSection());
3218 // Get all of the string pool entries and put them in an array by their ID so
3219 // we can sort them.
3220 SmallVector<std::pair<unsigned,
3221 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3223 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3224 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3225 Entries.push_back(std::make_pair(I->second.second, &*I));
3227 array_pod_sort(Entries.begin(), Entries.end());
3229 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3230 // Emit a label for reference from debug information entries.
3231 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3233 // Emit the string itself.
3234 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3238 /// emitDebugLoc - Emit visible names into a debug loc section.
3240 void DwarfDebug::emitDebugLoc() {
3241 // Start the dwarf loc section.
3242 Asm->OutStreamer.SwitchSection(
3243 Asm->getObjFileLowering().getDwarfLocSection());
3246 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3248 void DwarfDebug::EmitDebugARanges() {
3249 // Start the dwarf aranges section.
3250 Asm->OutStreamer.SwitchSection(
3251 Asm->getObjFileLowering().getDwarfARangesSection());
3254 /// emitDebugRanges - Emit visible names into a debug ranges section.
3256 void DwarfDebug::emitDebugRanges() {
3257 // Start the dwarf ranges section.
3258 Asm->OutStreamer.SwitchSection(
3259 Asm->getObjFileLowering().getDwarfRangesSection());
3260 unsigned char Size = Asm->getTargetData().getPointerSize();
3261 for (SmallVector<const MCSymbol *, 8>::iterator
3262 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3265 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3267 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3271 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3273 void DwarfDebug::emitDebugMacInfo() {
3274 if (const MCSection *LineInfo =
3275 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3276 // Start the dwarf macinfo section.
3277 Asm->OutStreamer.SwitchSection(LineInfo);
3281 /// emitDebugInlineInfo - Emit inline info using following format.
3283 /// 1. length of section
3284 /// 2. Dwarf version number
3285 /// 3. address size.
3287 /// Entries (one "entry" for each function that was inlined):
3289 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3290 /// otherwise offset into __debug_str for regular function name.
3291 /// 2. offset into __debug_str section for regular function name.
3292 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3293 /// instances for the function.
3295 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3296 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3297 /// __debug_info section, and the low_pc is the starting address for the
3298 /// inlining instance.
3299 void DwarfDebug::emitDebugInlineInfo() {
3300 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3306 Asm->OutStreamer.SwitchSection(
3307 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3309 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3310 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3311 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3313 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3315 Asm->OutStreamer.AddComment("Dwarf Version");
3316 Asm->EmitInt16(dwarf::DWARF_VERSION);
3317 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3318 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3320 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3321 E = InlinedSPNodes.end(); I != E; ++I) {
3324 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3325 = InlineInfo.find(Node);
3326 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3327 DISubprogram SP(Node);
3328 StringRef LName = SP.getLinkageName();
3329 StringRef Name = SP.getName();
3331 Asm->OutStreamer.AddComment("MIPS linkage name");
3332 if (LName.empty()) {
3333 Asm->OutStreamer.EmitBytes(Name, 0);
3334 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3336 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3337 DwarfStrSectionSym);
3339 Asm->OutStreamer.AddComment("Function name");
3340 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3341 Asm->EmitULEB128(Labels.size(), "Inline count");
3343 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3344 LE = Labels.end(); LI != LE; ++LI) {
3345 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3346 Asm->EmitInt32(LI->second->getOffset());
3348 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3349 Asm->OutStreamer.EmitSymbolValue(LI->first,
3350 Asm->getTargetData().getPointerSize(),0);
3354 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));