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",
49 cl::desc("Disable debug info printing"));
51 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
52 cl::desc("Make an absense of debug location information explicit."),
56 const char *DWARFGroupName = "DWARF Emission";
57 const char *DbgTimerName = "DWARF Debug Writer";
58 } // end anonymous namespace
60 //===----------------------------------------------------------------------===//
62 /// Configuration values for initial hash set sizes (log2).
64 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
68 //===----------------------------------------------------------------------===//
69 /// CompileUnit - This dwarf writer support class manages information associate
70 /// with a source file.
72 /// ID - File identifier for source.
76 /// Die - Compile unit debug information entry.
78 const OwningPtr<DIE> CUDie;
80 /// IndexTyDie - An anonymous type for index type. Owned by CUDie.
83 /// MDNodeToDieMap - Tracks the mapping of unit level debug informaton
84 /// variables to debug information entries.
85 DenseMap<const MDNode *, DIE *> MDNodeToDieMap;
87 /// MDNodeToDIEEntryMap - Tracks the mapping of unit level debug informaton
88 /// descriptors to debug information entries using a DIEEntry proxy.
89 DenseMap<const MDNode *, DIEEntry *> MDNodeToDIEEntryMap;
91 /// Globals - A map of globally visible named entities for this unit.
93 StringMap<DIE*> Globals;
95 /// GlobalTypes - A map of globally visible types for this unit.
97 StringMap<DIE*> GlobalTypes;
100 CompileUnit(unsigned I, DIE *D)
101 : ID(I), CUDie(D), IndexTyDie(0) {}
104 unsigned getID() const { return ID; }
105 DIE* getCUDie() const { return CUDie.get(); }
106 const StringMap<DIE*> &getGlobals() const { return Globals; }
107 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
109 /// hasContent - Return true if this compile unit has something to write out.
111 bool hasContent() const { return !CUDie->getChildren().empty(); }
113 /// addGlobal - Add a new global entity to the compile unit.
115 void addGlobal(StringRef Name, DIE *Die) { Globals[Name] = Die; }
117 /// addGlobalType - Add a new global type to the compile unit.
119 void addGlobalType(StringRef Name, DIE *Die) {
120 GlobalTypes[Name] = Die;
123 /// getDIE - Returns the debug information entry map slot for the
124 /// specified debug variable.
125 DIE *getDIE(const MDNode *N) { return MDNodeToDieMap.lookup(N); }
127 /// insertDIE - Insert DIE into the map.
128 void insertDIE(const MDNode *N, DIE *D) {
129 MDNodeToDieMap.insert(std::make_pair(N, D));
132 /// getDIEEntry - Returns the debug information entry for the speciefied
134 DIEEntry *getDIEEntry(const MDNode *N) {
135 DenseMap<const MDNode *, DIEEntry *>::iterator I =
136 MDNodeToDIEEntryMap.find(N);
137 if (I == MDNodeToDIEEntryMap.end())
142 /// insertDIEEntry - Insert debug information entry into the map.
143 void insertDIEEntry(const MDNode *N, DIEEntry *E) {
144 MDNodeToDIEEntryMap.insert(std::make_pair(N, E));
147 /// addDie - Adds or interns the DIE to the compile unit.
149 void addDie(DIE *Buffer) {
150 this->CUDie->addChild(Buffer);
153 // getIndexTyDie - Get an anonymous type for index type.
154 DIE *getIndexTyDie() {
158 // setIndexTyDie - Set D as anonymous type for index which can be reused
160 void setIndexTyDie(DIE *D) {
166 //===----------------------------------------------------------------------===//
167 /// DbgVariable - This class is used to track local variable information.
170 DIVariable Var; // Variable Descriptor.
171 DIE *TheDIE; // Variable DIE.
172 unsigned DotDebugLocOffset; // Offset in DotDebugLocEntries.
174 // AbsVar may be NULL.
175 DbgVariable(DIVariable V) : Var(V), TheDIE(0), DotDebugLocOffset(~0U) {}
178 DIVariable getVariable() const { return Var; }
179 void setDIE(DIE *D) { TheDIE = D; }
180 DIE *getDIE() const { return TheDIE; }
181 void setDotDebugLocOffset(unsigned O) { DotDebugLocOffset = O; }
182 unsigned getDotDebugLocOffset() const { return DotDebugLocOffset; }
183 StringRef getName() const { return Var.getName(); }
184 unsigned getTag() const { return Var.getTag(); }
185 bool variableHasComplexAddress() const {
186 assert(Var.Verify() && "Invalid complex DbgVariable!");
187 return Var.hasComplexAddress();
189 bool isBlockByrefVariable() const {
190 assert(Var.Verify() && "Invalid complex DbgVariable!");
191 return Var.isBlockByrefVariable();
193 unsigned getNumAddrElements() const {
194 assert(Var.Verify() && "Invalid complex DbgVariable!");
195 return Var.getNumAddrElements();
197 uint64_t getAddrElement(unsigned i) const {
198 return Var.getAddrElement(i);
200 DIType getType() const {
201 DIType Ty = Var.getType();
202 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
203 // addresses instead.
204 if (Var.isBlockByrefVariable()) {
205 /* Byref variables, in Blocks, are declared by the programmer as
206 "SomeType VarName;", but the compiler creates a
207 __Block_byref_x_VarName struct, and gives the variable VarName
208 either the struct, or a pointer to the struct, as its type. This
209 is necessary for various behind-the-scenes things the compiler
210 needs to do with by-reference variables in blocks.
212 However, as far as the original *programmer* is concerned, the
213 variable should still have type 'SomeType', as originally declared.
215 The following function dives into the __Block_byref_x_VarName
216 struct to find the original type of the variable. This will be
217 passed back to the code generating the type for the Debug
218 Information Entry for the variable 'VarName'. 'VarName' will then
219 have the original type 'SomeType' in its debug information.
221 The original type 'SomeType' will be the type of the field named
222 'VarName' inside the __Block_byref_x_VarName struct.
224 NOTE: In order for this to not completely fail on the debugger
225 side, the Debug Information Entry for the variable VarName needs to
226 have a DW_AT_location that tells the debugger how to unwind through
227 the pointers and __Block_byref_x_VarName struct to find the actual
228 value of the variable. The function addBlockByrefType does this. */
230 unsigned tag = Ty.getTag();
232 if (tag == dwarf::DW_TAG_pointer_type) {
233 DIDerivedType DTy = DIDerivedType(Ty);
234 subType = DTy.getTypeDerivedFrom();
237 DICompositeType blockStruct = DICompositeType(subType);
238 DIArray Elements = blockStruct.getTypeArray();
240 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
241 DIDescriptor Element = Elements.getElement(i);
242 DIDerivedType DT = DIDerivedType(Element);
243 if (getName() == DT.getName())
244 return (DT.getTypeDerivedFrom());
252 //===----------------------------------------------------------------------===//
253 /// DbgRange - This is used to track range of instructions with identical
254 /// debug info scope.
256 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
258 //===----------------------------------------------------------------------===//
259 /// DbgScope - This class is used to track scope information.
262 DbgScope *Parent; // Parent to this scope.
263 DIDescriptor Desc; // Debug info descriptor for scope.
264 // Location at which this scope is inlined.
265 AssertingVH<const MDNode> InlinedAtLocation;
266 bool AbstractScope; // Abstract Scope
267 const MachineInstr *LastInsn; // Last instruction of this scope.
268 const MachineInstr *FirstInsn; // First instruction of this scope.
269 unsigned DFSIn, DFSOut;
270 // Scopes defined in scope. Contents not owned.
271 SmallVector<DbgScope *, 4> Scopes;
272 // Variables declared in scope. Contents owned.
273 SmallVector<DbgVariable *, 8> Variables;
274 SmallVector<DbgRange, 4> Ranges;
275 // Private state for dump()
276 mutable unsigned IndentLevel;
278 DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
279 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
280 LastInsn(0), FirstInsn(0),
281 DFSIn(0), DFSOut(0), IndentLevel(0) {}
285 DbgScope *getParent() const { return Parent; }
286 void setParent(DbgScope *P) { Parent = P; }
287 DIDescriptor getDesc() const { return Desc; }
288 const MDNode *getInlinedAt() const { return InlinedAtLocation; }
289 const MDNode *getScopeNode() const { return Desc; }
290 const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
291 const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
292 const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
294 /// openInsnRange - This scope covers instruction range starting from MI.
295 void openInsnRange(const MachineInstr *MI) {
300 Parent->openInsnRange(MI);
303 /// extendInsnRange - Extend the current instruction range covered by
305 void extendInsnRange(const MachineInstr *MI) {
306 assert (FirstInsn && "MI Range is not open!");
309 Parent->extendInsnRange(MI);
312 /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
313 /// until now. This is used when a new scope is encountered while walking
314 /// machine instructions.
315 void closeInsnRange(DbgScope *NewScope = NULL) {
316 assert (LastInsn && "Last insn missing!");
317 Ranges.push_back(DbgRange(FirstInsn, LastInsn));
320 // If Parent dominates NewScope then do not close Parent's instruction
322 if (Parent && (!NewScope || !Parent->dominates(NewScope)))
323 Parent->closeInsnRange(NewScope);
326 void setAbstractScope() { AbstractScope = true; }
327 bool isAbstractScope() const { return AbstractScope; }
329 // Depth First Search support to walk and mainpluate DbgScope hierarchy.
330 unsigned getDFSOut() const { return DFSOut; }
331 void setDFSOut(unsigned O) { DFSOut = O; }
332 unsigned getDFSIn() const { return DFSIn; }
333 void setDFSIn(unsigned I) { DFSIn = I; }
334 bool dominates(const DbgScope *S) {
337 if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
342 /// addScope - Add a scope to the scope.
344 void addScope(DbgScope *S) { Scopes.push_back(S); }
346 /// addVariable - Add a variable to the scope.
348 void addVariable(DbgVariable *V) { Variables.push_back(V); }
355 } // end llvm namespace
358 void DbgScope::dump() const {
359 raw_ostream &err = dbgs();
360 err.indent(IndentLevel);
361 const MDNode *N = Desc;
364 err << "Abstract Scope\n";
368 err << "Children ...\n";
369 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
370 if (Scopes[i] != this)
377 DbgScope::~DbgScope() {
378 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
382 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
383 : Asm(A), MMI(Asm->MMI), FirstCU(0),
384 AbbreviationsSet(InitAbbreviationsSetSize),
385 CurrentFnDbgScope(0), PrevLabel(NULL) {
386 NextStringPoolNumber = 0;
388 DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
389 DwarfStrSectionSym = TextSectionSym = 0;
390 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
391 FunctionBeginSym = FunctionEndSym = 0;
392 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
394 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
398 DwarfDebug::~DwarfDebug() {
399 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
400 DIEBlocks[j]->~DIEBlock();
403 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
404 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
405 if (Entry.first) return Entry.first;
407 Entry.second = NextStringPoolNumber++;
408 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
412 /// assignAbbrevNumber - Define a unique number for the abbreviation.
414 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
415 // Profile the node so that we can make it unique.
419 // Check the set for priors.
420 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
422 // If it's newly added.
423 if (InSet == &Abbrev) {
424 // Add to abbreviation list.
425 Abbreviations.push_back(&Abbrev);
427 // Assign the vector position + 1 as its number.
428 Abbrev.setNumber(Abbreviations.size());
430 // Assign existing abbreviation number.
431 Abbrev.setNumber(InSet->getNumber());
435 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
436 /// information entry.
437 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
438 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
442 /// addUInt - Add an unsigned integer attribute data and value.
444 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
445 unsigned Form, uint64_t Integer) {
446 if (!Form) Form = DIEInteger::BestForm(false, Integer);
447 DIEValue *Value = Integer == 1 ?
448 DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
449 Die->addValue(Attribute, Form, Value);
452 /// addSInt - Add an signed integer attribute data and value.
454 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
455 unsigned Form, int64_t Integer) {
456 if (!Form) Form = DIEInteger::BestForm(true, Integer);
457 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
458 Die->addValue(Attribute, Form, Value);
461 /// addString - Add a string attribute data and value. DIEString only
462 /// keeps string reference.
463 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
465 DIEValue *Value = new (DIEValueAllocator) DIEString(String);
466 Die->addValue(Attribute, Form, Value);
469 /// addLabel - Add a Dwarf label attribute data and value.
471 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
472 const MCSymbol *Label) {
473 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
474 Die->addValue(Attribute, Form, Value);
477 /// addDelta - Add a label delta attribute data and value.
479 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
480 const MCSymbol *Hi, const MCSymbol *Lo) {
481 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
482 Die->addValue(Attribute, Form, Value);
485 /// addDIEEntry - Add a DIE attribute data and value.
487 void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
489 Die->addValue(Attribute, Form, createDIEEntry(Entry));
493 /// addBlock - Add block data.
495 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
497 Block->ComputeSize(Asm);
498 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
499 Die->addValue(Attribute, Block->BestForm(), Block);
502 /// addSourceLine - Add location information to specified debug information
504 void DwarfDebug::addSourceLine(DIE *Die, DIVariable V) {
509 unsigned Line = V.getLineNumber();
510 unsigned FileID = GetOrCreateSourceID(V.getContext().getDirectory(),
511 V.getContext().getFilename());
512 assert(FileID && "Invalid file id");
513 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
514 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
517 /// addSourceLine - Add location information to specified debug information
519 void DwarfDebug::addSourceLine(DIE *Die, DIGlobalVariable G) {
520 // Verify global variable.
524 unsigned Line = G.getLineNumber();
525 unsigned FileID = GetOrCreateSourceID(G.getContext().getDirectory(),
526 G.getContext().getFilename());
527 assert(FileID && "Invalid file id");
528 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
529 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
532 /// addSourceLine - Add location information to specified debug information
534 void DwarfDebug::addSourceLine(DIE *Die, DISubprogram SP) {
535 // Verify subprogram.
538 // If the line number is 0, don't add it.
539 if (SP.getLineNumber() == 0)
542 unsigned Line = SP.getLineNumber();
543 if (!SP.getContext().Verify())
545 unsigned FileID = GetOrCreateSourceID(SP.getDirectory(),
547 assert(FileID && "Invalid file id");
548 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
549 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
552 /// addSourceLine - Add location information to specified debug information
554 void DwarfDebug::addSourceLine(DIE *Die, DIType Ty) {
559 unsigned Line = Ty.getLineNumber();
560 if (!Ty.getContext().Verify())
562 unsigned FileID = GetOrCreateSourceID(Ty.getContext().getDirectory(),
563 Ty.getContext().getFilename());
564 assert(FileID && "Invalid file id");
565 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
566 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
569 /// addSourceLine - Add location information to specified debug information
571 void DwarfDebug::addSourceLine(DIE *Die, DINameSpace NS) {
576 unsigned Line = NS.getLineNumber();
577 StringRef FN = NS.getFilename();
578 StringRef Dir = NS.getDirectory();
580 unsigned FileID = GetOrCreateSourceID(Dir, FN);
581 assert(FileID && "Invalid file id");
582 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
583 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
586 /// addVariableAddress - Add DW_AT_location attribute for a DbgVariable based
587 /// on provided frame index.
588 void DwarfDebug::addVariableAddress(DbgVariable *&DV, DIE *Die, int64_t FI) {
589 MachineLocation Location;
591 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
592 int Offset = RI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
593 Location.set(FrameReg, Offset);
595 if (DV->variableHasComplexAddress())
596 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
597 else if (DV->isBlockByrefVariable())
598 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
600 addAddress(Die, dwarf::DW_AT_location, Location);
603 /// addComplexAddress - Start with the address based on the location provided,
604 /// and generate the DWARF information necessary to find the actual variable
605 /// given the extra address information encoded in the DIVariable, starting from
606 /// the starting location. Add the DWARF information to the die.
608 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
610 const MachineLocation &Location) {
611 DIType Ty = DV->getType();
613 // Decode the original location, and use that as the start of the byref
614 // variable's location.
615 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
616 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
617 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
619 if (Location.isReg()) {
621 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
623 Reg = Reg - dwarf::DW_OP_reg0;
624 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
625 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
629 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
631 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
632 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
635 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
638 for (unsigned i = 0, N = DV->getNumAddrElements(); i < N; ++i) {
639 uint64_t Element = DV->getAddrElement(i);
641 if (Element == DIFactory::OpPlus) {
642 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
643 addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
644 } else if (Element == DIFactory::OpDeref) {
645 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
646 } else llvm_unreachable("unknown DIFactory Opcode");
649 // Now attach the location information to the DIE.
650 addBlock(Die, Attribute, 0, Block);
653 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
654 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
655 gives the variable VarName either the struct, or a pointer to the struct, as
656 its type. This is necessary for various behind-the-scenes things the
657 compiler needs to do with by-reference variables in Blocks.
659 However, as far as the original *programmer* is concerned, the variable
660 should still have type 'SomeType', as originally declared.
662 The function getBlockByrefType dives into the __Block_byref_x_VarName
663 struct to find the original type of the variable, which is then assigned to
664 the variable's Debug Information Entry as its real type. So far, so good.
665 However now the debugger will expect the variable VarName to have the type
666 SomeType. So we need the location attribute for the variable to be an
667 expression that explains to the debugger how to navigate through the
668 pointers and struct to find the actual variable of type SomeType.
670 The following function does just that. We start by getting
671 the "normal" location for the variable. This will be the location
672 of either the struct __Block_byref_x_VarName or the pointer to the
673 struct __Block_byref_x_VarName.
675 The struct will look something like:
677 struct __Block_byref_x_VarName {
679 struct __Block_byref_x_VarName *forwarding;
680 ... <various other fields>
682 ... <maybe more fields>
685 If we are given the struct directly (as our starting point) we
686 need to tell the debugger to:
688 1). Add the offset of the forwarding field.
690 2). Follow that pointer to get the real __Block_byref_x_VarName
691 struct to use (the real one may have been copied onto the heap).
693 3). Add the offset for the field VarName, to find the actual variable.
695 If we started with a pointer to the struct, then we need to
696 dereference that pointer first, before the other steps.
697 Translating this into DWARF ops, we will need to append the following
698 to the current location description for the variable:
700 DW_OP_deref -- optional, if we start with a pointer
701 DW_OP_plus_uconst <forward_fld_offset>
703 DW_OP_plus_uconst <varName_fld_offset>
705 That is what this function does. */
707 /// addBlockByrefAddress - Start with the address based on the location
708 /// provided, and generate the DWARF information necessary to find the
709 /// actual Block variable (navigating the Block struct) based on the
710 /// starting location. Add the DWARF information to the die. For
711 /// more information, read large comment just above here.
713 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
715 const MachineLocation &Location) {
716 DIType Ty = DV->getType();
718 unsigned Tag = Ty.getTag();
719 bool isPointer = false;
721 StringRef varName = DV->getName();
723 if (Tag == dwarf::DW_TAG_pointer_type) {
724 DIDerivedType DTy = DIDerivedType(Ty);
725 TmpTy = DTy.getTypeDerivedFrom();
729 DICompositeType blockStruct = DICompositeType(TmpTy);
731 // Find the __forwarding field and the variable field in the __Block_byref
733 DIArray Fields = blockStruct.getTypeArray();
734 DIDescriptor varField = DIDescriptor();
735 DIDescriptor forwardingField = DIDescriptor();
737 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
738 DIDescriptor Element = Fields.getElement(i);
739 DIDerivedType DT = DIDerivedType(Element);
740 StringRef fieldName = DT.getName();
741 if (fieldName == "__forwarding")
742 forwardingField = Element;
743 else if (fieldName == varName)
747 // Get the offsets for the forwarding field and the variable field.
748 unsigned forwardingFieldOffset =
749 DIDerivedType(forwardingField).getOffsetInBits() >> 3;
750 unsigned varFieldOffset =
751 DIDerivedType(varField).getOffsetInBits() >> 3;
753 // Decode the original location, and use that as the start of the byref
754 // variable's location.
755 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
756 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
757 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
759 if (Location.isReg()) {
761 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
763 Reg = Reg - dwarf::DW_OP_reg0;
764 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
765 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
769 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
771 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
772 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
775 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
778 // If we started with a pointer to the __Block_byref... struct, then
779 // the first thing we need to do is dereference the pointer (DW_OP_deref).
781 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
783 // Next add the offset for the '__forwarding' field:
784 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
785 // adding the offset if it's 0.
786 if (forwardingFieldOffset > 0) {
787 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
788 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
791 // Now dereference the __forwarding field to get to the real __Block_byref
792 // struct: DW_OP_deref.
793 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
795 // Now that we've got the real __Block_byref... struct, add the offset
796 // for the variable's field to get to the location of the actual variable:
797 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
798 if (varFieldOffset > 0) {
799 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
800 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
803 // Now attach the location information to the DIE.
804 addBlock(Die, Attribute, 0, Block);
807 /// addAddress - Add an address attribute to a die based on the location
809 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
810 const MachineLocation &Location) {
811 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
812 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
813 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
814 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
816 if (TRI->getFrameRegister(*Asm->MF) == Location.getReg()
817 && Location.getOffset()) {
818 // If variable offset is based in frame register then use fbreg.
819 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
820 addSInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
821 addBlock(Die, Attribute, 0, Block);
825 if (Location.isReg()) {
827 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
829 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
830 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
834 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
836 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
837 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
840 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
843 addBlock(Die, Attribute, 0, Block);
846 /// addRegisterAddress - Add register location entry in variable DIE.
847 bool DwarfDebug::addRegisterAddress(DIE *Die, const MCSymbol *VS,
848 const MachineOperand &MO) {
849 assert (MO.isReg() && "Invalid machine operand!");
852 MachineLocation Location;
853 Location.set(MO.getReg());
854 addAddress(Die, dwarf::DW_AT_location, Location);
856 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
860 /// addConstantValue - Add constant value entry in variable DIE.
861 bool DwarfDebug::addConstantValue(DIE *Die, const MCSymbol *VS,
862 const MachineOperand &MO) {
863 assert (MO.isImm() && "Invalid machine operand!");
864 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
865 unsigned Imm = MO.getImm();
866 addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
867 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
869 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
873 /// addConstantFPValue - Add constant value entry in variable DIE.
874 bool DwarfDebug::addConstantFPValue(DIE *Die, const MCSymbol *VS,
875 const MachineOperand &MO) {
876 assert (MO.isFPImm() && "Invalid machine operand!");
877 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
878 APFloat FPImm = MO.getFPImm()->getValueAPF();
880 // Get the raw data form of the floating point.
881 const APInt FltVal = FPImm.bitcastToAPInt();
882 const char *FltPtr = (const char*)FltVal.getRawData();
884 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
885 bool LittleEndian = Asm->getTargetData().isLittleEndian();
886 int Incr = (LittleEndian ? 1 : -1);
887 int Start = (LittleEndian ? 0 : NumBytes - 1);
888 int Stop = (LittleEndian ? NumBytes : -1);
890 // Output the constant to DWARF one byte at a time.
891 for (; Start != Stop; Start += Incr)
892 addUInt(Block, 0, dwarf::DW_FORM_data1,
893 (unsigned char)0xFF & FltPtr[Start]);
895 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
897 addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
902 /// addToContextOwner - Add Die into the list of its context owner's children.
903 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
904 if (Context.isType()) {
905 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
906 ContextDIE->addChild(Die);
907 } else if (Context.isNameSpace()) {
908 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
909 ContextDIE->addChild(Die);
910 } else if (Context.isSubprogram()) {
911 DIE *ContextDIE = createSubprogramDIE(DISubprogram(Context));
912 ContextDIE->addChild(Die);
913 } else if (DIE *ContextDIE = getCompileUnit(Context)->getDIE(Context))
914 ContextDIE->addChild(Die);
916 getCompileUnit(Context)->addDie(Die);
919 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
921 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
922 CompileUnit *TypeCU = getCompileUnit(Ty);
923 DIE *TyDIE = TypeCU->getDIE(Ty);
928 TyDIE = new DIE(dwarf::DW_TAG_base_type);
929 TypeCU->insertDIE(Ty, TyDIE);
930 if (Ty.isBasicType())
931 constructTypeDIE(*TyDIE, DIBasicType(Ty));
932 else if (Ty.isCompositeType())
933 constructTypeDIE(*TyDIE, DICompositeType(Ty));
935 assert(Ty.isDerivedType() && "Unknown kind of DIType");
936 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
939 addToContextOwner(TyDIE, Ty.getContext());
943 /// addType - Add a new type attribute to the specified entity.
944 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
948 // Check for pre-existence.
949 CompileUnit *TypeCU = getCompileUnit(Ty);
950 DIEEntry *Entry = TypeCU->getDIEEntry(Ty);
951 // If it exists then use the existing value.
953 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
958 DIE *Buffer = getOrCreateTypeDIE(Ty);
961 Entry = createDIEEntry(Buffer);
962 TypeCU->insertDIEEntry(Ty, Entry);
964 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
967 /// constructTypeDIE - Construct basic type die from DIBasicType.
968 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
969 // Get core information.
970 StringRef Name = BTy.getName();
971 Buffer.setTag(dwarf::DW_TAG_base_type);
972 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
975 // Add name if not anonymous or intermediate type.
977 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
978 uint64_t Size = BTy.getSizeInBits() >> 3;
979 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
982 /// constructTypeDIE - Construct derived type die from DIDerivedType.
983 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
984 // Get core information.
985 StringRef Name = DTy.getName();
986 uint64_t Size = DTy.getSizeInBits() >> 3;
987 unsigned Tag = DTy.getTag();
989 // FIXME - Workaround for templates.
990 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
994 // Map to main type, void will not have a type.
995 DIType FromTy = DTy.getTypeDerivedFrom();
996 addType(&Buffer, FromTy);
998 // Add name if not anonymous or intermediate type.
1000 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1002 // Add size if non-zero (derived types might be zero-sized.)
1004 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1006 // Add source line info if available and TyDesc is not a forward declaration.
1007 if (!DTy.isForwardDecl())
1008 addSourceLine(&Buffer, DTy);
1011 /// constructTypeDIE - Construct type DIE from DICompositeType.
1012 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1013 // Get core information.
1014 StringRef Name = CTy.getName();
1016 uint64_t Size = CTy.getSizeInBits() >> 3;
1017 unsigned Tag = CTy.getTag();
1021 case dwarf::DW_TAG_vector_type:
1022 case dwarf::DW_TAG_array_type:
1023 constructArrayTypeDIE(Buffer, &CTy);
1025 case dwarf::DW_TAG_enumeration_type: {
1026 DIArray Elements = CTy.getTypeArray();
1028 // Add enumerators to enumeration type.
1029 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1030 DIE *ElemDie = NULL;
1031 DIDescriptor Enum(Elements.getElement(i));
1032 if (Enum.isEnumerator()) {
1033 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
1034 Buffer.addChild(ElemDie);
1039 case dwarf::DW_TAG_subroutine_type: {
1041 DIArray Elements = CTy.getTypeArray();
1042 DIDescriptor RTy = Elements.getElement(0);
1043 addType(&Buffer, DIType(RTy));
1045 // Add prototype flag.
1046 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1049 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1050 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1051 DIDescriptor Ty = Elements.getElement(i);
1052 addType(Arg, DIType(Ty));
1053 Buffer.addChild(Arg);
1057 case dwarf::DW_TAG_structure_type:
1058 case dwarf::DW_TAG_union_type:
1059 case dwarf::DW_TAG_class_type: {
1060 // Add elements to structure type.
1061 DIArray Elements = CTy.getTypeArray();
1063 // A forward struct declared type may not have elements available.
1064 unsigned N = Elements.getNumElements();
1068 // Add elements to structure type.
1069 for (unsigned i = 0; i < N; ++i) {
1070 DIDescriptor Element = Elements.getElement(i);
1071 DIE *ElemDie = NULL;
1072 if (Element.isSubprogram()) {
1073 DISubprogram SP(Element);
1074 ElemDie = createSubprogramDIE(DISubprogram(Element));
1075 if (SP.isProtected())
1076 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1077 dwarf::DW_ACCESS_protected);
1078 else if (SP.isPrivate())
1079 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1080 dwarf::DW_ACCESS_private);
1082 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1083 dwarf::DW_ACCESS_public);
1085 else if (Element.isVariable()) {
1086 DIVariable DV(Element);
1087 ElemDie = new DIE(dwarf::DW_TAG_variable);
1088 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1090 addType(ElemDie, DV.getType());
1091 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1092 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1093 addSourceLine(ElemDie, DV);
1094 } else if (Element.isDerivedType())
1095 ElemDie = createMemberDIE(DIDerivedType(Element));
1098 Buffer.addChild(ElemDie);
1101 if (CTy.isAppleBlockExtension())
1102 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1104 unsigned RLang = CTy.getRunTimeLang();
1106 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1107 dwarf::DW_FORM_data1, RLang);
1109 DICompositeType ContainingType = CTy.getContainingType();
1110 if (DIDescriptor(ContainingType).isCompositeType())
1111 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1112 getOrCreateTypeDIE(DIType(ContainingType)));
1114 DIDescriptor Context = CTy.getContext();
1115 addToContextOwner(&Buffer, Context);
1123 // Add name if not anonymous or intermediate type.
1125 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1127 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
1128 || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1130 // Add size if non-zero (derived types might be zero-sized.)
1132 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1134 // Add zero size if it is not a forward declaration.
1135 if (CTy.isForwardDecl())
1136 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1138 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1141 // Add source line info if available.
1142 if (!CTy.isForwardDecl())
1143 addSourceLine(&Buffer, CTy);
1147 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1148 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1149 int64_t L = SR.getLo();
1150 int64_t H = SR.getHi();
1151 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1153 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1155 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1156 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1158 Buffer.addChild(DW_Subrange);
1161 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1162 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1163 DICompositeType *CTy) {
1164 Buffer.setTag(dwarf::DW_TAG_array_type);
1165 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1166 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1168 // Emit derived type.
1169 addType(&Buffer, CTy->getTypeDerivedFrom());
1170 DIArray Elements = CTy->getTypeArray();
1172 // Get an anonymous type for index type.
1173 CompileUnit *TheCU = getCompileUnit(*CTy);
1174 DIE *IdxTy = TheCU->getIndexTyDie();
1176 // Construct an anonymous type for index type.
1177 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1178 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1179 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1180 dwarf::DW_ATE_signed);
1181 TheCU->addDie(IdxTy);
1182 TheCU->setIndexTyDie(IdxTy);
1185 // Add subranges to array type.
1186 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1187 DIDescriptor Element = Elements.getElement(i);
1188 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1189 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1193 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1194 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1195 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1196 StringRef Name = ETy.getName();
1197 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1198 int64_t Value = ETy.getEnumValue();
1199 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1203 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1204 /// printer to not emit usual symbol prefix before the symbol name is used then
1205 /// return linkage name after skipping this special LLVM prefix.
1206 static StringRef getRealLinkageName(StringRef LinkageName) {
1208 if (LinkageName.startswith(StringRef(&One, 1)))
1209 return LinkageName.substr(1);
1213 /// createMemberDIE - Create new member DIE.
1214 DIE *DwarfDebug::createMemberDIE(DIDerivedType DT) {
1215 DIE *MemberDie = new DIE(DT.getTag());
1216 StringRef Name = DT.getName();
1218 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1220 addType(MemberDie, DT.getTypeDerivedFrom());
1222 addSourceLine(MemberDie, DT);
1224 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1225 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1227 uint64_t Size = DT.getSizeInBits();
1228 uint64_t FieldSize = DT.getOriginalTypeSize();
1230 if (Size != FieldSize) {
1232 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1233 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1235 uint64_t Offset = DT.getOffsetInBits();
1236 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1237 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1238 uint64_t FieldOffset = (HiMark - FieldSize);
1239 Offset -= FieldOffset;
1241 // Maybe we need to work from the other end.
1242 if (Asm->getTargetData().isLittleEndian())
1243 Offset = FieldSize - (Offset + Size);
1244 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1246 // Here WD_AT_data_member_location points to the anonymous
1247 // field that includes this bit field.
1248 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1251 // This is not a bitfield.
1252 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1254 if (DT.getTag() == dwarf::DW_TAG_inheritance
1255 && DT.isVirtual()) {
1257 // For C++, virtual base classes are not at fixed offset. Use following
1258 // expression to extract appropriate offset from vtable.
1259 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1261 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1262 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1263 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1264 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1265 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1266 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1267 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1268 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1270 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1273 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1275 if (DT.isProtected())
1276 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1277 dwarf::DW_ACCESS_protected);
1278 else if (DT.isPrivate())
1279 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1280 dwarf::DW_ACCESS_private);
1281 // Otherwise C++ member and base classes are considered public.
1282 else if (DT.getCompileUnit().getLanguage() == dwarf::DW_LANG_C_plus_plus)
1283 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1284 dwarf::DW_ACCESS_public);
1286 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1287 dwarf::DW_VIRTUALITY_virtual);
1291 /// createSubprogramDIE - Create new DIE using SP.
1292 DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
1293 CompileUnit *SPCU = getCompileUnit(SP);
1294 DIE *SPDie = SPCU->getDIE(SP);
1298 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1299 // Constructors and operators for anonymous aggregates do not have names.
1300 if (!SP.getName().empty())
1301 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1303 StringRef LinkageName = SP.getLinkageName();
1304 if (!LinkageName.empty())
1305 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1306 getRealLinkageName(LinkageName));
1308 addSourceLine(SPDie, SP);
1310 // Add prototyped tag, if C or ObjC.
1311 unsigned Lang = SP.getCompileUnit().getLanguage();
1312 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1313 Lang == dwarf::DW_LANG_ObjC)
1314 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1317 DICompositeType SPTy = SP.getType();
1318 DIArray Args = SPTy.getTypeArray();
1319 unsigned SPTag = SPTy.getTag();
1321 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1322 addType(SPDie, SPTy);
1324 addType(SPDie, DIType(Args.getElement(0)));
1326 unsigned VK = SP.getVirtuality();
1328 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1329 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1330 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1331 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1332 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1333 ContainingTypeMap.insert(std::make_pair(SPDie,
1334 SP.getContainingType()));
1337 if (!SP.isDefinition()) {
1338 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1340 // Add arguments. Do not add arguments for subprogram definition. They will
1341 // be handled while processing variables.
1342 DICompositeType SPTy = SP.getType();
1343 DIArray Args = SPTy.getTypeArray();
1344 unsigned SPTag = SPTy.getTag();
1346 if (SPTag == dwarf::DW_TAG_subroutine_type)
1347 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1348 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1349 DIType ATy = DIType(DIType(Args.getElement(i)));
1351 if (ATy.isArtificial())
1352 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1353 SPDie->addChild(Arg);
1357 if (SP.isArtificial())
1358 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1360 if (!SP.isLocalToUnit())
1361 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1363 if (SP.isOptimized())
1364 addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1366 if (unsigned isa = Asm->getISAEncoding()) {
1367 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1370 // DW_TAG_inlined_subroutine may refer to this DIE.
1371 SPCU->insertDIE(SP, SPDie);
1373 // Add to context owner.
1374 addToContextOwner(SPDie, SP.getContext());
1379 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
1380 assert(N && "Invalid Scope encoding!");
1382 DbgScope *AScope = AbstractScopes.lookup(N);
1386 DbgScope *Parent = NULL;
1388 DIDescriptor Scope(N);
1389 if (Scope.isLexicalBlock()) {
1390 DILexicalBlock DB(N);
1391 DIDescriptor ParentDesc = DB.getContext();
1392 Parent = getOrCreateAbstractScope(ParentDesc);
1395 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1398 Parent->addScope(AScope);
1399 AScope->setAbstractScope();
1400 AbstractScopes[N] = AScope;
1401 if (DIDescriptor(N).isSubprogram())
1402 AbstractScopesList.push_back(AScope);
1406 /// isSubprogramContext - Return true if Context is either a subprogram
1407 /// or another context nested inside a subprogram.
1408 static bool isSubprogramContext(const MDNode *Context) {
1411 DIDescriptor D(Context);
1412 if (D.isSubprogram())
1415 return isSubprogramContext(DIType(Context).getContext());
1419 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1420 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1421 /// If there are global variables in this scope then create and insert
1422 /// DIEs for these variables.
1423 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
1424 CompileUnit *SPCU = getCompileUnit(SPNode);
1425 DIE *SPDie = SPCU->getDIE(SPNode);
1427 assert(SPDie && "Unable to find subprogram DIE!");
1428 DISubprogram SP(SPNode);
1430 // There is not any need to generate specification DIE for a function
1431 // defined at compile unit level. If a function is defined inside another
1432 // function then gdb prefers the definition at top level and but does not
1433 // expect specification DIE in parent function. So avoid creating
1434 // specification DIE for a function defined inside a function.
1435 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1436 !SP.getContext().isFile() &&
1437 !isSubprogramContext(SP.getContext())) {
1438 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1441 DICompositeType SPTy = SP.getType();
1442 DIArray Args = SPTy.getTypeArray();
1443 unsigned SPTag = SPTy.getTag();
1444 if (SPTag == dwarf::DW_TAG_subroutine_type)
1445 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1446 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1447 DIType ATy = DIType(DIType(Args.getElement(i)));
1449 if (ATy.isArtificial())
1450 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1451 SPDie->addChild(Arg);
1453 DIE *SPDeclDie = SPDie;
1454 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1455 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1457 SPCU->addDie(SPDie);
1460 // Pick up abstract subprogram DIE.
1461 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
1462 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1463 addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
1464 dwarf::DW_FORM_ref4, AbsSPDIE);
1465 SPCU->addDie(SPDie);
1468 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1469 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1470 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1471 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1472 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1473 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1474 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1479 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1480 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1481 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1483 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1484 if (Scope->isAbstractScope())
1487 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1491 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1492 if (Ranges.size() > 1) {
1493 // .debug_range section has not been laid out yet. Emit offset in
1494 // .debug_range as a uint, size 4, for now. emitDIE will handle
1495 // DW_AT_ranges appropriately.
1496 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1497 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1498 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1499 RE = Ranges.end(); RI != RE; ++RI) {
1500 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
1501 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
1503 DebugRangeSymbols.push_back(NULL);
1504 DebugRangeSymbols.push_back(NULL);
1508 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
1509 const MCSymbol *End = getLabelAfterInsn(RI->second);
1511 if (End == 0) return 0;
1513 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1514 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1516 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1517 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1522 /// constructInlinedScopeDIE - This scope represents inlined body of
1523 /// a function. Construct DIE to represent this concrete inlined copy
1524 /// of the function.
1525 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1527 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1528 assert (Ranges.empty() == false
1529 && "DbgScope does not have instruction markers!");
1531 // FIXME : .debug_inlined section specification does not clearly state how
1532 // to emit inlined scope that is split into multiple instruction ranges.
1533 // For now, use first instruction range and emit low_pc/high_pc pair and
1534 // corresponding .debug_inlined section entry for this pair.
1535 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1536 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
1537 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
1539 if (StartLabel == 0 || EndLabel == 0) {
1540 assert (0 && "Unexpected Start and End labels for a inlined scope!");
1543 assert(StartLabel->isDefined() &&
1544 "Invalid starting label for an inlined scope!");
1545 assert(EndLabel->isDefined() &&
1546 "Invalid end label for an inlined scope!");
1548 if (!Scope->getScopeNode())
1550 DIScope DS(Scope->getScopeNode());
1551 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1553 DISubprogram InlinedSP = getDISubprogram(DS);
1554 CompileUnit *TheCU = getCompileUnit(InlinedSP);
1555 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
1556 assert(OriginDIE && "Unable to find Origin DIE!");
1557 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1558 dwarf::DW_FORM_ref4, OriginDIE);
1560 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1561 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1563 InlinedSubprogramDIEs.insert(OriginDIE);
1565 // Track the start label for this inlined function.
1566 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1567 I = InlineInfo.find(InlinedSP);
1569 if (I == InlineInfo.end()) {
1570 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
1572 InlinedSPNodes.push_back(InlinedSP);
1574 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1576 DILocation DL(Scope->getInlinedAt());
1577 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
1578 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1584 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1585 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1586 StringRef Name = DV->getName();
1590 // Translate tag to proper Dwarf tag. The result variable is dropped for
1593 switch (DV->getTag()) {
1594 case dwarf::DW_TAG_return_variable:
1596 case dwarf::DW_TAG_arg_variable:
1597 Tag = dwarf::DW_TAG_formal_parameter;
1599 case dwarf::DW_TAG_auto_variable: // fall thru
1601 Tag = dwarf::DW_TAG_variable;
1605 // Define variable debug information entry.
1606 DIE *VariableDie = new DIE(Tag);
1609 DenseMap<const DbgVariable *, const DbgVariable *>::iterator
1610 V2AVI = VarToAbstractVarMap.find(DV);
1611 if (V2AVI != VarToAbstractVarMap.end())
1612 AbsDIE = V2AVI->second->getDIE();
1615 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1616 dwarf::DW_FORM_ref4, AbsDIE);
1618 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1619 addSourceLine(VariableDie, DV->getVariable());
1621 // Add variable type.
1622 addType(VariableDie, DV->getType());
1625 if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
1626 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1627 else if (DIVariable(DV->getVariable()).isArtificial())
1628 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1630 if (Scope->isAbstractScope()) {
1631 DV->setDIE(VariableDie);
1635 // Add variable address.
1637 unsigned Offset = DV->getDotDebugLocOffset();
1638 if (Offset != ~0U) {
1639 addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1640 Asm->GetTempSymbol("debug_loc", Offset));
1641 DV->setDIE(VariableDie);
1642 UseDotDebugLocEntry.insert(VariableDie);
1646 // Check if variable is described by a DBG_VALUE instruction.
1647 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
1648 DbgVariableToDbgInstMap.find(DV);
1649 if (DVI != DbgVariableToDbgInstMap.end()) {
1650 const MachineInstr *DVInsn = DVI->second;
1651 const MCSymbol *DVLabel = findVariableLabel(DV);
1652 bool updated = false;
1653 // FIXME : Handle getNumOperands != 3
1654 if (DVInsn->getNumOperands() == 3) {
1655 if (DVInsn->getOperand(0).isReg()) {
1656 const MachineOperand RegOp = DVInsn->getOperand(0);
1657 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1658 if (DVInsn->getOperand(1).isImm() &&
1659 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1660 addVariableAddress(DV, VariableDie, DVInsn->getOperand(1).getImm());
1663 updated = addRegisterAddress(VariableDie, DVLabel, RegOp);
1665 else if (DVInsn->getOperand(0).isImm())
1666 updated = addConstantValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1667 else if (DVInsn->getOperand(0).isFPImm())
1669 addConstantFPValue(VariableDie, DVLabel, DVInsn->getOperand(0));
1671 MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1672 if (Location.getReg()) {
1673 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1675 addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1681 // If variableDie is not updated then DBG_VALUE instruction does not
1682 // have valid variable info.
1686 DV->setDIE(VariableDie);
1690 // .. else use frame index, if available.
1692 if (findVariableFrameIndex(DV, &FI))
1693 addVariableAddress(DV, VariableDie, FI);
1695 DV->setDIE(VariableDie);
1700 void DwarfDebug::addPubTypes(DISubprogram SP) {
1701 DICompositeType SPTy = SP.getType();
1702 unsigned SPTag = SPTy.getTag();
1703 if (SPTag != dwarf::DW_TAG_subroutine_type)
1706 DIArray Args = SPTy.getTypeArray();
1707 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1708 DIType ATy(Args.getElement(i));
1711 DICompositeType CATy = getDICompositeType(ATy);
1712 if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
1713 && !CATy.isForwardDecl()) {
1714 CompileUnit *TheCU = getCompileUnit(CATy);
1715 if (DIEEntry *Entry = TheCU->getDIEEntry(CATy))
1716 TheCU->addGlobalType(CATy.getName(), Entry->getEntry());
1721 /// constructScopeDIE - Construct a DIE for this scope.
1722 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1723 if (!Scope || !Scope->getScopeNode())
1726 DIScope DS(Scope->getScopeNode());
1727 DIE *ScopeDIE = NULL;
1728 if (Scope->getInlinedAt())
1729 ScopeDIE = constructInlinedScopeDIE(Scope);
1730 else if (DS.isSubprogram()) {
1731 ProcessedSPNodes.insert(DS);
1732 if (Scope->isAbstractScope()) {
1733 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
1734 // Note down abstract DIE.
1736 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
1739 ScopeDIE = updateSubprogramScopeDIE(DS);
1742 ScopeDIE = constructLexicalScopeDIE(Scope);
1743 if (!ScopeDIE) return NULL;
1745 // Add variables to scope.
1746 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1747 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1748 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1750 ScopeDIE->addChild(VariableDIE);
1753 // Add nested scopes.
1754 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1755 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1756 // Define the Scope debug information entry.
1757 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1759 ScopeDIE->addChild(NestedDIE);
1762 if (DS.isSubprogram())
1763 addPubTypes(DISubprogram(DS));
1768 /// GetOrCreateSourceID - Look up the source id with the given directory and
1769 /// source file names. If none currently exists, create a new id and insert it
1770 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1772 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1774 assert (DirName.empty() == false && "Invalid directory name!");
1776 // If FE did not provide a file name, then assume stdin.
1777 if (FileName.empty())
1778 return GetOrCreateSourceID(DirName, "<stdin>");
1780 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1781 if (DI != DirectoryIdMap.end()) {
1782 DId = DI->getValue();
1784 DId = DirectoryNames.size() + 1;
1785 DirectoryIdMap[DirName] = DId;
1786 DirectoryNames.push_back(DirName);
1790 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1791 if (FI != SourceFileIdMap.end()) {
1792 FId = FI->getValue();
1794 FId = SourceFileNames.size() + 1;
1795 SourceFileIdMap[FileName] = FId;
1796 SourceFileNames.push_back(FileName);
1799 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1800 SourceIdMap.find(std::make_pair(DId, FId));
1801 if (SI != SourceIdMap.end())
1804 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1805 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1806 SourceIds.push_back(std::make_pair(DId, FId));
1811 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1812 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1813 CompileUnit *TheCU = getCompileUnit(NS);
1814 DIE *NDie = TheCU->getDIE(NS);
1817 NDie = new DIE(dwarf::DW_TAG_namespace);
1818 TheCU->insertDIE(NS, NDie);
1819 if (!NS.getName().empty())
1820 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1821 addSourceLine(NDie, NS);
1822 addToContextOwner(NDie, NS.getContext());
1826 /// constructCompileUnit - Create new CompileUnit for the given
1827 /// metadata node with tag DW_TAG_compile_unit.
1828 void DwarfDebug::constructCompileUnit(const MDNode *N) {
1829 DICompileUnit DIUnit(N);
1830 StringRef FN = DIUnit.getFilename();
1831 StringRef Dir = DIUnit.getDirectory();
1832 unsigned ID = GetOrCreateSourceID(Dir, FN);
1834 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1835 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1836 DIUnit.getProducer());
1837 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1838 DIUnit.getLanguage());
1839 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1840 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1841 // simplifies debug range entries.
1842 addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
1843 // DW_AT_stmt_list is a offset of line number information for this
1844 // compile unit in debug_line section.
1845 if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
1846 addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
1847 Asm->GetTempSymbol("section_line"));
1849 addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1852 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1853 if (DIUnit.isOptimized())
1854 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1856 StringRef Flags = DIUnit.getFlags();
1858 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1860 unsigned RVer = DIUnit.getRunTimeVersion();
1862 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1863 dwarf::DW_FORM_data1, RVer);
1865 CompileUnit *NewCU = new CompileUnit(ID, Die);
1868 CUMap.insert(std::make_pair(N, NewCU));
1871 /// getCompielUnit - Get CompileUnit DIE.
1872 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
1873 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
1875 const MDNode *CUNode = NULL;
1876 if (D.isCompileUnit())
1878 else if (D.isSubprogram())
1879 CUNode = DISubprogram(N).getCompileUnit();
1880 else if (D.isType())
1881 CUNode = DIType(N).getCompileUnit();
1882 else if (D.isGlobalVariable())
1883 CUNode = DIGlobalVariable(N).getCompileUnit();
1884 else if (D.isVariable())
1885 CUNode = DIVariable(N).getCompileUnit();
1886 else if (D.isNameSpace())
1887 CUNode = DINameSpace(N).getCompileUnit();
1888 else if (D.isFile())
1889 CUNode = DIFile(N).getCompileUnit();
1893 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
1894 = CUMap.find(CUNode);
1895 if (I == CUMap.end())
1900 /// isUnsignedDIType - Return true if type encoding is unsigned.
1901 static bool isUnsignedDIType(DIType Ty) {
1902 DIDerivedType DTy(Ty);
1904 return isUnsignedDIType(DTy.getTypeDerivedFrom());
1906 DIBasicType BTy(Ty);
1908 unsigned Encoding = BTy.getEncoding();
1909 if (Encoding == dwarf::DW_ATE_unsigned ||
1910 Encoding == dwarf::DW_ATE_unsigned_char)
1916 /// constructGlobalVariableDIE - Construct global variable DIE.
1917 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
1918 DIGlobalVariable GV(N);
1920 // If debug information is malformed then ignore it.
1921 if (GV.Verify() == false)
1924 // Check for pre-existence.
1925 CompileUnit *TheCU = getCompileUnit(N);
1926 if (TheCU->getDIE(GV))
1929 DIType GTy = GV.getType();
1930 DIE *VariableDIE = new DIE(GV.getTag());
1932 bool isGlobalVariable = GV.getGlobal() != NULL;
1935 addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1936 GV.getDisplayName());
1937 StringRef LinkageName = GV.getLinkageName();
1938 if (!LinkageName.empty() && isGlobalVariable)
1939 addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1940 getRealLinkageName(LinkageName));
1942 addType(VariableDIE, GTy);
1943 if (GTy.isCompositeType() && !GTy.getName().empty()
1944 && !GTy.isForwardDecl()) {
1945 DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1946 assert(Entry && "Missing global type!");
1947 TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1949 // Add scoping info.
1950 if (!GV.isLocalToUnit()) {
1951 addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1952 // Expose as global.
1953 TheCU->addGlobal(GV.getName(), VariableDIE);
1955 // Add line number info.
1956 addSourceLine(VariableDIE, GV);
1958 TheCU->insertDIE(N, VariableDIE);
1959 // Add to context owner.
1960 DIDescriptor GVContext = GV.getContext();
1961 addToContextOwner(VariableDIE, GVContext);
1963 if (isGlobalVariable) {
1964 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1965 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1966 addLabel(Block, 0, dwarf::DW_FORM_udata,
1967 Asm->Mang->getSymbol(GV.getGlobal()));
1968 // Do not create specification DIE if context is either compile unit
1970 if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1971 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1972 // Create specification DIE.
1973 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1974 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1975 dwarf::DW_FORM_ref4, VariableDIE);
1976 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1977 addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1978 TheCU->addDie(VariableSpecDIE);
1980 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1982 } else if (Constant *C = GV.getConstant()) {
1983 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1984 if (isUnsignedDIType(GTy))
1985 addUInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
1986 CI->getZExtValue());
1988 addSInt(VariableDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1989 CI->getSExtValue());
1995 /// construct SubprogramDIE - Construct subprogram DIE.
1996 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1999 // Check for pre-existence.
2000 CompileUnit *TheCU = getCompileUnit(N);
2001 if (TheCU->getDIE(N))
2004 if (!SP.isDefinition())
2005 // This is a method declaration which will be handled while constructing
2009 DIE *SubprogramDie = createSubprogramDIE(SP);
2012 TheCU->insertDIE(N, SubprogramDie);
2014 // Add to context owner.
2015 addToContextOwner(SubprogramDie, SP.getContext());
2017 // Expose as global.
2018 TheCU->addGlobal(SP.getName(), SubprogramDie);
2023 /// beginModule - Emit all Dwarf sections that should come prior to the
2024 /// content. Create global DIEs and emit initial debug info sections.
2025 /// This is inovked by the target AsmPrinter.
2026 void DwarfDebug::beginModule(Module *M) {
2027 if (DisableDebugInfoPrinting)
2030 DebugInfoFinder DbgFinder;
2031 DbgFinder.processModule(*M);
2033 bool HasDebugInfo = false;
2035 // Scan all the compile-units to see if there are any marked as the main unit.
2036 // if not, we do not generate debug info.
2037 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2038 E = DbgFinder.compile_unit_end(); I != E; ++I) {
2039 if (DICompileUnit(*I).isMain()) {
2040 HasDebugInfo = true;
2045 if (!HasDebugInfo) return;
2047 // Tell MMI that we have debug info.
2048 MMI->setDebugInfoAvailability(true);
2050 // Emit initial sections.
2051 EmitSectionLabels();
2053 // Create all the compile unit DIEs.
2054 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
2055 E = DbgFinder.compile_unit_end(); I != E; ++I)
2056 constructCompileUnit(*I);
2058 // Create DIEs for each subprogram.
2059 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
2060 E = DbgFinder.subprogram_end(); I != E; ++I)
2061 constructSubprogramDIE(*I);
2063 // Create DIEs for each global variable.
2064 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
2065 E = DbgFinder.global_variable_end(); I != E; ++I)
2066 constructGlobalVariableDIE(*I);
2068 //getOrCreateTypeDIE
2069 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
2070 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2071 getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2073 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
2074 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
2075 getOrCreateTypeDIE(DIType(NMD->getOperand(i)));
2077 // Prime section data.
2078 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
2080 // Print out .file directives to specify files for .loc directives. These are
2081 // printed out early so that they precede any .loc directives.
2082 if (Asm->MAI->hasDotLocAndDotFile()) {
2083 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2084 // Remember source id starts at 1.
2085 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2086 // FIXME: don't use sys::path for this! This should not depend on the
2088 sys::Path FullPath(getSourceDirectoryName(Id.first));
2090 FullPath.appendComponent(getSourceFileName(Id.second));
2091 assert(AppendOk && "Could not append filename to directory!");
2093 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
2098 /// endModule - Emit all Dwarf sections that should come after the content.
2100 void DwarfDebug::endModule() {
2101 if (!FirstCU) return;
2102 const Module *M = MMI->getModule();
2103 DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
2104 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
2105 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
2106 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
2107 DISubprogram SP(AllSPs->getOperand(SI));
2108 if (!SP.Verify()) continue;
2110 // Collect info for variables that were optimized out.
2111 if (!SP.isDefinition()) continue;
2112 StringRef FName = SP.getLinkageName();
2114 FName = SP.getName();
2116 M->getNamedMetadata(Twine("llvm.dbg.lv.", getRealLinkageName(FName)));
2118 unsigned E = NMD->getNumOperands();
2120 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
2121 DeadFnScopeMap[SP] = Scope;
2122 for (unsigned I = 0; I != E; ++I) {
2123 DIVariable DV(NMD->getOperand(I));
2124 if (!DV.Verify()) continue;
2125 Scope->addVariable(new DbgVariable(DV));
2128 // Construct subprogram DIE and add variables DIEs.
2129 constructSubprogramDIE(SP);
2130 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
2131 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
2132 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2133 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
2135 ScopeDIE->addChild(VariableDIE);
2140 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
2141 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
2142 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
2144 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
2147 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
2148 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
2149 DIE *SPDie = CI->first;
2150 const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
2152 DIE *NDie = getCompileUnit(N)->getDIE(N);
2153 if (!NDie) continue;
2154 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
2157 // Standard sections final addresses.
2158 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
2159 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
2160 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
2161 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
2163 // End text sections.
2164 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2165 Asm->OutStreamer.SwitchSection(SectionMap[i]);
2166 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
2169 // Emit common frame information.
2170 emitCommonDebugFrame();
2172 // Emit function debug frame information
2173 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2174 E = DebugFrames.end(); I != E; ++I)
2175 emitFunctionDebugFrame(*I);
2177 // Compute DIE offsets and sizes.
2178 computeSizeAndOffsets();
2180 // Emit all the DIEs into a debug info section
2183 // Corresponding abbreviations into a abbrev section.
2184 emitAbbreviations();
2186 // Emit source line correspondence into a debug line section.
2189 // Emit info into a debug pubnames section.
2190 emitDebugPubNames();
2192 // Emit info into a debug pubtypes section.
2193 emitDebugPubTypes();
2195 // Emit info into a debug loc section.
2198 // Emit info into a debug aranges section.
2201 // Emit info into a debug ranges section.
2204 // Emit info into a debug macinfo section.
2207 // Emit inline info.
2208 emitDebugInlineInfo();
2210 // Emit info into a debug str section.
2214 DeleteContainerSeconds(DeadFnScopeMap);
2215 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2216 E = CUMap.end(); I != E; ++I)
2218 FirstCU = NULL; // Reset for the next Module, if any.
2221 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2222 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2223 DebugLoc ScopeLoc) {
2225 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2227 return AbsDbgVariable;
2229 LLVMContext &Ctx = Var->getContext();
2230 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2234 AbsDbgVariable = new DbgVariable(Var);
2235 Scope->addVariable(AbsDbgVariable);
2236 AbstractVariables[Var] = AbsDbgVariable;
2237 return AbsDbgVariable;
2240 /// collectVariableInfoFromMMITable - Collect variable information from
2241 /// side table maintained by MMI.
2243 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
2244 SmallPtrSet<const MDNode *, 16> &Processed) {
2245 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2246 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2247 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2248 VE = VMap.end(); VI != VE; ++VI) {
2249 const MDNode *Var = VI->first;
2251 Processed.insert(Var);
2253 const std::pair<unsigned, DebugLoc> &VP = VI->second;
2255 DbgScope *Scope = 0;
2256 if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
2257 Scope = ConcreteScopes.lookup(IA);
2259 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2261 // If variable scope is not found then skip this variable.
2265 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
2266 DbgVariable *RegVar = new DbgVariable(DV);
2267 recordVariableFrameIndex(RegVar, VP.first);
2268 Scope->addVariable(RegVar);
2269 if (AbsDbgVariable) {
2270 recordVariableFrameIndex(AbsDbgVariable, VP.first);
2271 VarToAbstractVarMap[RegVar] = AbsDbgVariable;
2276 /// isDbgValueInUndefinedReg - Return true if debug value, encoded by
2277 /// DBG_VALUE instruction, is in undefined reg.
2278 static bool isDbgValueInUndefinedReg(const MachineInstr *MI) {
2279 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2280 if (MI->getOperand(0).isReg() && !MI->getOperand(0).getReg())
2285 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
2286 /// DBG_VALUE instruction, is in a defined reg.
2287 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
2288 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
2289 if (MI->getOperand(0).isReg() && MI->getOperand(0).getReg())
2294 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2296 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
2297 SmallPtrSet<const MDNode *, 16> &Processed) {
2299 /// collection info from MMI table.
2300 collectVariableInfoFromMMITable(MF, Processed);
2302 SmallVector<const MachineInstr *, 8> DbgValues;
2303 // Collect variable information from DBG_VALUE machine instructions;
2304 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2306 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2308 const MachineInstr *MInsn = II;
2309 if (!MInsn->isDebugValue() || isDbgValueInUndefinedReg(MInsn))
2311 DbgValues.push_back(MInsn);
2314 // This is a collection of DBV_VALUE instructions describing same variable.
2315 SmallVector<const MachineInstr *, 4> MultipleValues;
2316 for(SmallVector<const MachineInstr *, 8>::iterator I = DbgValues.begin(),
2317 E = DbgValues.end(); I != E; ++I) {
2318 const MachineInstr *MInsn = *I;
2319 MultipleValues.clear();
2320 if (isDbgValueInDefinedReg(MInsn))
2321 MultipleValues.push_back(MInsn);
2322 DIVariable DV(MInsn->getOperand(MInsn->getNumOperands() - 1).getMetadata());
2323 if (Processed.count(DV) != 0)
2326 const MachineInstr *PrevMI = MInsn;
2327 for (SmallVector<const MachineInstr *, 8>::iterator MI = I+1,
2328 ME = DbgValues.end(); MI != ME; ++MI) {
2330 (*MI)->getOperand((*MI)->getNumOperands()-1).getMetadata();
2331 if (Var == DV && isDbgValueInDefinedReg(*MI) &&
2332 !PrevMI->isIdenticalTo(*MI))
2333 MultipleValues.push_back(*MI);
2337 DbgScope *Scope = findDbgScope(MInsn);
2338 bool CurFnArg = false;
2339 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
2340 DISubprogram(DV.getContext()).describes(MF->getFunction()))
2342 if (!Scope && CurFnArg)
2343 Scope = CurrentFnDbgScope;
2344 // If variable scope is not found then skip this variable.
2348 Processed.insert(DV);
2349 DbgVariable *RegVar = new DbgVariable(DV);
2350 Scope->addVariable(RegVar);
2352 DbgVariableLabelsMap[RegVar] = getLabelBeforeInsn(MInsn);
2353 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
2354 DbgVariableToDbgInstMap[AbsVar] = MInsn;
2355 VarToAbstractVarMap[RegVar] = AbsVar;
2357 if (MultipleValues.size() <= 1) {
2358 DbgVariableToDbgInstMap[RegVar] = MInsn;
2362 // handle multiple DBG_VALUE instructions describing one variable.
2363 if (DotDebugLocEntries.empty())
2364 RegVar->setDotDebugLocOffset(0);
2366 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
2367 const MachineInstr *Begin = NULL;
2368 const MachineInstr *End = NULL;
2369 for (SmallVector<const MachineInstr *, 4>::iterator
2370 MVI = MultipleValues.begin(), MVE = MultipleValues.end();
2371 MVI != MVE; ++MVI) {
2377 MachineLocation MLoc;
2378 if (Begin->getNumOperands() == 3) {
2379 if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2380 MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2382 MLoc = Asm->getDebugValueLocation(Begin);
2384 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
2385 const MCSymbol *SLabel = getLabelBeforeInsn(End);
2387 DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
2390 if (MVI + 1 == MVE) {
2391 // If End is the last instruction then its value is valid
2392 // until the end of the funtion.
2393 MachineLocation EMLoc;
2394 if (End->getNumOperands() == 3) {
2395 if (End->getOperand(0).isReg() && Begin->getOperand(1).isImm())
2396 EMLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
2398 EMLoc = Asm->getDebugValueLocation(End);
2401 push_back(DotDebugLocEntry(SLabel, FunctionEndSym, EMLoc));
2404 DotDebugLocEntries.push_back(DotDebugLocEntry());
2407 // Collect info for variables that were optimized out.
2408 const Function *F = MF->getFunction();
2409 const Module *M = F->getParent();
2410 if (NamedMDNode *NMD =
2411 M->getNamedMetadata(Twine("llvm.dbg.lv.",
2412 getRealLinkageName(F->getName())))) {
2413 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2414 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2415 if (!DV || !Processed.insert(DV))
2417 DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
2419 Scope->addVariable(new DbgVariable(DV));
2424 /// getLabelBeforeInsn - Return Label preceding the instruction.
2425 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
2426 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2427 LabelsBeforeInsn.find(MI);
2428 if (I == LabelsBeforeInsn.end())
2429 // FunctionBeginSym always preceeds all the instruction in current function.
2430 return FunctionBeginSym;
2434 /// getLabelAfterInsn - Return Label immediately following the instruction.
2435 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
2436 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
2437 LabelsAfterInsn.find(MI);
2438 if (I == LabelsAfterInsn.end())
2443 /// beginScope - Process beginning of a scope.
2444 void DwarfDebug::beginScope(const MachineInstr *MI) {
2445 if (InsnNeedsLabel.count(MI) == 0) {
2446 LabelsBeforeInsn[MI] = PrevLabel;
2451 DebugLoc DL = MI->getDebugLoc();
2452 if (!DL.isUnknown()) {
2453 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2454 PrevLabel = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2456 LabelsBeforeInsn[MI] = PrevLabel;
2460 // If location is unknown then use temp label for this DBG_VALUE
2462 if (MI->isDebugValue()) {
2463 PrevLabel = MMI->getContext().CreateTempSymbol();
2464 Asm->OutStreamer.EmitLabel(PrevLabel);
2465 LabelsBeforeInsn[MI] = PrevLabel;
2469 if (UnknownLocations) {
2470 PrevLabel = recordSourceLine(0, 0, 0);
2471 LabelsBeforeInsn[MI] = PrevLabel;
2475 assert (0 && "Instruction is not processed!");
2478 /// endScope - Process end of a scope.
2479 void DwarfDebug::endScope(const MachineInstr *MI) {
2480 if (InsnsEndScopeSet.count(MI) != 0) {
2481 // Emit a label if this instruction ends a scope.
2482 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2483 Asm->OutStreamer.EmitLabel(Label);
2484 LabelsAfterInsn[MI] = Label;
2488 /// getOrCreateDbgScope - Create DbgScope for the scope.
2489 DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
2490 const MDNode *InlinedAt) {
2492 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2495 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2496 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2497 if (DIDescriptor(Scope).isLexicalBlock()) {
2499 getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
2500 WScope->setParent(Parent);
2501 Parent->addScope(WScope);
2504 if (!WScope->getParent()) {
2505 StringRef SPName = DISubprogram(Scope).getLinkageName();
2506 // We used to check only for a linkage name, but that fails
2507 // since we began omitting the linkage name for private
2508 // functions. The new way is to check for the name in metadata,
2509 // but that's not supported in old .ll test cases. Ergo, we
2511 if (SPName == Asm->MF->getFunction()->getName() ||
2512 DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
2513 CurrentFnDbgScope = WScope;
2519 getOrCreateAbstractScope(Scope);
2520 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2524 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2525 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2526 DILocation DL(InlinedAt);
2528 getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
2529 WScope->setParent(Parent);
2530 Parent->addScope(WScope);
2532 ConcreteScopes[InlinedAt] = WScope;
2537 /// hasValidLocation - Return true if debug location entry attached with
2538 /// machine instruction encodes valid location info.
2539 static bool hasValidLocation(LLVMContext &Ctx,
2540 const MachineInstr *MInsn,
2541 const MDNode *&Scope, const MDNode *&InlinedAt) {
2542 DebugLoc DL = MInsn->getDebugLoc();
2543 if (DL.isUnknown()) return false;
2545 const MDNode *S = DL.getScope(Ctx);
2547 // There is no need to create another DIE for compile unit. For all
2548 // other scopes, create one DbgScope now. This will be translated
2549 // into a scope DIE at the end.
2550 if (DIScope(S).isCompileUnit()) return false;
2553 InlinedAt = DL.getInlinedAt(Ctx);
2557 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2559 static void calculateDominanceGraph(DbgScope *Scope) {
2560 assert (Scope && "Unable to calculate scop edominance graph!");
2561 SmallVector<DbgScope *, 4> WorkStack;
2562 WorkStack.push_back(Scope);
2563 unsigned Counter = 0;
2564 while (!WorkStack.empty()) {
2565 DbgScope *WS = WorkStack.back();
2566 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2567 bool visitedChildren = false;
2568 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2569 SE = Children.end(); SI != SE; ++SI) {
2570 DbgScope *ChildScope = *SI;
2571 if (!ChildScope->getDFSOut()) {
2572 WorkStack.push_back(ChildScope);
2573 visitedChildren = true;
2574 ChildScope->setDFSIn(++Counter);
2578 if (!visitedChildren) {
2579 WorkStack.pop_back();
2580 WS->setDFSOut(++Counter);
2585 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2587 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2588 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2591 unsigned PrevDFSIn = 0;
2592 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2594 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2596 const MachineInstr *MInsn = II;
2597 const MDNode *Scope = NULL;
2598 const MDNode *InlinedAt = NULL;
2600 // Check if instruction has valid location information.
2601 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2605 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
2606 MI2ScopeMap.find(MInsn);
2607 if (DI != MI2ScopeMap.end()) {
2608 DbgScope *S = DI->second;
2609 dbgs() << S->getDFSIn();
2610 PrevDFSIn = S->getDFSIn();
2612 dbgs() << PrevDFSIn;
2614 dbgs() << " [ x" << PrevDFSIn;
2622 /// extractScopeInformation - Scan machine instructions in this function
2623 /// and collect DbgScopes. Return true, if at least one scope was found.
2624 bool DwarfDebug::extractScopeInformation() {
2625 // If scope information was extracted using .dbg intrinsics then there is not
2626 // any need to extract these information by scanning each instruction.
2627 if (!DbgScopeMap.empty())
2630 // Scan each instruction and create scopes. First build working set of scopes.
2631 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2632 SmallVector<DbgRange, 4> MIRanges;
2633 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2634 const MDNode *PrevScope = NULL;
2635 const MDNode *PrevInlinedAt = NULL;
2636 const MachineInstr *RangeBeginMI = NULL;
2637 const MachineInstr *PrevMI = NULL;
2638 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2640 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2642 const MachineInstr *MInsn = II;
2643 const MDNode *Scope = NULL;
2644 const MDNode *InlinedAt = NULL;
2646 // Check if instruction has valid location information.
2647 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2652 // If scope has not changed then skip this instruction.
2653 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2659 // If we have alread seen a beginning of a instruction range and
2660 // current instruction scope does not match scope of first instruction
2661 // in this range then create a new instruction range.
2662 DbgRange R(RangeBeginMI, PrevMI);
2663 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
2665 MIRanges.push_back(R);
2668 // This is a beginning of a new instruction range.
2669 RangeBeginMI = MInsn;
2671 // Reset previous markers.
2674 PrevInlinedAt = InlinedAt;
2678 // Create last instruction range.
2679 if (RangeBeginMI && PrevMI && PrevScope) {
2680 DbgRange R(RangeBeginMI, PrevMI);
2681 MIRanges.push_back(R);
2682 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2685 if (!CurrentFnDbgScope)
2688 calculateDominanceGraph(CurrentFnDbgScope);
2690 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2692 // Find ranges of instructions covered by each DbgScope;
2693 DbgScope *PrevDbgScope = NULL;
2694 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2695 RE = MIRanges.end(); RI != RE; ++RI) {
2696 const DbgRange &R = *RI;
2697 DbgScope *S = MI2ScopeMap.lookup(R.first);
2698 assert (S && "Lost DbgScope for a machine instruction!");
2699 if (PrevDbgScope && !PrevDbgScope->dominates(S))
2700 PrevDbgScope->closeInsnRange(S);
2701 S->openInsnRange(R.first);
2702 S->extendInsnRange(R.second);
2707 PrevDbgScope->closeInsnRange();
2709 identifyScopeMarkers();
2711 return !DbgScopeMap.empty();
2714 /// identifyScopeMarkers() -
2715 /// Each DbgScope has first instruction and last instruction to mark beginning
2716 /// and end of a scope respectively. Create an inverse map that list scopes
2717 /// starts (and ends) with an instruction. One instruction may start (or end)
2718 /// multiple scopes. Ignore scopes that are not reachable.
2719 void DwarfDebug::identifyScopeMarkers() {
2720 SmallVector<DbgScope *, 4> WorkList;
2721 WorkList.push_back(CurrentFnDbgScope);
2722 while (!WorkList.empty()) {
2723 DbgScope *S = WorkList.pop_back_val();
2725 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2726 if (!Children.empty())
2727 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2728 SE = Children.end(); SI != SE; ++SI)
2729 WorkList.push_back(*SI);
2731 if (S->isAbstractScope())
2734 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2737 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2738 RE = Ranges.end(); RI != RE; ++RI) {
2739 assert(RI->first && "DbgRange does not have first instruction!");
2740 assert(RI->second && "DbgRange does not have second instruction!");
2741 InsnsEndScopeSet.insert(RI->second);
2746 /// FindFirstDebugLoc - Find the first debug location in the function. This
2747 /// is intended to be an approximation for the source position of the
2748 /// beginning of the function.
2749 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2750 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2752 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2753 MBBI != MBBE; ++MBBI) {
2754 DebugLoc DL = MBBI->getDebugLoc();
2755 if (!DL.isUnknown())
2761 /// beginFunction - Gather pre-function debug information. Assumes being
2762 /// emitted immediately after the function entry point.
2763 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2764 if (!MMI->hasDebugInfo()) return;
2765 if (!extractScopeInformation()) return;
2767 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2768 Asm->getFunctionNumber());
2769 // Assumes in correct section after the entry point.
2770 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2772 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2774 DebugLoc FDL = FindFirstDebugLoc(MF);
2775 if (FDL.isUnknown()) return;
2777 const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2778 const MDNode *TheScope = 0;
2780 DISubprogram SP = getDISubprogram(Scope);
2783 Line = SP.getLineNumber();
2787 Line = FDL.getLine();
2792 recordSourceLine(Line, Col, TheScope);
2794 /// ProcessedArgs - Collection of arguments already processed.
2795 SmallPtrSet<const MDNode *, 8> ProcessedArgs;
2798 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2800 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2802 const MachineInstr *MI = II;
2803 DebugLoc DL = MI->getDebugLoc();
2804 if (MI->isDebugValue()) {
2805 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
2806 DIVariable DV(MI->getOperand(MI->getNumOperands() - 1).getMetadata());
2807 if (!DV.Verify()) continue;
2808 // If DBG_VALUE is for a local variable then it needs a label.
2809 if (DV.getTag() != dwarf::DW_TAG_arg_variable
2810 && isDbgValueInUndefinedReg(MI) == false)
2811 InsnNeedsLabel.insert(MI);
2812 // DBG_VALUE for inlined functions argument needs a label.
2813 else if (!DISubprogram(getDISubprogram(DV.getContext())).
2814 describes(MF->getFunction()))
2815 InsnNeedsLabel.insert(MI);
2816 // DBG_VALUE indicating argument location change needs a label.
2817 else if (isDbgValueInUndefinedReg(MI) == false
2818 && !ProcessedArgs.insert(DV))
2819 InsnNeedsLabel.insert(MI);
2821 // If location is unknown then instruction needs a location only if
2822 // UnknownLocations flag is set.
2823 if (DL.isUnknown()) {
2824 if (UnknownLocations && !PrevLoc.isUnknown())
2825 InsnNeedsLabel.insert(MI);
2826 } else if (DL != PrevLoc)
2827 // Otherwise, instruction needs a location only if it is new location.
2828 InsnNeedsLabel.insert(MI);
2831 if (!DL.isUnknown() || UnknownLocations)
2835 PrevLabel = FunctionBeginSym;
2838 /// endFunction - Gather and emit post-function debug information.
2840 void DwarfDebug::endFunction(const MachineFunction *MF) {
2841 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2843 if (CurrentFnDbgScope) {
2845 // Define end label for subprogram.
2846 FunctionEndSym = Asm->GetTempSymbol("func_end",
2847 Asm->getFunctionNumber());
2848 // Assumes in correct section after the entry point.
2849 Asm->OutStreamer.EmitLabel(FunctionEndSym);
2851 SmallPtrSet<const MDNode *, 16> ProcessedVars;
2852 collectVariableInfo(MF, ProcessedVars);
2854 // Get function line info.
2855 if (!Lines.empty()) {
2856 // Get section line info.
2857 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2858 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2859 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2860 // Append the function info to section info.
2861 SectionLineInfos.insert(SectionLineInfos.end(),
2862 Lines.begin(), Lines.end());
2865 // Construct abstract scopes.
2866 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2867 AE = AbstractScopesList.end(); AI != AE; ++AI) {
2868 DISubprogram SP((*AI)->getScopeNode());
2870 // Collect info for variables that were optimized out.
2871 StringRef FName = SP.getLinkageName();
2873 FName = SP.getName();
2874 const Module *M = MF->getFunction()->getParent();
2875 if (NamedMDNode *NMD =
2876 M->getNamedMetadata(Twine("llvm.dbg.lv.",
2877 getRealLinkageName(FName)))) {
2878 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2879 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2880 if (!DV || !ProcessedVars.insert(DV))
2882 DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2884 Scope->addVariable(new DbgVariable(DV));
2888 if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2889 constructScopeDIE(*AI);
2892 DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2894 if (!DisableFramePointerElim(*MF))
2895 addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
2896 dwarf::DW_FORM_flag, 1);
2899 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2900 MMI->getFrameMoves()));
2904 CurrentFnDbgScope = NULL;
2905 InsnNeedsLabel.clear();
2906 DbgVariableToFrameIndexMap.clear();
2907 VarToAbstractVarMap.clear();
2908 DbgVariableToDbgInstMap.clear();
2909 DbgVariableLabelsMap.clear();
2910 DeleteContainerSeconds(DbgScopeMap);
2911 InsnsEndScopeSet.clear();
2912 ConcreteScopes.clear();
2913 DeleteContainerSeconds(AbstractScopes);
2914 AbstractScopesList.clear();
2915 AbstractVariables.clear();
2916 LabelsBeforeInsn.clear();
2917 LabelsAfterInsn.clear();
2922 /// recordVariableFrameIndex - Record a variable's index.
2923 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2924 assert (V && "Invalid DbgVariable!");
2925 DbgVariableToFrameIndexMap[V] = Index;
2928 /// findVariableFrameIndex - Return true if frame index for the variable
2929 /// is found. Update FI to hold value of the index.
2930 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2931 assert (V && "Invalid DbgVariable!");
2932 DenseMap<const DbgVariable *, int>::iterator I =
2933 DbgVariableToFrameIndexMap.find(V);
2934 if (I == DbgVariableToFrameIndexMap.end())
2940 /// findVariableLabel - Find MCSymbol for the variable.
2941 const MCSymbol *DwarfDebug::findVariableLabel(const DbgVariable *V) {
2942 DenseMap<const DbgVariable *, const MCSymbol *>::iterator I
2943 = DbgVariableLabelsMap.find(V);
2944 if (I == DbgVariableLabelsMap.end())
2946 else return I->second;
2949 /// findDbgScope - Find DbgScope for the debug loc attached with an
2951 DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2952 DbgScope *Scope = NULL;
2954 MInsn->getParent()->getParent()->getFunction()->getContext();
2955 DebugLoc DL = MInsn->getDebugLoc();
2960 if (const MDNode *IA = DL.getInlinedAt(Ctx))
2961 Scope = ConcreteScopes.lookup(IA);
2963 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2969 /// recordSourceLine - Register a source line with debug info. Returns the
2970 /// unique label that was emitted and which provides correspondence to
2971 /// the source line list.
2972 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2979 DIDescriptor Scope(S);
2981 if (Scope.isCompileUnit()) {
2982 DICompileUnit CU(S);
2983 Dir = CU.getDirectory();
2984 Fn = CU.getFilename();
2985 } else if (Scope.isSubprogram()) {
2987 Dir = SP.getDirectory();
2988 Fn = SP.getFilename();
2989 } else if (Scope.isLexicalBlock()) {
2990 DILexicalBlock DB(S);
2991 Dir = DB.getDirectory();
2992 Fn = DB.getFilename();
2994 assert(0 && "Unexpected scope info");
2996 Src = GetOrCreateSourceID(Dir, Fn);
2999 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
3000 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
3002 Asm->OutStreamer.EmitLabel(Label);
3006 //===----------------------------------------------------------------------===//
3008 //===----------------------------------------------------------------------===//
3010 /// computeSizeAndOffset - Compute the size and offset of a DIE.
3013 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
3014 // Get the children.
3015 const std::vector<DIE *> &Children = Die->getChildren();
3017 // If not last sibling and has children then add sibling offset attribute.
3018 if (!Last && !Children.empty())
3019 Die->addSiblingOffset(DIEValueAllocator);
3021 // Record the abbreviation.
3022 assignAbbrevNumber(Die->getAbbrev());
3024 // Get the abbreviation for this DIE.
3025 unsigned AbbrevNumber = Die->getAbbrevNumber();
3026 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3029 Die->setOffset(Offset);
3031 // Start the size with the size of abbreviation code.
3032 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
3034 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3035 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3037 // Size the DIE attribute values.
3038 for (unsigned i = 0, N = Values.size(); i < N; ++i)
3039 // Size attribute value.
3040 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
3042 // Size the DIE children if any.
3043 if (!Children.empty()) {
3044 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
3045 "Children flag not set");
3047 for (unsigned j = 0, M = Children.size(); j < M; ++j)
3048 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
3050 // End of children marker.
3051 Offset += sizeof(int8_t);
3054 Die->setSize(Offset - Die->getOffset());
3058 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
3060 void DwarfDebug::computeSizeAndOffsets() {
3061 unsigned PrevOffset = 0;
3062 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3063 E = CUMap.end(); I != E; ++I) {
3064 // Compute size of compile unit header.
3065 static unsigned Offset = PrevOffset +
3066 sizeof(int32_t) + // Length of Compilation Unit Info
3067 sizeof(int16_t) + // DWARF version number
3068 sizeof(int32_t) + // Offset Into Abbrev. Section
3069 sizeof(int8_t); // Pointer Size (in bytes)
3070 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
3071 PrevOffset = Offset;
3075 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
3076 /// temporary label to it if SymbolStem is specified.
3077 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
3078 const char *SymbolStem = 0) {
3079 Asm->OutStreamer.SwitchSection(Section);
3080 if (!SymbolStem) return 0;
3082 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
3083 Asm->OutStreamer.EmitLabel(TmpSym);
3087 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
3088 /// the start of each one.
3089 void DwarfDebug::EmitSectionLabels() {
3090 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
3092 // Dwarf sections base addresses.
3093 if (Asm->MAI->doesDwarfRequireFrameSection()) {
3094 DwarfFrameSectionSym =
3095 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
3098 DwarfInfoSectionSym =
3099 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
3100 DwarfAbbrevSectionSym =
3101 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
3102 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
3104 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
3105 EmitSectionSym(Asm, MacroInfo);
3107 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
3108 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
3109 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
3110 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
3111 DwarfStrSectionSym =
3112 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
3113 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
3116 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
3117 "section_debug_loc");
3119 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
3120 EmitSectionSym(Asm, TLOF.getDataSection());
3123 /// emitDIE - Recusively Emits a debug information entry.
3125 void DwarfDebug::emitDIE(DIE *Die) {
3126 // Get the abbreviation for this DIE.
3127 unsigned AbbrevNumber = Die->getAbbrevNumber();
3128 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
3130 // Emit the code (index) for the abbreviation.
3131 if (Asm->isVerbose())
3132 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
3133 Twine::utohexstr(Die->getOffset()) + ":0x" +
3134 Twine::utohexstr(Die->getSize()) + " " +
3135 dwarf::TagString(Abbrev->getTag()));
3136 Asm->EmitULEB128(AbbrevNumber);
3138 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
3139 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
3141 // Emit the DIE attribute values.
3142 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3143 unsigned Attr = AbbrevData[i].getAttribute();
3144 unsigned Form = AbbrevData[i].getForm();
3145 assert(Form && "Too many attributes for DIE (check abbreviation)");
3147 if (Asm->isVerbose())
3148 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
3151 case dwarf::DW_AT_sibling:
3152 Asm->EmitInt32(Die->getSiblingOffset());
3154 case dwarf::DW_AT_abstract_origin: {
3155 DIEEntry *E = cast<DIEEntry>(Values[i]);
3156 DIE *Origin = E->getEntry();
3157 unsigned Addr = Origin->getOffset();
3158 Asm->EmitInt32(Addr);
3161 case dwarf::DW_AT_ranges: {
3162 // DW_AT_range Value encodes offset in debug_range section.
3163 DIEInteger *V = cast<DIEInteger>(Values[i]);
3165 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
3166 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
3170 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
3172 DwarfDebugRangeSectionSym,
3177 case dwarf::DW_AT_location: {
3178 if (UseDotDebugLocEntry.count(Die) != 0) {
3179 DIELabel *L = cast<DIELabel>(Values[i]);
3180 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
3182 Values[i]->EmitValue(Asm, Form);
3185 case dwarf::DW_AT_accessibility: {
3186 if (Asm->isVerbose()) {
3187 DIEInteger *V = cast<DIEInteger>(Values[i]);
3188 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
3190 Values[i]->EmitValue(Asm, Form);
3194 // Emit an attribute using the defined form.
3195 Values[i]->EmitValue(Asm, Form);
3200 // Emit the DIE children if any.
3201 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
3202 const std::vector<DIE *> &Children = Die->getChildren();
3204 for (unsigned j = 0, M = Children.size(); j < M; ++j)
3205 emitDIE(Children[j]);
3207 if (Asm->isVerbose())
3208 Asm->OutStreamer.AddComment("End Of Children Mark");
3213 /// emitDebugInfo - Emit the debug info section.
3215 void DwarfDebug::emitDebugInfo() {
3216 // Start debug info section.
3217 Asm->OutStreamer.SwitchSection(
3218 Asm->getObjFileLowering().getDwarfInfoSection());
3219 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3220 E = CUMap.end(); I != E; ++I) {
3221 CompileUnit *TheCU = I->second;
3222 DIE *Die = TheCU->getCUDie();
3224 // Emit the compile units header.
3225 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
3228 // Emit size of content not including length itself
3229 unsigned ContentSize = Die->getSize() +
3230 sizeof(int16_t) + // DWARF version number
3231 sizeof(int32_t) + // Offset Into Abbrev. Section
3232 sizeof(int8_t) + // Pointer Size (in bytes)
3233 sizeof(int32_t); // FIXME - extra pad for gdb bug.
3235 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
3236 Asm->EmitInt32(ContentSize);
3237 Asm->OutStreamer.AddComment("DWARF version number");
3238 Asm->EmitInt16(dwarf::DWARF_VERSION);
3239 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
3240 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
3241 DwarfAbbrevSectionSym);
3242 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3243 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3246 // FIXME - extra padding for gdb bug.
3247 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
3252 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
3256 /// emitAbbreviations - Emit the abbreviation section.
3258 void DwarfDebug::emitAbbreviations() const {
3259 // Check to see if it is worth the effort.
3260 if (!Abbreviations.empty()) {
3261 // Start the debug abbrev section.
3262 Asm->OutStreamer.SwitchSection(
3263 Asm->getObjFileLowering().getDwarfAbbrevSection());
3265 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
3267 // For each abbrevation.
3268 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3269 // Get abbreviation data
3270 const DIEAbbrev *Abbrev = Abbreviations[i];
3272 // Emit the abbrevations code (base 1 index.)
3273 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
3275 // Emit the abbreviations data.
3279 // Mark end of abbreviations.
3280 Asm->EmitULEB128(0, "EOM(3)");
3282 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
3286 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
3287 /// the line matrix.
3289 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
3290 // Define last address of section.
3291 Asm->OutStreamer.AddComment("Extended Op");
3294 Asm->OutStreamer.AddComment("Op size");
3295 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3296 Asm->OutStreamer.AddComment("DW_LNE_set_address");
3297 Asm->EmitInt8(dwarf::DW_LNE_set_address);
3299 Asm->OutStreamer.AddComment("Section end label");
3301 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
3302 Asm->getTargetData().getPointerSize(),
3305 // Mark end of matrix.
3306 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
3312 /// emitDebugLines - Emit source line information.
3314 void DwarfDebug::emitDebugLines() {
3315 // If the target is using .loc/.file, the assembler will be emitting the
3316 // .debug_line table automatically.
3317 if (Asm->MAI->hasDotLocAndDotFile())
3320 // Minimum line delta, thus ranging from -10..(255-10).
3321 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
3322 // Maximum line delta, thus ranging from -10..(255-10).
3323 const int MaxLineDelta = 255 + MinLineDelta;
3325 // Start the dwarf line section.
3326 Asm->OutStreamer.SwitchSection(
3327 Asm->getObjFileLowering().getDwarfLineSection());
3329 // Construct the section header.
3330 Asm->OutStreamer.AddComment("Length of Source Line Info");
3331 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
3332 Asm->GetTempSymbol("line_begin"), 4);
3333 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
3335 Asm->OutStreamer.AddComment("DWARF version number");
3336 Asm->EmitInt16(dwarf::DWARF_VERSION);
3338 Asm->OutStreamer.AddComment("Prolog Length");
3339 Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
3340 Asm->GetTempSymbol("line_prolog_begin"), 4);
3341 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
3343 Asm->OutStreamer.AddComment("Minimum Instruction Length");
3345 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
3347 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
3348 Asm->EmitInt8(MinLineDelta);
3349 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
3350 Asm->EmitInt8(MaxLineDelta);
3351 Asm->OutStreamer.AddComment("Special Opcode Base");
3352 Asm->EmitInt8(-MinLineDelta);
3354 // Line number standard opcode encodings argument count
3355 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
3357 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
3359 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
3361 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
3363 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
3365 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
3367 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
3369 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
3371 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
3374 // Emit directories.
3375 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
3376 const std::string &Dir = getSourceDirectoryName(DI);
3377 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
3378 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
3381 Asm->OutStreamer.AddComment("End of directories");
3385 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
3386 // Remember source id starts at 1.
3387 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
3388 const std::string &FN = getSourceFileName(Id.second);
3389 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
3390 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
3392 Asm->EmitULEB128(Id.first, "Directory #");
3393 Asm->EmitULEB128(0, "Mod date");
3394 Asm->EmitULEB128(0, "File size");
3397 Asm->OutStreamer.AddComment("End of files");
3400 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
3402 // A sequence for each text section.
3403 unsigned SecSrcLinesSize = SectionSourceLines.size();
3405 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3406 // Isolate current sections line info.
3407 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
3409 // Dwarf assumes we start with first line of first source file.
3410 unsigned Source = 1;
3413 // Construct rows of the address, source, line, column matrix.
3414 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3415 const SrcLineInfo &LineInfo = LineInfos[i];
3416 MCSymbol *Label = LineInfo.getLabel();
3417 if (!Label->isDefined()) continue; // Not emitted, in dead code.
3419 if (Asm->isVerbose()) {
3420 std::pair<unsigned, unsigned> SrcID =
3421 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
3422 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
3424 Twine(getSourceFileName(SrcID.second)) +
3425 ":" + Twine(LineInfo.getLine()));
3428 // Define the line address.
3429 Asm->OutStreamer.AddComment("Extended Op");
3431 Asm->OutStreamer.AddComment("Op size");
3432 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3434 Asm->OutStreamer.AddComment("DW_LNE_set_address");
3435 Asm->EmitInt8(dwarf::DW_LNE_set_address);
3437 Asm->OutStreamer.AddComment("Location label");
3438 Asm->OutStreamer.EmitSymbolValue(Label,
3439 Asm->getTargetData().getPointerSize(),
3442 // If change of source, then switch to the new source.
3443 if (Source != LineInfo.getSourceID()) {
3444 Source = LineInfo.getSourceID();
3445 Asm->OutStreamer.AddComment("DW_LNS_set_file");
3446 Asm->EmitInt8(dwarf::DW_LNS_set_file);
3447 Asm->EmitULEB128(Source, "New Source");
3450 // If change of line.
3451 if (Line != LineInfo.getLine()) {
3452 // Determine offset.
3453 int Offset = LineInfo.getLine() - Line;
3454 int Delta = Offset - MinLineDelta;
3457 Line = LineInfo.getLine();
3459 // If delta is small enough and in range...
3460 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3461 // ... then use fast opcode.
3462 Asm->OutStreamer.AddComment("Line Delta");
3463 Asm->EmitInt8(Delta - MinLineDelta);
3465 // ... otherwise use long hand.
3466 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
3467 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
3468 Asm->EmitSLEB128(Offset, "Line Offset");
3469 Asm->OutStreamer.AddComment("DW_LNS_copy");
3470 Asm->EmitInt8(dwarf::DW_LNS_copy);
3473 // Copy the previous row (different address or source)
3474 Asm->OutStreamer.AddComment("DW_LNS_copy");
3475 Asm->EmitInt8(dwarf::DW_LNS_copy);
3479 emitEndOfLineMatrix(j + 1);
3482 if (SecSrcLinesSize == 0)
3483 // Because we're emitting a debug_line section, we still need a line
3484 // table. The linker and friends expect it to exist. If there's nothing to
3485 // put into it, emit an empty table.
3486 emitEndOfLineMatrix(1);
3488 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3491 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3493 void DwarfDebug::emitCommonDebugFrame() {
3494 if (!Asm->MAI->doesDwarfRequireFrameSection())
3497 int stackGrowth = Asm->getTargetData().getPointerSize();
3498 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3499 TargetFrameInfo::StackGrowsDown)
3502 // Start the dwarf frame section.
3503 Asm->OutStreamer.SwitchSection(
3504 Asm->getObjFileLowering().getDwarfFrameSection());
3506 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3507 Asm->OutStreamer.AddComment("Length of Common Information Entry");
3508 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3509 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3511 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3512 Asm->OutStreamer.AddComment("CIE Identifier Tag");
3513 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3514 Asm->OutStreamer.AddComment("CIE Version");
3515 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3516 Asm->OutStreamer.AddComment("CIE Augmentation");
3517 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3518 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3519 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3520 Asm->OutStreamer.AddComment("CIE RA Column");
3521 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3522 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3524 std::vector<MachineMove> Moves;
3525 RI->getInitialFrameState(Moves);
3527 Asm->EmitFrameMoves(Moves, 0, false);
3529 Asm->EmitAlignment(2);
3530 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3533 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3536 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3537 if (!Asm->MAI->doesDwarfRequireFrameSection())
3540 // Start the dwarf frame section.
3541 Asm->OutStreamer.SwitchSection(
3542 Asm->getObjFileLowering().getDwarfFrameSection());
3544 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3545 MCSymbol *DebugFrameBegin =
3546 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3547 MCSymbol *DebugFrameEnd =
3548 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3549 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3551 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3553 Asm->OutStreamer.AddComment("FDE CIE offset");
3554 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
3555 DwarfFrameSectionSym);
3557 Asm->OutStreamer.AddComment("FDE initial location");
3558 MCSymbol *FuncBeginSym =
3559 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3560 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3561 Asm->getTargetData().getPointerSize(),
3565 Asm->OutStreamer.AddComment("FDE address range");
3566 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3567 FuncBeginSym, Asm->getTargetData().getPointerSize());
3569 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3571 Asm->EmitAlignment(2);
3572 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3575 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3577 void DwarfDebug::emitDebugPubNames() {
3578 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3579 E = CUMap.end(); I != E; ++I) {
3580 CompileUnit *TheCU = I->second;
3581 // Start the dwarf pubnames section.
3582 Asm->OutStreamer.SwitchSection(
3583 Asm->getObjFileLowering().getDwarfPubNamesSection());
3585 Asm->OutStreamer.AddComment("Length of Public Names Info");
3586 Asm->EmitLabelDifference(
3587 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
3588 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
3590 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3593 Asm->OutStreamer.AddComment("DWARF Version");
3594 Asm->EmitInt16(dwarf::DWARF_VERSION);
3596 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3597 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3598 DwarfInfoSectionSym);
3600 Asm->OutStreamer.AddComment("Compilation Unit Length");
3601 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3602 Asm->GetTempSymbol("info_begin", TheCU->getID()),
3605 const StringMap<DIE*> &Globals = TheCU->getGlobals();
3606 for (StringMap<DIE*>::const_iterator
3607 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3608 const char *Name = GI->getKeyData();
3609 DIE *Entity = GI->second;
3611 Asm->OutStreamer.AddComment("DIE offset");
3612 Asm->EmitInt32(Entity->getOffset());
3614 if (Asm->isVerbose())
3615 Asm->OutStreamer.AddComment("External Name");
3616 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3619 Asm->OutStreamer.AddComment("End Mark");
3621 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3626 void DwarfDebug::emitDebugPubTypes() {
3627 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3628 E = CUMap.end(); I != E; ++I) {
3629 CompileUnit *TheCU = I->second;
3630 // Start the dwarf pubnames section.
3631 Asm->OutStreamer.SwitchSection(
3632 Asm->getObjFileLowering().getDwarfPubTypesSection());
3633 Asm->OutStreamer.AddComment("Length of Public Types Info");
3634 Asm->EmitLabelDifference(
3635 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
3636 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
3638 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3641 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3642 Asm->EmitInt16(dwarf::DWARF_VERSION);
3644 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3645 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3646 DwarfInfoSectionSym);
3648 Asm->OutStreamer.AddComment("Compilation Unit Length");
3649 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3650 Asm->GetTempSymbol("info_begin", TheCU->getID()),
3653 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
3654 for (StringMap<DIE*>::const_iterator
3655 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3656 const char *Name = GI->getKeyData();
3657 DIE * Entity = GI->second;
3659 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3660 Asm->EmitInt32(Entity->getOffset());
3662 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3663 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3666 Asm->OutStreamer.AddComment("End Mark");
3668 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3673 /// emitDebugStr - Emit visible names into a debug str section.
3675 void DwarfDebug::emitDebugStr() {
3676 // Check to see if it is worth the effort.
3677 if (StringPool.empty()) return;
3679 // Start the dwarf str section.
3680 Asm->OutStreamer.SwitchSection(
3681 Asm->getObjFileLowering().getDwarfStrSection());
3683 // Get all of the string pool entries and put them in an array by their ID so
3684 // we can sort them.
3685 SmallVector<std::pair<unsigned,
3686 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3688 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3689 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3690 Entries.push_back(std::make_pair(I->second.second, &*I));
3692 array_pod_sort(Entries.begin(), Entries.end());
3694 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3695 // Emit a label for reference from debug information entries.
3696 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3698 // Emit the string itself.
3699 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3703 /// emitDebugLoc - Emit visible names into a debug loc section.
3705 void DwarfDebug::emitDebugLoc() {
3706 if (DotDebugLocEntries.empty())
3709 // Start the dwarf loc section.
3710 Asm->OutStreamer.SwitchSection(
3711 Asm->getObjFileLowering().getDwarfLocSection());
3712 unsigned char Size = Asm->getTargetData().getPointerSize();
3713 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
3715 for (SmallVector<DotDebugLocEntry, 4>::iterator
3716 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
3717 I != E; ++I, ++index) {
3718 DotDebugLocEntry Entry = *I;
3719 if (Entry.isEmpty()) {
3720 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3721 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3722 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
3724 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
3725 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
3726 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3727 unsigned Reg = RI->getDwarfRegNum(Entry.Loc.getReg(), false);
3728 if (int Offset = Entry.Loc.getOffset()) {
3729 // If the value is at a certain offset from frame register then
3731 unsigned OffsetSize = Offset ? MCAsmInfo::getSLEB128Size(Offset) : 1;
3732 Asm->OutStreamer.AddComment("Loc expr size");
3733 Asm->EmitInt16(1 + OffsetSize);
3734 Asm->OutStreamer.AddComment(
3735 dwarf::OperationEncodingString(dwarf::DW_OP_fbreg));
3736 Asm->EmitInt8(dwarf::DW_OP_fbreg);
3737 Asm->OutStreamer.AddComment("Offset");
3738 Asm->EmitSLEB128(Offset);
3741 Asm->OutStreamer.AddComment("Loc expr size");
3743 Asm->OutStreamer.AddComment(
3744 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
3745 Asm->EmitInt8(dwarf::DW_OP_reg0 + Reg);
3747 Asm->OutStreamer.AddComment("Loc expr size");
3748 Asm->EmitInt16(1 + MCAsmInfo::getULEB128Size(Reg));
3749 Asm->EmitInt8(dwarf::DW_OP_regx);
3750 Asm->EmitULEB128(Reg);
3757 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3759 void DwarfDebug::EmitDebugARanges() {
3760 // Start the dwarf aranges section.
3761 Asm->OutStreamer.SwitchSection(
3762 Asm->getObjFileLowering().getDwarfARangesSection());
3765 /// emitDebugRanges - Emit visible names into a debug ranges section.
3767 void DwarfDebug::emitDebugRanges() {
3768 // Start the dwarf ranges section.
3769 Asm->OutStreamer.SwitchSection(
3770 Asm->getObjFileLowering().getDwarfRangesSection());
3771 unsigned char Size = Asm->getTargetData().getPointerSize();
3772 for (SmallVector<const MCSymbol *, 8>::iterator
3773 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
3776 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3778 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3782 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3784 void DwarfDebug::emitDebugMacInfo() {
3785 if (const MCSection *LineInfo =
3786 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3787 // Start the dwarf macinfo section.
3788 Asm->OutStreamer.SwitchSection(LineInfo);
3792 /// emitDebugInlineInfo - Emit inline info using following format.
3794 /// 1. length of section
3795 /// 2. Dwarf version number
3796 /// 3. address size.
3798 /// Entries (one "entry" for each function that was inlined):
3800 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3801 /// otherwise offset into __debug_str for regular function name.
3802 /// 2. offset into __debug_str section for regular function name.
3803 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3804 /// instances for the function.
3806 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3807 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3808 /// __debug_info section, and the low_pc is the starting address for the
3809 /// inlining instance.
3810 void DwarfDebug::emitDebugInlineInfo() {
3811 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3817 Asm->OutStreamer.SwitchSection(
3818 Asm->getObjFileLowering().getDwarfDebugInlineSection());
3820 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3821 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3822 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3824 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3826 Asm->OutStreamer.AddComment("Dwarf Version");
3827 Asm->EmitInt16(dwarf::DWARF_VERSION);
3828 Asm->OutStreamer.AddComment("Address Size (in bytes)");
3829 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3831 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3832 E = InlinedSPNodes.end(); I != E; ++I) {
3834 const MDNode *Node = *I;
3835 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3836 = InlineInfo.find(Node);
3837 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3838 DISubprogram SP(Node);
3839 StringRef LName = SP.getLinkageName();
3840 StringRef Name = SP.getName();
3842 Asm->OutStreamer.AddComment("MIPS linkage name");
3843 if (LName.empty()) {
3844 Asm->OutStreamer.EmitBytes(Name, 0);
3845 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3847 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3848 DwarfStrSectionSym);
3850 Asm->OutStreamer.AddComment("Function name");
3851 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3852 Asm->EmitULEB128(Labels.size(), "Inline count");
3854 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3855 LE = Labels.end(); LI != LE; ++LI) {
3856 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3857 Asm->EmitInt32(LI->second->getOffset());
3859 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3860 Asm->OutStreamer.EmitSymbolValue(LI->first,
3861 Asm->getTargetData().getPointerSize(),0);
3865 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));