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 if (TimePassesIsEnabled) {
334 NamedRegionTimer T(DbgTimerName, DWARFGroupName);
340 DwarfDebug::~DwarfDebug() {
341 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
342 DIEBlocks[j]->~DIEBlock();
345 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
346 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
347 if (Entry.first) return Entry.first;
349 Entry.second = NextStringPoolNumber++;
350 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
354 /// assignAbbrevNumber - Define a unique number for the abbreviation.
356 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
357 // Profile the node so that we can make it unique.
361 // Check the set for priors.
362 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
364 // If it's newly added.
365 if (InSet == &Abbrev) {
366 // Add to abbreviation list.
367 Abbreviations.push_back(&Abbrev);
369 // Assign the vector position + 1 as its number.
370 Abbrev.setNumber(Abbreviations.size());
372 // Assign existing abbreviation number.
373 Abbrev.setNumber(InSet->getNumber());
377 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
378 /// information entry.
379 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
380 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
384 /// addUInt - Add an unsigned integer attribute data and value.
386 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
387 unsigned Form, uint64_t Integer) {
388 if (!Form) Form = DIEInteger::BestForm(false, Integer);
389 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
390 Die->addValue(Attribute, Form, Value);
393 /// addSInt - Add an signed integer attribute data and value.
395 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
396 unsigned Form, int64_t Integer) {
397 if (!Form) Form = DIEInteger::BestForm(true, Integer);
398 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
399 Die->addValue(Attribute, Form, Value);
402 /// addString - Add a string attribute data and value. DIEString only
403 /// keeps string reference.
404 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
406 DIEValue *Value = new (DIEValueAllocator) DIEString(String);
407 Die->addValue(Attribute, Form, Value);
410 /// addLabel - Add a Dwarf label attribute data and value.
412 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
413 const MCSymbol *Label) {
414 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
415 Die->addValue(Attribute, Form, Value);
418 /// addDelta - Add a label delta attribute data and value.
420 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
421 const MCSymbol *Hi, const MCSymbol *Lo) {
422 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
423 Die->addValue(Attribute, Form, Value);
426 /// addDIEEntry - Add a DIE attribute data and value.
428 void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
430 Die->addValue(Attribute, Form, createDIEEntry(Entry));
434 /// addBlock - Add block data.
436 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
438 Block->ComputeSize(Asm);
439 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
440 Die->addValue(Attribute, Block->BestForm(), Block);
443 /// addSourceLine - Add location information to specified debug information
445 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
446 // If there is no compile unit specified, don't add a line #.
447 if (!V->getCompileUnit().Verify())
450 unsigned Line = V->getLineNumber();
451 unsigned FileID = GetOrCreateSourceID(V->getContext().getDirectory(),
452 V->getContext().getFilename());
453 assert(FileID && "Invalid file id");
454 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
455 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
458 /// addSourceLine - Add location information to specified debug information
460 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
461 // If there is no compile unit specified, don't add a line #.
462 if (!G->getCompileUnit().Verify())
465 unsigned Line = G->getLineNumber();
466 unsigned FileID = GetOrCreateSourceID(G->getContext().getDirectory(),
467 G->getContext().getFilename());
468 assert(FileID && "Invalid file id");
469 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
470 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
473 /// addSourceLine - Add location information to specified debug information
475 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
476 // If there is no compile unit specified, don't add a line #.
477 if (!SP->getCompileUnit().Verify())
479 // If the line number is 0, don't add it.
480 if (SP->getLineNumber() == 0)
483 unsigned Line = SP->getLineNumber();
484 if (!SP->getContext().Verify())
486 unsigned FileID = GetOrCreateSourceID(SP->getDirectory(),
488 assert(FileID && "Invalid file id");
489 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
490 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
493 /// addSourceLine - Add location information to specified debug information
495 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
496 // If there is no compile unit specified, don't add a line #.
497 DICompileUnit CU = Ty->getCompileUnit();
501 unsigned Line = Ty->getLineNumber();
502 if (!Ty->getContext().Verify())
504 unsigned FileID = GetOrCreateSourceID(Ty->getContext().getDirectory(),
505 Ty->getContext().getFilename());
506 assert(FileID && "Invalid file id");
507 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
508 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
511 /// addSourceLine - Add location information to specified debug information
513 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
514 // If there is no compile unit specified, don't add a line #.
515 if (!NS->getCompileUnit().Verify())
518 unsigned Line = NS->getLineNumber();
519 StringRef FN = NS->getFilename();
520 StringRef Dir = NS->getDirectory();
522 unsigned FileID = GetOrCreateSourceID(Dir, FN);
523 assert(FileID && "Invalid file id");
524 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
525 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
528 /* Byref variables, in Blocks, are declared by the programmer as
529 "SomeType VarName;", but the compiler creates a
530 __Block_byref_x_VarName struct, and gives the variable VarName
531 either the struct, or a pointer to the struct, as its type. This
532 is necessary for various behind-the-scenes things the compiler
533 needs to do with by-reference variables in blocks.
535 However, as far as the original *programmer* is concerned, the
536 variable should still have type 'SomeType', as originally declared.
538 The following function dives into the __Block_byref_x_VarName
539 struct to find the original type of the variable. This will be
540 passed back to the code generating the type for the Debug
541 Information Entry for the variable 'VarName'. 'VarName' will then
542 have the original type 'SomeType' in its debug information.
544 The original type 'SomeType' will be the type of the field named
545 'VarName' inside the __Block_byref_x_VarName struct.
547 NOTE: In order for this to not completely fail on the debugger
548 side, the Debug Information Entry for the variable VarName needs to
549 have a DW_AT_location that tells the debugger how to unwind through
550 the pointers and __Block_byref_x_VarName struct to find the actual
551 value of the variable. The function addBlockByrefType does this. */
553 /// Find the type the programmer originally declared the variable to be
554 /// and return that type.
556 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
559 unsigned tag = Ty.getTag();
561 if (tag == dwarf::DW_TAG_pointer_type) {
562 DIDerivedType DTy = DIDerivedType(Ty.getNode());
563 subType = DTy.getTypeDerivedFrom();
566 DICompositeType blockStruct = DICompositeType(subType.getNode());
567 DIArray Elements = blockStruct.getTypeArray();
569 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
570 DIDescriptor Element = Elements.getElement(i);
571 DIDerivedType DT = DIDerivedType(Element.getNode());
572 if (Name == DT.getName())
573 return (DT.getTypeDerivedFrom());
579 /// addComplexAddress - Start with the address based on the location provided,
580 /// and generate the DWARF information necessary to find the actual variable
581 /// given the extra address information encoded in the DIVariable, starting from
582 /// the starting location. Add the DWARF information to the die.
584 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
586 const MachineLocation &Location) {
587 const DIVariable &VD = DV->getVariable();
588 DIType Ty = VD.getType();
590 // Decode the original location, and use that as the start of the byref
591 // variable's location.
592 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
593 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
594 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
596 if (Location.isReg()) {
598 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
600 Reg = Reg - dwarf::DW_OP_reg0;
601 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
602 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
606 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
608 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
609 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
612 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
615 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
616 uint64_t Element = VD.getAddrElement(i);
618 if (Element == DIFactory::OpPlus) {
619 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
620 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
621 } else if (Element == DIFactory::OpDeref) {
622 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
623 } else llvm_unreachable("unknown DIFactory Opcode");
626 // Now attach the location information to the DIE.
627 addBlock(Die, Attribute, 0, Block);
630 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
631 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
632 gives the variable VarName either the struct, or a pointer to the struct, as
633 its type. This is necessary for various behind-the-scenes things the
634 compiler needs to do with by-reference variables in Blocks.
636 However, as far as the original *programmer* is concerned, the variable
637 should still have type 'SomeType', as originally declared.
639 The function getBlockByrefType dives into the __Block_byref_x_VarName
640 struct to find the original type of the variable, which is then assigned to
641 the variable's Debug Information Entry as its real type. So far, so good.
642 However now the debugger will expect the variable VarName to have the type
643 SomeType. So we need the location attribute for the variable to be an
644 expression that explains to the debugger how to navigate through the
645 pointers and struct to find the actual variable of type SomeType.
647 The following function does just that. We start by getting
648 the "normal" location for the variable. This will be the location
649 of either the struct __Block_byref_x_VarName or the pointer to the
650 struct __Block_byref_x_VarName.
652 The struct will look something like:
654 struct __Block_byref_x_VarName {
656 struct __Block_byref_x_VarName *forwarding;
657 ... <various other fields>
659 ... <maybe more fields>
662 If we are given the struct directly (as our starting point) we
663 need to tell the debugger to:
665 1). Add the offset of the forwarding field.
667 2). Follow that pointer to get the real __Block_byref_x_VarName
668 struct to use (the real one may have been copied onto the heap).
670 3). Add the offset for the field VarName, to find the actual variable.
672 If we started with a pointer to the struct, then we need to
673 dereference that pointer first, before the other steps.
674 Translating this into DWARF ops, we will need to append the following
675 to the current location description for the variable:
677 DW_OP_deref -- optional, if we start with a pointer
678 DW_OP_plus_uconst <forward_fld_offset>
680 DW_OP_plus_uconst <varName_fld_offset>
682 That is what this function does. */
684 /// addBlockByrefAddress - Start with the address based on the location
685 /// provided, and generate the DWARF information necessary to find the
686 /// actual Block variable (navigating the Block struct) based on the
687 /// starting location. Add the DWARF information to the die. For
688 /// more information, read large comment just above here.
690 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
692 const MachineLocation &Location) {
693 const DIVariable &VD = DV->getVariable();
694 DIType Ty = VD.getType();
696 unsigned Tag = Ty.getTag();
697 bool isPointer = false;
699 StringRef varName = VD.getName();
701 if (Tag == dwarf::DW_TAG_pointer_type) {
702 DIDerivedType DTy = DIDerivedType(Ty.getNode());
703 TmpTy = DTy.getTypeDerivedFrom();
707 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
709 // Find the __forwarding field and the variable field in the __Block_byref
711 DIArray Fields = blockStruct.getTypeArray();
712 DIDescriptor varField = DIDescriptor();
713 DIDescriptor forwardingField = DIDescriptor();
715 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
716 DIDescriptor Element = Fields.getElement(i);
717 DIDerivedType DT = DIDerivedType(Element.getNode());
718 StringRef fieldName = DT.getName();
719 if (fieldName == "__forwarding")
720 forwardingField = Element;
721 else if (fieldName == varName)
725 // Get the offsets for the forwarding field and the variable field.
726 unsigned forwardingFieldOffset =
727 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
728 unsigned varFieldOffset =
729 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
731 // Decode the original location, and use that as the start of the byref
732 // variable's location.
733 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
734 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
735 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
737 if (Location.isReg()) {
739 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
741 Reg = Reg - dwarf::DW_OP_reg0;
742 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
743 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
747 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
749 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
750 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
753 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
756 // If we started with a pointer to the __Block_byref... struct, then
757 // the first thing we need to do is dereference the pointer (DW_OP_deref).
759 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
761 // Next add the offset for the '__forwarding' field:
762 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
763 // adding the offset if it's 0.
764 if (forwardingFieldOffset > 0) {
765 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
766 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
769 // Now dereference the __forwarding field to get to the real __Block_byref
770 // struct: DW_OP_deref.
771 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
773 // Now that we've got the real __Block_byref... struct, add the offset
774 // for the variable's field to get to the location of the actual variable:
775 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
776 if (varFieldOffset > 0) {
777 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
778 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
781 // Now attach the location information to the DIE.
782 addBlock(Die, Attribute, 0, Block);
785 /// addAddress - Add an address attribute to a die based on the location
787 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
788 const MachineLocation &Location) {
789 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
790 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
791 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
793 if (Location.isReg()) {
795 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
797 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
798 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
802 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
804 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
805 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
808 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
811 addBlock(Die, Attribute, 0, Block);
814 /// addToContextOwner - Add Die into the list of its context owner's children.
815 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
816 if (Context.isType()) {
817 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
818 ContextDIE->addChild(Die);
819 } else if (Context.isNameSpace()) {
820 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
821 ContextDIE->addChild(Die);
822 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
823 ContextDIE->addChild(Die);
825 ModuleCU->addDie(Die);
828 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
830 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
831 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
836 TyDIE = new DIE(dwarf::DW_TAG_base_type);
837 ModuleCU->insertDIE(Ty.getNode(), TyDIE);
838 if (Ty.isBasicType())
839 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
840 else if (Ty.isCompositeType())
841 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
843 assert(Ty.isDerivedType() && "Unknown kind of DIType");
844 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
847 addToContextOwner(TyDIE, Ty.getContext());
851 /// addType - Add a new type attribute to the specified entity.
852 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
856 // Check for pre-existence.
857 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
858 // If it exists then use the existing value.
860 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
865 DIE *Buffer = getOrCreateTypeDIE(Ty);
868 Entry = createDIEEntry(Buffer);
869 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
871 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
874 /// constructTypeDIE - Construct basic type die from DIBasicType.
875 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
876 // Get core information.
877 StringRef Name = BTy.getName();
878 Buffer.setTag(dwarf::DW_TAG_base_type);
879 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
882 // Add name if not anonymous or intermediate type.
884 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
885 uint64_t Size = BTy.getSizeInBits() >> 3;
886 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
889 /// constructTypeDIE - Construct derived type die from DIDerivedType.
890 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
891 // Get core information.
892 StringRef Name = DTy.getName();
893 uint64_t Size = DTy.getSizeInBits() >> 3;
894 unsigned Tag = DTy.getTag();
896 // FIXME - Workaround for templates.
897 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
901 // Map to main type, void will not have a type.
902 DIType FromTy = DTy.getTypeDerivedFrom();
903 addType(&Buffer, FromTy);
905 // Add name if not anonymous or intermediate type.
907 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
909 // Add size if non-zero (derived types might be zero-sized.)
911 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
913 // Add source line info if available and TyDesc is not a forward declaration.
914 if (!DTy.isForwardDecl())
915 addSourceLine(&Buffer, &DTy);
918 /// constructTypeDIE - Construct type DIE from DICompositeType.
919 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
920 // Get core information.
921 StringRef Name = CTy.getName();
923 uint64_t Size = CTy.getSizeInBits() >> 3;
924 unsigned Tag = CTy.getTag();
928 case dwarf::DW_TAG_vector_type:
929 case dwarf::DW_TAG_array_type:
930 constructArrayTypeDIE(Buffer, &CTy);
932 case dwarf::DW_TAG_enumeration_type: {
933 DIArray Elements = CTy.getTypeArray();
935 // Add enumerators to enumeration type.
936 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
938 DIDescriptor Enum(Elements.getElement(i).getNode());
939 if (Enum.isEnumerator()) {
940 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode()));
941 Buffer.addChild(ElemDie);
946 case dwarf::DW_TAG_subroutine_type: {
948 DIArray Elements = CTy.getTypeArray();
949 DIDescriptor RTy = Elements.getElement(0);
950 addType(&Buffer, DIType(RTy.getNode()));
952 // Add prototype flag.
953 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
956 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
957 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
958 DIDescriptor Ty = Elements.getElement(i);
959 addType(Arg, DIType(Ty.getNode()));
960 Buffer.addChild(Arg);
964 case dwarf::DW_TAG_structure_type:
965 case dwarf::DW_TAG_union_type:
966 case dwarf::DW_TAG_class_type: {
967 // Add elements to structure type.
968 DIArray Elements = CTy.getTypeArray();
970 // A forward struct declared type may not have elements available.
971 unsigned N = Elements.getNumElements();
975 // Add elements to structure type.
976 for (unsigned i = 0; i < N; ++i) {
977 DIDescriptor Element = Elements.getElement(i);
979 if (Element.isSubprogram())
980 ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
981 else if (Element.isVariable()) {
982 DIVariable DV(Element.getNode());
983 ElemDie = new DIE(dwarf::DW_TAG_variable);
984 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
986 addType(ElemDie, DV.getType());
987 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
988 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
989 addSourceLine(ElemDie, &DV);
990 } else if (Element.isDerivedType())
991 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
994 Buffer.addChild(ElemDie);
997 if (CTy.isAppleBlockExtension())
998 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1000 unsigned RLang = CTy.getRunTimeLang();
1002 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1003 dwarf::DW_FORM_data1, RLang);
1005 DICompositeType ContainingType = CTy.getContainingType();
1006 if (DIDescriptor(ContainingType.getNode()).isCompositeType())
1007 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1008 getOrCreateTypeDIE(DIType(ContainingType.getNode())));
1015 // Add name if not anonymous or intermediate type.
1017 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1019 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
1020 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1021 // Add size if non-zero (derived types might be zero-sized.)
1023 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1025 // Add zero size if it is not a forward declaration.
1026 if (CTy.isForwardDecl())
1027 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1029 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1032 // Add source line info if available.
1033 if (!CTy.isForwardDecl())
1034 addSourceLine(&Buffer, &CTy);
1038 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1039 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1040 int64_t L = SR.getLo();
1041 int64_t H = SR.getHi();
1042 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1044 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1046 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1047 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1049 Buffer.addChild(DW_Subrange);
1052 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1053 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1054 DICompositeType *CTy) {
1055 Buffer.setTag(dwarf::DW_TAG_array_type);
1056 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1057 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1059 // Emit derived type.
1060 addType(&Buffer, CTy->getTypeDerivedFrom());
1061 DIArray Elements = CTy->getTypeArray();
1063 // Get an anonymous type for index type.
1064 DIE *IdxTy = ModuleCU->getIndexTyDie();
1066 // Construct an anonymous type for index type.
1067 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1068 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1069 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1070 dwarf::DW_ATE_signed);
1071 ModuleCU->addDie(IdxTy);
1072 ModuleCU->setIndexTyDie(IdxTy);
1075 // Add subranges to array type.
1076 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1077 DIDescriptor Element = Elements.getElement(i);
1078 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1079 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1083 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1084 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1085 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1086 StringRef Name = ETy.getName();
1087 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1088 int64_t Value = ETy.getEnumValue();
1089 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1093 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1094 /// printer to not emit usual symbol prefix before the symbol name is used then
1095 /// return linkage name after skipping this special LLVM prefix.
1096 static StringRef getRealLinkageName(StringRef LinkageName) {
1098 if (LinkageName.startswith(StringRef(&One, 1)))
1099 return LinkageName.substr(1);
1103 /// createGlobalVariableDIE - Create new DIE using GV.
1104 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1105 // If the global variable was optmized out then no need to create debug info
1107 if (!GV.getGlobal()) return NULL;
1108 if (GV.getDisplayName().empty()) return NULL;
1110 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1111 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1112 GV.getDisplayName());
1114 StringRef LinkageName = GV.getLinkageName();
1115 if (!LinkageName.empty())
1116 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1117 getRealLinkageName(LinkageName));
1119 addType(GVDie, GV.getType());
1120 if (!GV.isLocalToUnit())
1121 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1122 addSourceLine(GVDie, &GV);
1127 /// createMemberDIE - Create new member DIE.
1128 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1129 DIE *MemberDie = new DIE(DT.getTag());
1130 StringRef Name = DT.getName();
1132 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1134 addType(MemberDie, DT.getTypeDerivedFrom());
1136 addSourceLine(MemberDie, &DT);
1138 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1139 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1141 uint64_t Size = DT.getSizeInBits();
1142 uint64_t FieldSize = DT.getOriginalTypeSize();
1144 if (Size != FieldSize) {
1146 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1147 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1149 uint64_t Offset = DT.getOffsetInBits();
1150 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1151 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1152 uint64_t FieldOffset = (HiMark - FieldSize);
1153 Offset -= FieldOffset;
1155 // Maybe we need to work from the other end.
1156 if (Asm->getTargetData().isLittleEndian())
1157 Offset = FieldSize - (Offset + Size);
1158 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1160 // Here WD_AT_data_member_location points to the anonymous
1161 // field that includes this bit field.
1162 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1165 // This is not a bitfield.
1166 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1168 if (DT.getTag() == dwarf::DW_TAG_inheritance
1169 && DT.isVirtual()) {
1171 // For C++, virtual base classes are not at fixed offset. Use following
1172 // expression to extract appropriate offset from vtable.
1173 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1175 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1176 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1177 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1178 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1179 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1180 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1181 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1182 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1184 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1187 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1189 if (DT.isProtected())
1190 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1191 dwarf::DW_ACCESS_protected);
1192 else if (DT.isPrivate())
1193 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1194 dwarf::DW_ACCESS_private);
1195 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1196 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1197 dwarf::DW_ACCESS_public);
1199 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1200 dwarf::DW_VIRTUALITY_virtual);
1204 /// createSubprogramDIE - Create new DIE using SP.
1205 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1206 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1210 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1211 // Constructors and operators for anonymous aggregates do not have names.
1212 if (!SP.getName().empty())
1213 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1215 StringRef LinkageName = SP.getLinkageName();
1216 if (!LinkageName.empty())
1217 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1218 getRealLinkageName(LinkageName));
1220 addSourceLine(SPDie, &SP);
1222 // Add prototyped tag, if C or ObjC.
1223 unsigned Lang = SP.getCompileUnit().getLanguage();
1224 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1225 Lang == dwarf::DW_LANG_ObjC)
1226 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1229 DICompositeType SPTy = SP.getType();
1230 DIArray Args = SPTy.getTypeArray();
1231 unsigned SPTag = SPTy.getTag();
1233 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1234 addType(SPDie, SPTy);
1236 addType(SPDie, DIType(Args.getElement(0).getNode()));
1238 unsigned VK = SP.getVirtuality();
1240 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1241 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1242 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1243 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1244 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1245 ContainingTypeMap.insert(std::make_pair(SPDie,
1246 SP.getContainingType().getNode()));
1249 if (MakeDecl || !SP.isDefinition()) {
1250 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1252 // Add arguments. Do not add arguments for subprogram definition. They will
1253 // be handled while processing variables.
1254 DICompositeType SPTy = SP.getType();
1255 DIArray Args = SPTy.getTypeArray();
1256 unsigned SPTag = SPTy.getTag();
1258 if (SPTag == dwarf::DW_TAG_subroutine_type)
1259 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1260 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1261 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1263 if (ATy.isArtificial())
1264 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1265 SPDie->addChild(Arg);
1269 if (SP.isArtificial())
1270 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1272 // DW_TAG_inlined_subroutine may refer to this DIE.
1273 ModuleCU->insertDIE(SP.getNode(), SPDie);
1275 if (!DisableFramePointerElim(*Asm->MF))
1276 addUInt(SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr, dwarf::DW_FORM_flag, 1);
1281 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1282 assert(N && "Invalid Scope encoding!");
1284 DbgScope *AScope = AbstractScopes.lookup(N);
1288 DbgScope *Parent = NULL;
1290 DIDescriptor Scope(N);
1291 if (Scope.isLexicalBlock()) {
1292 DILexicalBlock DB(N);
1293 DIDescriptor ParentDesc = DB.getContext();
1294 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1297 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1300 Parent->addScope(AScope);
1301 AScope->setAbstractScope();
1302 AbstractScopes[N] = AScope;
1303 if (DIDescriptor(N).isSubprogram())
1304 AbstractScopesList.push_back(AScope);
1308 /// isSubprogramContext - Return true if Context is either a subprogram
1309 /// or another context nested inside a subprogram.
1310 static bool isSubprogramContext(MDNode *Context) {
1313 DIDescriptor D(Context);
1314 if (D.isSubprogram())
1317 return isSubprogramContext(DIType(Context).getContext().getNode());
1321 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1322 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1323 /// If there are global variables in this scope then create and insert
1324 /// DIEs for these variables.
1325 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1326 DIE *SPDie = ModuleCU->getDIE(SPNode);
1327 assert(SPDie && "Unable to find subprogram DIE!");
1328 DISubprogram SP(SPNode);
1330 // There is not any need to generate specification DIE for a function
1331 // defined at compile unit level. If a function is defined inside another
1332 // function then gdb prefers the definition at top level and but does not
1333 // expect specification DIE in parent function. So avoid creating
1334 // specification DIE for a function defined inside a function.
1335 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1336 !SP.getContext().isFile() &&
1337 !isSubprogramContext(SP.getContext().getNode())) {
1338 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1341 DICompositeType SPTy = SP.getType();
1342 DIArray Args = SPTy.getTypeArray();
1343 unsigned SPTag = SPTy.getTag();
1344 if (SPTag == dwarf::DW_TAG_subroutine_type)
1345 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1346 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1347 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1349 if (ATy.isArtificial())
1350 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1351 SPDie->addChild(Arg);
1353 DIE *SPDeclDie = SPDie;
1354 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1355 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1357 ModuleCU->addDie(SPDie);
1360 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1361 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1362 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1363 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1364 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1365 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1366 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1368 if (!DISubprogram(SPNode).isLocalToUnit())
1369 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1374 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1375 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1376 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1378 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1379 if (Scope->isAbstractScope())
1382 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1386 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1387 if (Ranges.size() > 1) {
1388 // .debug_range section has not been laid out yet. Emit offset in
1389 // .debug_range as a uint, size 4, for now. emitDIE will handle
1390 // DW_AT_ranges appropriately.
1391 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1392 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1393 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1394 RE = Ranges.end(); RI != RE; ++RI) {
1395 DebugRangeSymbols.push_back(InsnBeforeLabelMap.lookup(RI->first));
1396 DebugRangeSymbols.push_back(InsnAfterLabelMap.lookup(RI->second));
1398 DebugRangeSymbols.push_back(NULL);
1399 DebugRangeSymbols.push_back(NULL);
1403 MCSymbol *Start = InsnBeforeLabelMap.lookup(RI->first);
1404 MCSymbol *End = InsnAfterLabelMap.lookup(RI->second);
1406 if (Start == 0 || End == 0) return 0;
1408 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1409 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1411 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1412 Start ? Start : Asm->GetTempSymbol("func_begin",
1413 Asm->getFunctionNumber()));
1414 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1415 End ? End : Asm->GetTempSymbol("func_end",Asm->getFunctionNumber()));
1420 /// constructInlinedScopeDIE - This scope represents inlined body of
1421 /// a function. Construct DIE to represent this concrete inlined copy
1422 /// of the function.
1423 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1425 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1426 assert (Ranges.empty() == false
1427 && "DbgScope does not have instruction markers!");
1429 // FIXME : .debug_inlined section specification does not clearly state how
1430 // to emit inlined scope that is split into multiple instruction ranges.
1431 // For now, use first instruction range and emit low_pc/high_pc pair and
1432 // corresponding .debug_inlined section entry for this pair.
1433 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1434 MCSymbol *StartLabel = InsnBeforeLabelMap.lookup(RI->first);
1435 MCSymbol *EndLabel = InsnAfterLabelMap.lookup(RI->second);
1437 if (StartLabel == 0 || EndLabel == 0) {
1438 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1441 assert(StartLabel->isDefined() &&
1442 "Invalid starting label for an inlined scope!");
1443 assert(EndLabel->isDefined() &&
1444 "Invalid end label for an inlined scope!");
1446 if (!Scope->getScopeNode())
1448 DIScope DS(Scope->getScopeNode());
1449 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1451 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1452 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1453 assert(OriginDIE && "Unable to find Origin DIE!");
1454 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1455 dwarf::DW_FORM_ref4, OriginDIE);
1457 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1458 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1460 InlinedSubprogramDIEs.insert(OriginDIE);
1462 // Track the start label for this inlined function.
1463 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1464 I = InlineInfo.find(InlinedSP.getNode());
1466 if (I == InlineInfo.end()) {
1467 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel,
1469 InlinedSPNodes.push_back(InlinedSP.getNode());
1471 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1473 DILocation DL(Scope->getInlinedAt());
1474 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1475 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1481 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1482 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1483 // Get the descriptor.
1484 const DIVariable &VD = DV->getVariable();
1485 StringRef Name = VD.getName();
1489 // Translate tag to proper Dwarf tag. The result variable is dropped for
1492 switch (VD.getTag()) {
1493 case dwarf::DW_TAG_return_variable:
1495 case dwarf::DW_TAG_arg_variable:
1496 Tag = dwarf::DW_TAG_formal_parameter;
1498 case dwarf::DW_TAG_auto_variable: // fall thru
1500 Tag = dwarf::DW_TAG_variable;
1504 // Define variable debug information entry.
1505 DIE *VariableDie = new DIE(Tag);
1509 if (DbgVariable *AV = DV->getAbstractVariable())
1510 AbsDIE = AV->getDIE();
1513 DIScope DS(Scope->getScopeNode());
1514 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1515 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1517 assert(OriginSPDIE && "Unable to find Origin DIE for the SP!");
1518 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1519 assert(AbsDIE && "Unable to find Origin DIE for the Variable!");
1520 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1521 dwarf::DW_FORM_ref4, AbsDIE);
1524 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1525 addSourceLine(VariableDie, &VD);
1527 // Add variable type.
1528 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1529 // addresses instead.
1530 if (VD.isBlockByrefVariable())
1531 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1533 addType(VariableDie, VD.getType());
1536 // Add variable address.
1537 if (!Scope->isAbstractScope()) {
1538 // Check if variable is described by DBG_VALUE instruction.
1539 if (const MachineInstr *DbgValueInsn = DV->getDbgValue()) {
1540 if (DbgValueInsn->getNumOperands() == 3) {
1541 // FIXME : Handle getNumOperands != 3
1542 if (DbgValueInsn->getOperand(0).getType()
1543 == MachineOperand::MO_Register
1544 && DbgValueInsn->getOperand(0).getReg()) {
1545 MachineLocation Location;
1546 Location.set(DbgValueInsn->getOperand(0).getReg());
1547 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1548 if (MCSymbol *VS = DV->getDbgValueLabel())
1549 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1551 } else if (DbgValueInsn->getOperand(0).getType() ==
1552 MachineOperand::MO_Immediate) {
1553 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1554 unsigned Imm = DbgValueInsn->getOperand(0).getImm();
1555 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
1556 addBlock(VariableDie, dwarf::DW_AT_const_value, 0, Block);
1557 if (MCSymbol *VS = DV->getDbgValueLabel())
1558 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1560 } else if (DbgValueInsn->getOperand(0).getType() ==
1561 MachineOperand::MO_FPImmediate) {
1562 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1563 APFloat FPImm = DbgValueInsn->getOperand(0).getFPImm()->getValueAPF();
1565 // Get the raw data form of the floating point.
1566 const APInt FltVal = FPImm.bitcastToAPInt();
1567 const char *FltPtr = (const char*)FltVal.getRawData();
1569 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
1570 bool LittleEndian = Asm->getTargetData().isLittleEndian();
1571 int Incr = (LittleEndian ? 1 : -1);
1572 int Start = (LittleEndian ? 0 : NumBytes - 1);
1573 int Stop = (LittleEndian ? NumBytes : -1);
1575 // Output the constant to DWARF one byte at a time.
1576 for (; Start != Stop; Start += Incr)
1577 addUInt(Block, 0, dwarf::DW_FORM_data1,
1578 (unsigned char)0xFF & FltPtr[Start]);
1580 addBlock(VariableDie, dwarf::DW_AT_const_value, 0, Block);
1582 if (MCSymbol *VS = DV->getDbgValueLabel())
1583 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1586 //FIXME : Handle other operand types.
1592 MachineLocation Location;
1594 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1595 int Offset = RI->getFrameIndexReference(*Asm->MF, DV->getFrameIndex(),
1597 Location.set(FrameReg, Offset);
1599 if (VD.hasComplexAddress())
1600 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1601 else if (VD.isBlockByrefVariable())
1602 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1604 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1608 if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1609 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1610 DV->setDIE(VariableDie);
1615 void DwarfDebug::addPubTypes(DISubprogram SP) {
1616 DICompositeType SPTy = SP.getType();
1617 unsigned SPTag = SPTy.getTag();
1618 if (SPTag != dwarf::DW_TAG_subroutine_type)
1621 DIArray Args = SPTy.getTypeArray();
1622 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1623 DIType ATy(Args.getElement(i).getNode());
1626 DICompositeType CATy = getDICompositeType(ATy);
1627 if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty()
1628 && !CATy.isForwardDecl()) {
1629 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1630 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1635 /// constructScopeDIE - Construct a DIE for this scope.
1636 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1637 if (!Scope || !Scope->getScopeNode())
1640 DIScope DS(Scope->getScopeNode());
1641 DIE *ScopeDIE = NULL;
1642 if (Scope->getInlinedAt())
1643 ScopeDIE = constructInlinedScopeDIE(Scope);
1644 else if (DS.isSubprogram()) {
1645 if (Scope->isAbstractScope())
1646 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1648 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1651 ScopeDIE = constructLexicalScopeDIE(Scope);
1652 if (!ScopeDIE) return NULL;
1654 // Add variables to scope.
1655 const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1656 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1657 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1659 ScopeDIE->addChild(VariableDIE);
1662 // Add nested scopes.
1663 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1664 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1665 // Define the Scope debug information entry.
1666 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1668 ScopeDIE->addChild(NestedDIE);
1671 if (DS.isSubprogram())
1672 addPubTypes(DISubprogram(DS.getNode()));
1677 /// GetOrCreateSourceID - Look up the source id with the given directory and
1678 /// source file names. If none currently exists, create a new id and insert it
1679 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1681 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1683 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1684 if (DI != DirectoryIdMap.end()) {
1685 DId = DI->getValue();
1687 DId = DirectoryNames.size() + 1;
1688 DirectoryIdMap[DirName] = DId;
1689 DirectoryNames.push_back(DirName);
1693 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1694 if (FI != SourceFileIdMap.end()) {
1695 FId = FI->getValue();
1697 FId = SourceFileNames.size() + 1;
1698 SourceFileIdMap[FileName] = FId;
1699 SourceFileNames.push_back(FileName);
1702 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1703 SourceIdMap.find(std::make_pair(DId, FId));
1704 if (SI != SourceIdMap.end())
1707 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1708 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1709 SourceIds.push_back(std::make_pair(DId, FId));
1714 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1715 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1716 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1719 NDie = new DIE(dwarf::DW_TAG_namespace);
1720 ModuleCU->insertDIE(NS.getNode(), NDie);
1721 if (!NS.getName().empty())
1722 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1723 addSourceLine(NDie, &NS);
1724 addToContextOwner(NDie, NS.getContext());
1728 void DwarfDebug::constructCompileUnit(MDNode *N) {
1729 DICompileUnit DIUnit(N);
1730 // Use first compile unit marked as isMain as the compile unit for this
1732 if (ModuleCU || !DIUnit.isMain())
1734 StringRef FN = DIUnit.getFilename();
1735 StringRef Dir = DIUnit.getDirectory();
1736 unsigned ID = GetOrCreateSourceID(Dir, FN);
1738 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1739 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1740 DIUnit.getProducer());
1741 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1742 DIUnit.getLanguage());
1743 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1744 addLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, TextSectionSym);
1745 addLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1746 Asm->GetTempSymbol("text_end"));
1747 // DW_AT_stmt_list is a offset of line number information for this
1748 // compile unit in debug_line section. It is always zero when only one
1749 // compile unit is emitted in one object file.
1750 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1753 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1754 if (DIUnit.isOptimized())
1755 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1757 StringRef Flags = DIUnit.getFlags();
1759 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1761 unsigned RVer = DIUnit.getRunTimeVersion();
1763 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1764 dwarf::DW_FORM_data1, RVer);
1767 "ModuleCU assigned since the top of constructCompileUnit");
1768 ModuleCU = new CompileUnit(ID, Die);
1771 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1772 DIGlobalVariable DI_GV(N);
1774 // If debug information is malformed then ignore it.
1775 if (DI_GV.Verify() == false)
1778 // Check for pre-existence.
1779 if (ModuleCU->getDIE(DI_GV.getNode()))
1782 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1787 ModuleCU->insertDIE(N, VariableDie);
1789 // Add to context owner.
1790 DIDescriptor GVContext = DI_GV.getContext();
1791 // Do not create specification DIE if context is either compile unit
1793 if (DI_GV.isDefinition() && !GVContext.isCompileUnit() &&
1794 !GVContext.isFile() &&
1795 !isSubprogramContext(GVContext.getNode())) {
1796 // Create specification DIE.
1797 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1798 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1799 dwarf::DW_FORM_ref4, VariableDie);
1800 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1801 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1802 addLabel(Block, 0, dwarf::DW_FORM_udata,
1803 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1804 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1805 addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1806 ModuleCU->addDie(VariableSpecDIE);
1808 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1809 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1810 addLabel(Block, 0, dwarf::DW_FORM_udata,
1811 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1812 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1814 addToContextOwner(VariableDie, GVContext);
1816 // Expose as global. FIXME - need to check external flag.
1817 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1819 DIType GTy = DI_GV.getType();
1820 if (GTy.isCompositeType() && !GTy.getName().empty()
1821 && !GTy.isForwardDecl()) {
1822 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1823 assert(Entry && "Missing global type!");
1824 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1829 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1832 // Check for pre-existence.
1833 if (ModuleCU->getDIE(N))
1836 if (!SP.isDefinition())
1837 // This is a method declaration which will be handled while constructing
1841 DIE *SubprogramDie = createSubprogramDIE(SP);
1844 ModuleCU->insertDIE(N, SubprogramDie);
1846 // Add to context owner.
1847 addToContextOwner(SubprogramDie, SP.getContext());
1849 // Expose as global.
1850 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1855 /// beginModule - Emit all Dwarf sections that should come prior to the
1856 /// content. Create global DIEs and emit initial debug info sections.
1857 /// This is inovked by the target AsmPrinter.
1858 void DwarfDebug::beginModule(Module *M) {
1859 if (DisableDebugInfoPrinting)
1862 DebugInfoFinder DbgFinder;
1863 DbgFinder.processModule(*M);
1865 bool HasDebugInfo = false;
1867 // Scan all the compile-units to see if there are any marked as the main unit.
1868 // if not, we do not generate debug info.
1869 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1870 E = DbgFinder.compile_unit_end(); I != E; ++I) {
1871 if (DICompileUnit(*I).isMain()) {
1872 HasDebugInfo = true;
1877 if (!HasDebugInfo) return;
1879 // Tell MMI that we have debug info.
1880 MMI->setDebugInfoAvailability(true);
1882 // Emit initial sections.
1883 EmitSectionLabels();
1885 // Create all the compile unit DIEs.
1886 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1887 E = DbgFinder.compile_unit_end(); I != E; ++I)
1888 constructCompileUnit(*I);
1890 // Create DIEs for each subprogram.
1891 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1892 E = DbgFinder.subprogram_end(); I != E; ++I)
1893 constructSubprogramDIE(*I);
1895 // Create DIEs for each global variable.
1896 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1897 E = DbgFinder.global_variable_end(); I != E; ++I)
1898 constructGlobalVariableDIE(*I);
1900 // Prime section data.
1901 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1903 // Print out .file directives to specify files for .loc directives. These are
1904 // printed out early so that they precede any .loc directives.
1905 if (Asm->MAI->hasDotLocAndDotFile()) {
1906 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1907 // Remember source id starts at 1.
1908 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1909 // FIXME: don't use sys::path for this! This should not depend on the
1911 sys::Path FullPath(getSourceDirectoryName(Id.first));
1913 FullPath.appendComponent(getSourceFileName(Id.second));
1914 assert(AppendOk && "Could not append filename to directory!");
1916 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1921 /// endModule - Emit all Dwarf sections that should come after the content.
1923 void DwarfDebug::endModule() {
1924 if (!ModuleCU) return;
1926 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1927 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1928 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1930 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1933 for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
1934 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1935 DIE *SPDie = CI->first;
1936 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1938 DIE *NDie = ModuleCU->getDIE(N);
1939 if (!NDie) continue;
1940 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1943 // Standard sections final addresses.
1944 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1945 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1946 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1947 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1949 // End text sections.
1950 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1951 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1952 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1955 // Emit common frame information.
1956 emitCommonDebugFrame();
1958 // Emit function debug frame information
1959 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1960 E = DebugFrames.end(); I != E; ++I)
1961 emitFunctionDebugFrame(*I);
1963 // Compute DIE offsets and sizes.
1964 computeSizeAndOffsets();
1966 // Emit all the DIEs into a debug info section
1969 // Corresponding abbreviations into a abbrev section.
1970 emitAbbreviations();
1972 // Emit source line correspondence into a debug line section.
1975 // Emit info into a debug pubnames section.
1976 emitDebugPubNames();
1978 // Emit info into a debug pubtypes section.
1979 emitDebugPubTypes();
1981 // Emit info into a debug loc section.
1984 // Emit info into a debug aranges section.
1987 // Emit info into a debug ranges section.
1990 // Emit info into a debug macinfo section.
1993 // Emit inline info.
1994 emitDebugInlineInfo();
1996 // Emit info into a debug str section.
2000 ModuleCU = NULL; // Reset for the next Module, if any.
2003 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2004 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2006 DebugLoc ScopeLoc) {
2008 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
2010 return AbsDbgVariable;
2012 LLVMContext &Ctx = Var.getNode()->getContext();
2013 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2017 AbsDbgVariable = new DbgVariable(Var, FrameIdx,
2018 NULL /* No more-abstract variable*/);
2019 Scope->addVariable(AbsDbgVariable);
2020 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2021 return AbsDbgVariable;
2024 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2025 /// FIXME : Refactor findAbstractVariable.
2026 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2027 const MachineInstr *MI,
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, MI,
2040 NULL /* No more-abstract variable*/);
2041 Scope->addVariable(AbsDbgVariable);
2042 AbstractVariables[Var.getNode()] = AbsDbgVariable;
2043 DbgValueStartMap[MI] = AbsDbgVariable;
2044 return AbsDbgVariable;
2047 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2048 void DwarfDebug::collectVariableInfo() {
2049 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2051 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2052 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2053 VE = VMap.end(); VI != VE; ++VI) {
2054 MDNode *Var = VI->first;
2057 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2059 DbgScope *Scope = 0;
2060 if (MDNode *IA = VP.second.getInlinedAt(Ctx))
2061 Scope = ConcreteScopes.lookup(IA);
2063 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2065 // If variable scope is not found then skip this variable.
2069 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, VP.second);
2070 DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
2071 Scope->addVariable(RegVar);
2074 // Collect variable information from DBG_VALUE machine instructions;
2075 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2077 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2079 const MachineInstr *MInsn = II;
2080 if (!MInsn->isDebugValue())
2083 // FIXME : Lift this restriction.
2084 if (MInsn->getNumOperands() != 3)
2087 const_cast<MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1)
2089 if (DV.getTag() == dwarf::DW_TAG_arg_variable) {
2090 // FIXME Handle inlined subroutine arguments.
2091 DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL);
2092 CurrentFnDbgScope->addVariable(ArgVar);
2093 DbgValueStartMap[MInsn] = ArgVar;
2097 DebugLoc DL = MInsn->getDebugLoc();
2098 if (DL.isUnknown()) continue;
2099 DbgScope *Scope = 0;
2100 if (MDNode *IA = DL.getInlinedAt(Ctx))
2101 Scope = ConcreteScopes.lookup(IA);
2103 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2105 // If variable scope is not found then skip this variable.
2109 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL);
2110 DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable);
2111 DbgValueStartMap[MInsn] = RegVar;
2112 Scope->addVariable(RegVar);
2117 /// beginScope - Process beginning of a scope.
2118 void DwarfDebug::beginScope(const MachineInstr *MI) {
2120 DebugLoc DL = MI->getDebugLoc();
2124 MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2126 // FIXME: Should only verify each scope once!
2127 if (!DIScope(Scope).Verify())
2130 // DBG_VALUE instruction establishes new value.
2131 if (MI->isDebugValue()) {
2132 DenseMap<const MachineInstr *, DbgVariable *>::iterator DI
2133 = DbgValueStartMap.find(MI);
2134 if (DI != DbgValueStartMap.end()) {
2135 MCSymbol *Label = NULL;
2136 if (DL == PrevInstLoc)
2139 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2143 DI->second->setDbgValueLabel(Label);
2148 // Emit a label to indicate location change. This is used for line
2149 // table even if this instruction does not start a new scope.
2150 MCSymbol *Label = NULL;
2151 if (DL == PrevInstLoc)
2154 Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2159 // If this instruction begins a scope then note down corresponding label.
2160 if (InsnsBeginScopeSet.count(MI) != 0)
2161 InsnBeforeLabelMap[MI] = Label;
2164 /// endScope - Process end of a scope.
2165 void DwarfDebug::endScope(const MachineInstr *MI) {
2166 if (InsnsEndScopeSet.count(MI) != 0) {
2167 // Emit a label if this instruction ends a scope.
2168 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2169 Asm->OutStreamer.EmitLabel(Label);
2170 InsnAfterLabelMap[MI] = Label;
2174 /// getOrCreateDbgScope - Create DbgScope for the scope.
2175 DbgScope *DwarfDebug::getOrCreateDbgScope(MDNode *Scope, MDNode *InlinedAt) {
2177 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2180 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2181 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2182 if (DIDescriptor(Scope).isLexicalBlock()) {
2184 getOrCreateDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2185 WScope->setParent(Parent);
2186 Parent->addScope(WScope);
2189 if (!WScope->getParent()) {
2190 StringRef SPName = DISubprogram(Scope).getLinkageName();
2191 if (SPName == Asm->MF->getFunction()->getName())
2192 CurrentFnDbgScope = WScope;
2198 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2202 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2203 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2204 DILocation DL(InlinedAt);
2206 getOrCreateDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2207 WScope->setParent(Parent);
2208 Parent->addScope(WScope);
2210 ConcreteScopes[InlinedAt] = WScope;
2211 getOrCreateAbstractScope(Scope);
2216 /// hasValidLocation - Return true if debug location entry attached with
2217 /// machine instruction encodes valid location info.
2218 static bool hasValidLocation(LLVMContext &Ctx,
2219 const MachineInstr *MInsn,
2220 MDNode *&Scope, MDNode *&InlinedAt) {
2221 if (MInsn->isDebugValue())
2223 DebugLoc DL = MInsn->getDebugLoc();
2224 if (DL.isUnknown()) return false;
2226 MDNode *S = DL.getScope(Ctx);
2228 // There is no need to create another DIE for compile unit. For all
2229 // other scopes, create one DbgScope now. This will be translated
2230 // into a scope DIE at the end.
2231 if (DIScope(S).isCompileUnit()) return false;
2234 InlinedAt = DL.getInlinedAt(Ctx);
2238 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2240 static void calculateDominanceGraph(DbgScope *Scope) {
2241 assert (Scope && "Unable to calculate scop edominance graph!");
2242 SmallVector<DbgScope *, 4> WorkStack;
2243 WorkStack.push_back(Scope);
2244 unsigned Counter = 0;
2245 while (!WorkStack.empty()) {
2246 DbgScope *WS = WorkStack.back();
2247 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2248 bool visitedChildren = false;
2249 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2250 SE = Children.end(); SI != SE; ++SI) {
2251 DbgScope *ChildScope = *SI;
2252 if (!ChildScope->getDFSOut()) {
2253 WorkStack.push_back(ChildScope);
2254 visitedChildren = true;
2255 ChildScope->setDFSIn(++Counter);
2259 if (!visitedChildren) {
2260 WorkStack.pop_back();
2261 WS->setDFSOut(++Counter);
2266 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2268 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2269 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2272 unsigned PrevDFSIn = 0;
2273 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2275 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2277 const MachineInstr *MInsn = II;
2278 MDNode *Scope = NULL;
2279 MDNode *InlinedAt = NULL;
2281 // Check if instruction has valid location information.
2282 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2286 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2287 MI2ScopeMap.find(MInsn);
2288 if (DI != MI2ScopeMap.end()) {
2289 DbgScope *S = DI->second;
2290 dbgs() << S->getDFSIn();
2291 PrevDFSIn = S->getDFSIn();
2293 dbgs() << PrevDFSIn;
2295 dbgs() << " [ x" << PrevDFSIn;
2303 /// extractScopeInformation - Scan machine instructions in this function
2304 /// and collect DbgScopes. Return true, if at least one scope was found.
2305 bool DwarfDebug::extractScopeInformation() {
2306 // If scope information was extracted using .dbg intrinsics then there is not
2307 // any need to extract these information by scanning each instruction.
2308 if (!DbgScopeMap.empty())
2311 // Scan each instruction and create scopes. First build working set of scopes.
2312 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2313 SmallVector<DbgRange, 4> MIRanges;
2314 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2315 MDNode *PrevScope = NULL;
2316 MDNode *PrevInlinedAt = NULL;
2317 const MachineInstr *RangeBeginMI = NULL;
2318 const MachineInstr *PrevMI = NULL;
2319 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2321 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2323 const MachineInstr *MInsn = II;
2324 MDNode *Scope = NULL;
2325 MDNode *InlinedAt = NULL;
2327 // Check if instruction has valid location information.
2328 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2333 // If scope has not changed then skip this instruction.
2334 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2340 // If we have alread seen a beginning of a instruction range and
2341 // current instruction scope does not match scope of first instruction
2342 // in this range then create a new instruction range.
2343 DbgRange R(RangeBeginMI, PrevMI);
2344 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2345 MIRanges.push_back(R);
2348 // This is a beginning of a new instruction range.
2349 RangeBeginMI = MInsn;
2351 // Reset previous markers.
2354 PrevInlinedAt = InlinedAt;
2358 // Create last instruction range.
2359 if (RangeBeginMI && PrevMI && PrevScope) {
2360 DbgRange R(RangeBeginMI, PrevMI);
2361 MIRanges.push_back(R);
2362 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2365 if (!CurrentFnDbgScope)
2368 calculateDominanceGraph(CurrentFnDbgScope);
2370 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2372 // Find ranges of instructions covered by each DbgScope;
2373 DbgScope *PrevDbgScope = NULL;
2374 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2375 RE = MIRanges.end(); RI != RE; ++RI) {
2376 const DbgRange &R = *RI;
2377 DbgScope *S = MI2ScopeMap.lookup(R.first);
2378 assert (S && "Lost DbgScope for a machine instruction!");
2379 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2380 PrevDbgScope->closeInsnRange(S);
2381 S->openInsnRange(R.first);
2382 S->extendInsnRange(R.second);
2387 PrevDbgScope->closeInsnRange();
2389 identifyScopeMarkers();
2391 return !DbgScopeMap.empty();
2394 /// identifyScopeMarkers() -
2395 /// Each DbgScope has first instruction and last instruction to mark beginning
2396 /// and end of a scope respectively. Create an inverse map that list scopes
2397 /// starts (and ends) with an instruction. One instruction may start (or end)
2398 /// multiple scopes. Ignore scopes that are not reachable.
2399 void DwarfDebug::identifyScopeMarkers() {
2400 SmallVector<DbgScope *, 4> WorkList;
2401 WorkList.push_back(CurrentFnDbgScope);
2402 while (!WorkList.empty()) {
2403 DbgScope *S = WorkList.pop_back_val();
2405 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2406 if (!Children.empty())
2407 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2408 SE = Children.end(); SI != SE; ++SI)
2409 WorkList.push_back(*SI);
2411 if (S->isAbstractScope())
2414 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2417 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2418 RE = Ranges.end(); RI != RE; ++RI) {
2419 assert(RI->first && "DbgRange does not have first instruction!");
2420 assert(RI->second && "DbgRange does not have second instruction!");
2421 InsnsBeginScopeSet.insert(RI->first);
2422 InsnsEndScopeSet.insert(RI->second);
2427 /// FindFirstDebugLoc - Find the first debug location in the function. This
2428 /// is intended to be an approximation for the source position of the
2429 /// beginning of the function.
2430 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2431 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2433 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2434 MBBI != MBBE; ++MBBI) {
2435 DebugLoc DL = MBBI->getDebugLoc();
2436 if (!DL.isUnknown())
2442 /// beginFunction - Gather pre-function debug information. Assumes being
2443 /// emitted immediately after the function entry point.
2444 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2445 if (!MMI->hasDebugInfo()) return;
2446 if (!extractScopeInformation()) return;
2448 collectVariableInfo();
2450 // Assumes in correct section after the entry point.
2451 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_begin",
2452 Asm->getFunctionNumber()));
2454 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2456 DebugLoc FDL = FindFirstDebugLoc(MF);
2457 if (FDL.isUnknown()) return;
2459 MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2461 DISubprogram SP = getDISubprogram(Scope);
2464 Line = SP.getLineNumber();
2467 Line = FDL.getLine();
2471 recordSourceLine(Line, Col, Scope);
2474 /// endFunction - Gather and emit post-function debug information.
2476 void DwarfDebug::endFunction(const MachineFunction *MF) {
2477 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2479 if (CurrentFnDbgScope) {
2480 // Define end label for subprogram.
2481 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end",
2482 Asm->getFunctionNumber()));
2484 // Get function line info.
2485 if (!Lines.empty()) {
2486 // Get section line info.
2487 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2488 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2489 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2490 // Append the function info to section info.
2491 SectionLineInfos.insert(SectionLineInfos.end(),
2492 Lines.begin(), Lines.end());
2495 // Construct abstract scopes.
2496 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2497 AE = AbstractScopesList.end(); AI != AE; ++AI)
2498 constructScopeDIE(*AI);
2500 constructScopeDIE(CurrentFnDbgScope);
2502 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2503 MMI->getFrameMoves()));
2507 CurrentFnDbgScope = NULL;
2508 DeleteContainerSeconds(DbgScopeMap);
2509 InsnsBeginScopeSet.clear();
2510 InsnsEndScopeSet.clear();
2511 DbgValueStartMap.clear();
2512 ConcreteScopes.clear();
2513 DeleteContainerSeconds(AbstractScopes);
2514 AbstractScopesList.clear();
2515 AbstractVariables.clear();
2516 InsnBeforeLabelMap.clear();
2517 InsnAfterLabelMap.clear();
2522 /// recordSourceLine - Register a source line with debug info. Returns the
2523 /// unique label that was emitted and which provides correspondence to
2524 /// the source line list.
2525 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) {
2529 DIDescriptor Scope(S);
2530 if (Scope.isCompileUnit()) {
2531 DICompileUnit CU(S);
2532 Dir = CU.getDirectory();
2533 Fn = CU.getFilename();
2534 } else if (Scope.isSubprogram()) {
2536 Dir = SP.getDirectory();
2537 Fn = SP.getFilename();
2538 } else if (Scope.isLexicalBlock()) {
2539 DILexicalBlock DB(S);
2540 Dir = DB.getDirectory();
2541 Fn = DB.getFilename();
2543 assert(0 && "Unexpected scope info");
2545 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2546 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2547 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2549 Asm->OutStreamer.EmitLabel(Label);
2553 //===----------------------------------------------------------------------===//
2555 //===----------------------------------------------------------------------===//
2557 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2560 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2561 // Get the children.
2562 const std::vector<DIE *> &Children = Die->getChildren();
2564 // If not last sibling and has children then add sibling offset attribute.
2565 if (!Last && !Children.empty())
2566 Die->addSiblingOffset(DIEValueAllocator);
2568 // Record the abbreviation.
2569 assignAbbrevNumber(Die->getAbbrev());
2571 // Get the abbreviation for this DIE.
2572 unsigned AbbrevNumber = Die->getAbbrevNumber();
2573 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2576 Die->setOffset(Offset);
2578 // Start the size with the size of abbreviation code.
2579 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2581 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2582 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2584 // Size the DIE attribute values.
2585 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2586 // Size attribute value.
2587 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2589 // Size the DIE children if any.
2590 if (!Children.empty()) {
2591 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2592 "Children flag not set");
2594 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2595 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2597 // End of children marker.
2598 Offset += sizeof(int8_t);
2601 Die->setSize(Offset - Die->getOffset());
2605 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2607 void DwarfDebug::computeSizeAndOffsets() {
2608 // Compute size of compile unit header.
2609 static unsigned Offset =
2610 sizeof(int32_t) + // Length of Compilation Unit Info
2611 sizeof(int16_t) + // DWARF version number
2612 sizeof(int32_t) + // Offset Into Abbrev. Section
2613 sizeof(int8_t); // Pointer Size (in bytes)
2615 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2618 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2619 /// temporary label to it if SymbolStem is specified.
2620 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2621 const char *SymbolStem = 0) {
2622 Asm->OutStreamer.SwitchSection(Section);
2623 if (!SymbolStem) return 0;
2625 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2626 Asm->OutStreamer.EmitLabel(TmpSym);
2630 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2631 /// the start of each one.
2632 void DwarfDebug::EmitSectionLabels() {
2633 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2635 // Dwarf sections base addresses.
2636 if (Asm->MAI->doesDwarfRequireFrameSection()) {
2637 DwarfFrameSectionSym =
2638 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2641 DwarfInfoSectionSym =
2642 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2643 DwarfAbbrevSectionSym =
2644 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2645 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2647 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2648 EmitSectionSym(Asm, MacroInfo);
2650 EmitSectionSym(Asm, TLOF.getDwarfLineSection());
2651 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2652 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2653 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2654 DwarfStrSectionSym =
2655 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2656 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2659 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2660 EmitSectionSym(Asm, TLOF.getDataSection());
2663 /// emitDIE - Recusively Emits a debug information entry.
2665 void DwarfDebug::emitDIE(DIE *Die) {
2666 // Get the abbreviation for this DIE.
2667 unsigned AbbrevNumber = Die->getAbbrevNumber();
2668 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2670 // Emit the code (index) for the abbreviation.
2671 if (Asm->isVerbose())
2672 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2673 Twine::utohexstr(Die->getOffset()) + ":0x" +
2674 Twine::utohexstr(Die->getSize()) + " " +
2675 dwarf::TagString(Abbrev->getTag()));
2676 Asm->EmitULEB128(AbbrevNumber);
2678 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2679 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2681 // Emit the DIE attribute values.
2682 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2683 unsigned Attr = AbbrevData[i].getAttribute();
2684 unsigned Form = AbbrevData[i].getForm();
2685 assert(Form && "Too many attributes for DIE (check abbreviation)");
2687 if (Asm->isVerbose())
2688 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2691 case dwarf::DW_AT_sibling:
2692 Asm->EmitInt32(Die->getSiblingOffset());
2694 case dwarf::DW_AT_abstract_origin: {
2695 DIEEntry *E = cast<DIEEntry>(Values[i]);
2696 DIE *Origin = E->getEntry();
2697 unsigned Addr = Origin->getOffset();
2698 Asm->EmitInt32(Addr);
2701 case dwarf::DW_AT_ranges: {
2702 // DW_AT_range Value encodes offset in debug_range section.
2703 DIEInteger *V = cast<DIEInteger>(Values[i]);
2704 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2706 DwarfDebugRangeSectionSym,
2711 // Emit an attribute using the defined form.
2712 Values[i]->EmitValue(Asm, Form);
2717 // Emit the DIE children if any.
2718 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2719 const std::vector<DIE *> &Children = Die->getChildren();
2721 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2722 emitDIE(Children[j]);
2724 if (Asm->isVerbose())
2725 Asm->OutStreamer.AddComment("End Of Children Mark");
2730 /// emitDebugInfo - Emit the debug info section.
2732 void DwarfDebug::emitDebugInfo() {
2733 // Start debug info section.
2734 Asm->OutStreamer.SwitchSection(
2735 Asm->getObjFileLowering().getDwarfInfoSection());
2736 DIE *Die = ModuleCU->getCUDie();
2738 // Emit the compile units header.
2739 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2740 ModuleCU->getID()));
2742 // Emit size of content not including length itself
2743 unsigned ContentSize = Die->getSize() +
2744 sizeof(int16_t) + // DWARF version number
2745 sizeof(int32_t) + // Offset Into Abbrev. Section
2746 sizeof(int8_t) + // Pointer Size (in bytes)
2747 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2749 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2750 Asm->EmitInt32(ContentSize);
2751 Asm->OutStreamer.AddComment("DWARF version number");
2752 Asm->EmitInt16(dwarf::DWARF_VERSION);
2753 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2754 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2755 DwarfAbbrevSectionSym);
2756 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2757 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2760 // FIXME - extra padding for gdb bug.
2761 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2766 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", ModuleCU->getID()));
2769 /// emitAbbreviations - Emit the abbreviation section.
2771 void DwarfDebug::emitAbbreviations() const {
2772 // Check to see if it is worth the effort.
2773 if (!Abbreviations.empty()) {
2774 // Start the debug abbrev section.
2775 Asm->OutStreamer.SwitchSection(
2776 Asm->getObjFileLowering().getDwarfAbbrevSection());
2778 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2780 // For each abbrevation.
2781 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2782 // Get abbreviation data
2783 const DIEAbbrev *Abbrev = Abbreviations[i];
2785 // Emit the abbrevations code (base 1 index.)
2786 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2788 // Emit the abbreviations data.
2792 // Mark end of abbreviations.
2793 Asm->EmitULEB128(0, "EOM(3)");
2795 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2799 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2800 /// the line matrix.
2802 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2803 // Define last address of section.
2804 Asm->OutStreamer.AddComment("Extended Op");
2807 Asm->OutStreamer.AddComment("Op size");
2808 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2809 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2810 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2812 Asm->OutStreamer.AddComment("Section end label");
2814 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2815 Asm->getTargetData().getPointerSize(),
2818 // Mark end of matrix.
2819 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2825 /// emitDebugLines - Emit source line information.
2827 void DwarfDebug::emitDebugLines() {
2828 // If the target is using .loc/.file, the assembler will be emitting the
2829 // .debug_line table automatically.
2830 if (Asm->MAI->hasDotLocAndDotFile())
2833 // Minimum line delta, thus ranging from -10..(255-10).
2834 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2835 // Maximum line delta, thus ranging from -10..(255-10).
2836 const int MaxLineDelta = 255 + MinLineDelta;
2838 // Start the dwarf line section.
2839 Asm->OutStreamer.SwitchSection(
2840 Asm->getObjFileLowering().getDwarfLineSection());
2842 // Construct the section header.
2843 Asm->OutStreamer.AddComment("Length of Source Line Info");
2844 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
2845 Asm->GetTempSymbol("line_begin"), 4);
2846 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
2848 Asm->OutStreamer.AddComment("DWARF version number");
2849 Asm->EmitInt16(dwarf::DWARF_VERSION);
2851 Asm->OutStreamer.AddComment("Prolog Length");
2852 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
2853 Asm->GetTempSymbol("line_prolog_begin"), 4);
2854 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
2856 Asm->OutStreamer.AddComment("Minimum Instruction Length");
2858 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2860 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2861 Asm->EmitInt8(MinLineDelta);
2862 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2863 Asm->EmitInt8(MaxLineDelta);
2864 Asm->OutStreamer.AddComment("Special Opcode Base");
2865 Asm->EmitInt8(-MinLineDelta);
2867 // Line number standard opcode encodings argument count
2868 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2870 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2872 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2874 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2876 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2878 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2880 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2882 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2884 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2887 // Emit directories.
2888 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2889 const std::string &Dir = getSourceDirectoryName(DI);
2890 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
2891 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2894 Asm->OutStreamer.AddComment("End of directories");
2898 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2899 // Remember source id starts at 1.
2900 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2901 const std::string &FN = getSourceFileName(Id.second);
2902 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
2903 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2905 Asm->EmitULEB128(Id.first, "Directory #");
2906 Asm->EmitULEB128(0, "Mod date");
2907 Asm->EmitULEB128(0, "File size");
2910 Asm->OutStreamer.AddComment("End of files");
2913 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
2915 // A sequence for each text section.
2916 unsigned SecSrcLinesSize = SectionSourceLines.size();
2918 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2919 // Isolate current sections line info.
2920 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2922 // Dwarf assumes we start with first line of first source file.
2923 unsigned Source = 1;
2926 // Construct rows of the address, source, line, column matrix.
2927 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2928 const SrcLineInfo &LineInfo = LineInfos[i];
2929 MCSymbol *Label = LineInfo.getLabel();
2930 if (!Label->isDefined()) continue; // Not emitted, in dead code.
2932 if (LineInfo.getLine() == 0) continue;
2934 if (Asm->isVerbose()) {
2935 std::pair<unsigned, unsigned> SrcID =
2936 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2937 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
2939 Twine(getSourceFileName(SrcID.second)) +
2940 ":" + Twine(LineInfo.getLine()));
2943 // Define the line address.
2944 Asm->OutStreamer.AddComment("Extended Op");
2946 Asm->OutStreamer.AddComment("Op size");
2947 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2949 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2950 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2952 Asm->OutStreamer.AddComment("Location label");
2953 Asm->OutStreamer.EmitSymbolValue(Label,
2954 Asm->getTargetData().getPointerSize(),
2957 // If change of source, then switch to the new source.
2958 if (Source != LineInfo.getSourceID()) {
2959 Source = LineInfo.getSourceID();
2960 Asm->OutStreamer.AddComment("DW_LNS_set_file");
2961 Asm->EmitInt8(dwarf::DW_LNS_set_file);
2962 Asm->EmitULEB128(Source, "New Source");
2965 // If change of line.
2966 if (Line != LineInfo.getLine()) {
2967 // Determine offset.
2968 int Offset = LineInfo.getLine() - Line;
2969 int Delta = Offset - MinLineDelta;
2972 Line = LineInfo.getLine();
2974 // If delta is small enough and in range...
2975 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2976 // ... then use fast opcode.
2977 Asm->OutStreamer.AddComment("Line Delta");
2978 Asm->EmitInt8(Delta - MinLineDelta);
2980 // ... otherwise use long hand.
2981 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
2982 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2983 Asm->EmitSLEB128(Offset, "Line Offset");
2984 Asm->OutStreamer.AddComment("DW_LNS_copy");
2985 Asm->EmitInt8(dwarf::DW_LNS_copy);
2988 // Copy the previous row (different address or source)
2989 Asm->OutStreamer.AddComment("DW_LNS_copy");
2990 Asm->EmitInt8(dwarf::DW_LNS_copy);
2994 emitEndOfLineMatrix(j + 1);
2997 if (SecSrcLinesSize == 0)
2998 // Because we're emitting a debug_line section, we still need a line
2999 // table. The linker and friends expect it to exist. If there's nothing to
3000 // put into it, emit an empty table.
3001 emitEndOfLineMatrix(1);
3003 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3006 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3008 void DwarfDebug::emitCommonDebugFrame() {
3009 if (!Asm->MAI->doesDwarfRequireFrameSection())
3012 int stackGrowth = Asm->getTargetData().getPointerSize();
3013 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3014 TargetFrameInfo::StackGrowsDown)
3017 // Start the dwarf frame section.
3018 Asm->OutStreamer.SwitchSection(
3019 Asm->getObjFileLowering().getDwarfFrameSection());
3021 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3022 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3023 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3024 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3026 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3027 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3028 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3029 Asm->OutStreamer.AddComment("CIE Version");
3030 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3031 Asm->OutStreamer.AddComment("CIE Augmentation");
3032 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3033 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3034 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3035 Asm->OutStreamer.AddComment("CIE RA Column");
3036 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3037 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3039 std::vector<MachineMove> Moves;
3040 RI->getInitialFrameState(Moves);
3042 Asm->EmitFrameMoves(Moves, 0, false);
3044 Asm->EmitAlignment(2, 0, 0, false);
3045 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3048 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3051 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3052 if (!Asm->MAI->doesDwarfRequireFrameSection())
3055 // Start the dwarf frame section.
3056 Asm->OutStreamer.SwitchSection(
3057 Asm->getObjFileLowering().getDwarfFrameSection());
3059 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3060 MCSymbol *DebugFrameBegin =
3061 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3062 MCSymbol *DebugFrameEnd =
3063 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3064 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3066 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3068 Asm->OutStreamer.AddComment("FDE CIE offset");
3069 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3070 DwarfFrameSectionSym);
3072 Asm->OutStreamer.AddComment("FDE initial location");
3073 MCSymbol *FuncBeginSym =
3074 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3075 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3076 Asm->getTargetData().getPointerSize(),
3080 Asm->OutStreamer.AddComment("FDE address range");
3081 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3082 FuncBeginSym, Asm->getTargetData().getPointerSize());
3084 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3086 Asm->EmitAlignment(2, 0, 0, false);
3087 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3090 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3092 void DwarfDebug::emitDebugPubNames() {
3093 // Start the dwarf pubnames section.
3094 Asm->OutStreamer.SwitchSection(
3095 Asm->getObjFileLowering().getDwarfPubNamesSection());
3097 Asm->OutStreamer.AddComment("Length of Public Names Info");
3098 Asm->EmitLabelDifference(
3099 Asm->GetTempSymbol("pubnames_end", ModuleCU->getID()),
3100 Asm->GetTempSymbol("pubnames_begin", ModuleCU->getID()), 4);
3102 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3103 ModuleCU->getID()));
3105 Asm->OutStreamer.AddComment("DWARF Version");
3106 Asm->EmitInt16(dwarf::DWARF_VERSION);
3108 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3109 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3110 DwarfInfoSectionSym);
3112 Asm->OutStreamer.AddComment("Compilation Unit Length");
3113 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3114 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3117 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
3118 for (StringMap<DIE*>::const_iterator
3119 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3120 const char *Name = GI->getKeyData();
3121 DIE *Entity = GI->second;
3123 Asm->OutStreamer.AddComment("DIE offset");
3124 Asm->EmitInt32(Entity->getOffset());
3126 if (Asm->isVerbose())
3127 Asm->OutStreamer.AddComment("External Name");
3128 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3131 Asm->OutStreamer.AddComment("End Mark");
3133 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3134 ModuleCU->getID()));
3137 void DwarfDebug::emitDebugPubTypes() {
3138 // Start the dwarf pubnames section.
3139 Asm->OutStreamer.SwitchSection(
3140 Asm->getObjFileLowering().getDwarfPubTypesSection());
3141 Asm->OutStreamer.AddComment("Length of Public Types Info");
3142 Asm->EmitLabelDifference(
3143 Asm->GetTempSymbol("pubtypes_end", ModuleCU->getID()),
3144 Asm->GetTempSymbol("pubtypes_begin", ModuleCU->getID()), 4);
3146 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3147 ModuleCU->getID()));
3149 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3150 Asm->EmitInt16(dwarf::DWARF_VERSION);
3152 Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
3153 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3154 DwarfInfoSectionSym);
3156 Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
3157 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", ModuleCU->getID()),
3158 Asm->GetTempSymbol("info_begin", ModuleCU->getID()),
3161 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
3162 for (StringMap<DIE*>::const_iterator
3163 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3164 const char *Name = GI->getKeyData();
3165 DIE * Entity = GI->second;
3167 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3168 Asm->EmitInt32(Entity->getOffset());
3170 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3171 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3174 Asm->OutStreamer.AddComment("End Mark");
3176 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3177 ModuleCU->getID()));
3180 /// emitDebugStr - Emit visible names into a debug str section.
3182 void DwarfDebug::emitDebugStr() {
3183 // Check to see if it is worth the effort.
3184 if (StringPool.empty()) return;
3186 // Start the dwarf str section.
3187 Asm->OutStreamer.SwitchSection(
3188 Asm->getObjFileLowering().getDwarfStrSection());
3190 // Get all of the string pool entries and put them in an array by their ID so
3191 // we can sort them.
3192 SmallVector<std::pair<unsigned,
3193 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3195 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3196 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3197 Entries.push_back(std::make_pair(I->second.second, &*I));
3199 array_pod_sort(Entries.begin(), Entries.end());
3201 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3202 // Emit a label for reference from debug information entries.
3203 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3205 // Emit the string itself.
3206 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3210 /// emitDebugLoc - Emit visible names into a debug loc section.
3212 void DwarfDebug::emitDebugLoc() {
3213 // Start the dwarf loc section.
3214 Asm->OutStreamer.SwitchSection(
3215 Asm->getObjFileLowering().getDwarfLocSection());
3218 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3220 void DwarfDebug::EmitDebugARanges() {
3221 // Start the dwarf aranges section.
3222 Asm->OutStreamer.SwitchSection(
3223 Asm->getObjFileLowering().getDwarfARangesSection());
3226 /// emitDebugRanges - Emit visible names into a debug ranges section.
3228 void DwarfDebug::emitDebugRanges() {
3229 // Start the dwarf ranges section.
3230 Asm->OutStreamer.SwitchSection(
3231 Asm->getObjFileLowering().getDwarfRangesSection());
3232 for (SmallVector<const MCSymbol *, 8>::const_iterator I = DebugRangeSymbols.begin(),
3233 E = DebugRangeSymbols.end(); I != E; ++I) {
3235 Asm->EmitLabelDifference(*I, TextSectionSym,
3236 Asm->getTargetData().getPointerSize());
3238 Asm->OutStreamer.EmitIntValue(0, Asm->getTargetData().getPointerSize(),
3243 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3245 void DwarfDebug::emitDebugMacInfo() {
3246 if (const MCSection *LineInfo =
3247 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3248 // Start the dwarf macinfo section.
3249 Asm->OutStreamer.SwitchSection(LineInfo);
3253 /// emitDebugInlineInfo - Emit inline info using following format.
3255 /// 1. length of section
3256 /// 2. Dwarf version number
3257 /// 3. address size.
3259 /// Entries (one "entry" for each function that was inlined):
3261 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3262 /// otherwise offset into __debug_str for regular function name.
3263 /// 2. offset into __debug_str section for regular function name.
3264 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3265 /// instances for the function.
3267 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3268 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3269 /// __debug_info section, and the low_pc is the starting address for the
3270 /// inlining instance.
3271 void DwarfDebug::emitDebugInlineInfo() {
3272 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3278 Asm->OutStreamer.SwitchSection(
3279 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3281 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3282 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3283 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3285 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3287 Asm->OutStreamer.AddComment("Dwarf Version");
3288 Asm->EmitInt16(dwarf::DWARF_VERSION);
3289 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3290 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3292 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3293 E = InlinedSPNodes.end(); I != E; ++I) {
3296 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3297 = InlineInfo.find(Node);
3298 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3299 DISubprogram SP(Node);
3300 StringRef LName = SP.getLinkageName();
3301 StringRef Name = SP.getName();
3303 Asm->OutStreamer.AddComment("MIPS linkage name");
3304 if (LName.empty()) {
3305 Asm->OutStreamer.EmitBytes(Name, 0);
3306 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3308 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3309 DwarfStrSectionSym);
3311 Asm->OutStreamer.AddComment("Function name");
3312 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3313 Asm->EmitULEB128(Labels.size(), "Inline count");
3315 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3316 LE = Labels.end(); LI != LE; ++LI) {
3317 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3318 Asm->EmitInt32(LI->second->getOffset());
3320 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3321 Asm->OutStreamer.EmitSymbolValue(LI->first,
3322 Asm->getTargetData().getPointerSize(),0);
3326 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));