1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
13 #define DEBUG_TYPE "dwarfdebug"
14 #include "DwarfDebug.h"
15 #include "llvm/Module.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetFrameInfo.h"
23 #include "llvm/Target/TargetLoweringObjectFile.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Support/Timer.h"
30 #include "llvm/System/Path.h"
33 static TimerGroup &getDwarfTimerGroup() {
34 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
35 return DwarfTimerGroup;
38 //===----------------------------------------------------------------------===//
40 /// Configuration values for initial hash set sizes (log2).
42 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
46 //===----------------------------------------------------------------------===//
47 /// CompileUnit - This dwarf writer support class manages information associate
48 /// with a source file.
50 /// ID - File identifier for source.
54 /// Die - Compile unit debug information entry.
58 /// IndexTyDie - An anonymous type for index type.
61 /// GVToDieMap - Tracks the mapping of unit level debug informaton
62 /// variables to debug information entries.
63 /// FIXME : Rename GVToDieMap -> NodeToDieMap
64 ValueMap<MDNode *, DIE *> GVToDieMap;
66 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
67 /// descriptors to debug information entries using a DIEEntry proxy.
69 ValueMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
71 /// Globals - A map of globally visible named entities for this unit.
73 StringMap<DIE*> Globals;
76 CompileUnit(unsigned I, DIE *D)
77 : ID(I), CUDie(D), IndexTyDie(0) {}
78 ~CompileUnit() { delete CUDie; delete IndexTyDie; }
81 unsigned getID() const { return ID; }
82 DIE* getCUDie() const { return CUDie; }
83 StringMap<DIE*> &getGlobals() { return Globals; }
85 /// hasContent - Return true if this compile unit has something to write out.
87 bool hasContent() const { return !CUDie->getChildren().empty(); }
89 /// addGlobal - Add a new global entity to the compile unit.
91 void addGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
93 /// getDIE - Returns the debug information entry map slot for the
94 /// specified debug variable.
95 DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
97 /// insertDIE - Insert DIE into the map.
98 void insertDIE(MDNode *N, DIE *D) {
99 GVToDieMap.insert(std::make_pair(N, D));
102 /// getDIEEntry - Returns the debug information entry for the speciefied
104 DIEEntry *getDIEEntry(MDNode *N) { return GVToDIEEntryMap.lookup(N); }
106 /// insertDIEEntry - Insert debug information entry into the map.
107 void insertDIEEntry(MDNode *N, DIEEntry *E) {
108 GVToDIEEntryMap.insert(std::make_pair(N, E));
111 /// addDie - Adds or interns the DIE to the compile unit.
113 void addDie(DIE *Buffer) {
114 this->CUDie->addChild(Buffer);
117 // getIndexTyDie - Get an anonymous type for index type.
118 DIE *getIndexTyDie() {
122 // setIndexTyDie - Set D as anonymous type for index which can be reused later.
123 void setIndexTyDie(DIE *D) {
129 //===----------------------------------------------------------------------===//
130 /// DbgVariable - This class is used to track local variable information.
133 DIVariable Var; // Variable Descriptor.
134 unsigned FrameIndex; // Variable frame index.
135 DbgVariable *AbstractVar; // Abstract variable for this variable.
138 DbgVariable(DIVariable V, unsigned I)
139 : Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0) {}
142 DIVariable getVariable() const { return Var; }
143 unsigned getFrameIndex() const { return FrameIndex; }
144 void setAbstractVariable(DbgVariable *V) { AbstractVar = V; }
145 DbgVariable *getAbstractVariable() const { return AbstractVar; }
146 void setDIE(DIE *D) { TheDIE = D; }
147 DIE *getDIE() const { return TheDIE; }
150 //===----------------------------------------------------------------------===//
151 /// DbgScope - This class is used to track scope information.
154 DbgScope *Parent; // Parent to this scope.
155 DIDescriptor Desc; // Debug info descriptor for scope.
156 WeakVH InlinedAtLocation; // Location at which scope is inlined.
157 bool AbstractScope; // Abstract Scope
158 unsigned StartLabelID; // Label ID of the beginning of scope.
159 unsigned EndLabelID; // Label ID of the end of scope.
160 const MachineInstr *LastInsn; // Last instruction of this scope.
161 const MachineInstr *FirstInsn; // First instruction of this scope.
162 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
163 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
165 // Private state for dump()
166 mutable unsigned IndentLevel;
168 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
169 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
170 StartLabelID(0), EndLabelID(0),
171 LastInsn(0), FirstInsn(0), IndentLevel(0) {}
175 DbgScope *getParent() const { return Parent; }
176 void setParent(DbgScope *P) { Parent = P; }
177 DIDescriptor getDesc() const { return Desc; }
178 MDNode *getInlinedAt() const {
179 return dyn_cast_or_null<MDNode>(InlinedAtLocation);
181 MDNode *getScopeNode() const { return Desc.getNode(); }
182 unsigned getStartLabelID() const { return StartLabelID; }
183 unsigned getEndLabelID() const { return EndLabelID; }
184 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
185 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
186 void setStartLabelID(unsigned S) { StartLabelID = S; }
187 void setEndLabelID(unsigned E) { EndLabelID = E; }
188 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
189 const MachineInstr *getLastInsn() { return LastInsn; }
190 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
191 void setAbstractScope() { AbstractScope = true; }
192 bool isAbstractScope() const { return AbstractScope; }
193 const MachineInstr *getFirstInsn() { return FirstInsn; }
195 /// addScope - Add a scope to the scope.
197 void addScope(DbgScope *S) { Scopes.push_back(S); }
199 /// addVariable - Add a variable to the scope.
201 void addVariable(DbgVariable *V) { Variables.push_back(V); }
203 void fixInstructionMarkers() {
204 assert (getFirstInsn() && "First instruction is missing!");
208 // If a scope does not have an instruction to mark an end then use
209 // the end of last child scope.
210 SmallVector<DbgScope *, 4> &Scopes = getScopes();
211 assert (!Scopes.empty() && "Inner most scope does not have last insn!");
212 DbgScope *L = Scopes.back();
213 if (!L->getLastInsn())
214 L->fixInstructionMarkers();
215 setLastInsn(L->getLastInsn());
224 void DbgScope::dump() const {
225 raw_ostream &err = errs();
226 err.indent(IndentLevel);
227 MDNode *N = Desc.getNode();
229 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
231 err << "Abstract Scope\n";
235 err << "Children ...\n";
236 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
237 if (Scopes[i] != this)
244 DbgScope::~DbgScope() {
245 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
247 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
251 } // end llvm namespace
253 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
254 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
255 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
256 DIEValues(), StringPool(),
257 SectionSourceLines(), didInitial(false), shouldEmit(false),
258 CurrentFnDbgScope(0), DebugTimer(0) {
259 if (TimePassesIsEnabled)
260 DebugTimer = new Timer("Dwarf Debug Writer",
261 getDwarfTimerGroup());
263 DwarfDebug::~DwarfDebug() {
264 for (unsigned j = 0, M = DIEValues.size(); j < M; ++j)
270 /// assignAbbrevNumber - Define a unique number for the abbreviation.
272 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
273 // Profile the node so that we can make it unique.
277 // Check the set for priors.
278 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
280 // If it's newly added.
281 if (InSet == &Abbrev) {
282 // Add to abbreviation list.
283 Abbreviations.push_back(&Abbrev);
285 // Assign the vector position + 1 as its number.
286 Abbrev.setNumber(Abbreviations.size());
288 // Assign existing abbreviation number.
289 Abbrev.setNumber(InSet->getNumber());
293 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
294 /// information entry.
295 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
296 DIEEntry *Value = new DIEEntry(Entry);
297 DIEValues.push_back(Value);
301 /// addUInt - Add an unsigned integer attribute data and value.
303 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
304 unsigned Form, uint64_t Integer) {
305 if (!Form) Form = DIEInteger::BestForm(false, Integer);
306 DIEValue *Value = new DIEInteger(Integer);
307 DIEValues.push_back(Value);
308 Die->addValue(Attribute, Form, Value);
311 /// addSInt - Add an signed integer attribute data and value.
313 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
314 unsigned Form, int64_t Integer) {
315 if (!Form) Form = DIEInteger::BestForm(true, Integer);
316 DIEValue *Value = new DIEInteger(Integer);
317 DIEValues.push_back(Value);
318 Die->addValue(Attribute, Form, Value);
321 /// addString - Add a string attribute data and value.
323 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
324 const std::string &String) {
325 DIEValue *Value = new DIEString(String);
326 DIEValues.push_back(Value);
327 Die->addValue(Attribute, Form, Value);
330 /// addLabel - Add a Dwarf label attribute data and value.
332 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
333 const DWLabel &Label) {
334 DIEValue *Value = new DIEDwarfLabel(Label);
335 DIEValues.push_back(Value);
336 Die->addValue(Attribute, Form, Value);
339 /// addObjectLabel - Add an non-Dwarf label attribute data and value.
341 void DwarfDebug::addObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
342 const std::string &Label) {
343 DIEValue *Value = new DIEObjectLabel(Label);
344 DIEValues.push_back(Value);
345 Die->addValue(Attribute, Form, Value);
348 /// addSectionOffset - Add a section offset label attribute data and value.
350 void DwarfDebug::addSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
351 const DWLabel &Label, const DWLabel &Section,
352 bool isEH, bool useSet) {
353 DIEValue *Value = new DIESectionOffset(Label, Section, isEH, useSet);
354 DIEValues.push_back(Value);
355 Die->addValue(Attribute, Form, Value);
358 /// addDelta - Add a label delta attribute data and value.
360 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
361 const DWLabel &Hi, const DWLabel &Lo) {
362 DIEValue *Value = new DIEDelta(Hi, Lo);
363 DIEValues.push_back(Value);
364 Die->addValue(Attribute, Form, Value);
367 /// addBlock - Add block data.
369 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
371 Block->ComputeSize(TD);
372 DIEValues.push_back(Block);
373 Die->addValue(Attribute, Block->BestForm(), Block);
376 /// addSourceLine - Add location information to specified debug information
378 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
379 // If there is no compile unit specified, don't add a line #.
380 if (V->getCompileUnit().isNull())
383 unsigned Line = V->getLineNumber();
384 unsigned FileID = findCompileUnit(V->getCompileUnit()).getID();
385 assert(FileID && "Invalid file id");
386 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
387 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
390 /// addSourceLine - Add location information to specified debug information
392 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
393 // If there is no compile unit specified, don't add a line #.
394 if (G->getCompileUnit().isNull())
397 unsigned Line = G->getLineNumber();
398 unsigned FileID = findCompileUnit(G->getCompileUnit()).getID();
399 assert(FileID && "Invalid file id");
400 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
401 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
404 /// addSourceLine - Add location information to specified debug information
406 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
407 // If there is no compile unit specified, don't add a line #.
408 if (SP->getCompileUnit().isNull())
410 // If the line number is 0, don't add it.
411 if (SP->getLineNumber() == 0)
415 unsigned Line = SP->getLineNumber();
416 unsigned FileID = findCompileUnit(SP->getCompileUnit()).getID();
417 assert(FileID && "Invalid file id");
418 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
419 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
422 /// addSourceLine - Add location information to specified debug information
424 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
425 // If there is no compile unit specified, don't add a line #.
426 DICompileUnit CU = Ty->getCompileUnit();
430 unsigned Line = Ty->getLineNumber();
431 unsigned FileID = findCompileUnit(CU).getID();
432 assert(FileID && "Invalid file id");
433 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
434 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
437 /* Byref variables, in Blocks, are declared by the programmer as
438 "SomeType VarName;", but the compiler creates a
439 __Block_byref_x_VarName struct, and gives the variable VarName
440 either the struct, or a pointer to the struct, as its type. This
441 is necessary for various behind-the-scenes things the compiler
442 needs to do with by-reference variables in blocks.
444 However, as far as the original *programmer* is concerned, the
445 variable should still have type 'SomeType', as originally declared.
447 The following function dives into the __Block_byref_x_VarName
448 struct to find the original type of the variable. This will be
449 passed back to the code generating the type for the Debug
450 Information Entry for the variable 'VarName'. 'VarName' will then
451 have the original type 'SomeType' in its debug information.
453 The original type 'SomeType' will be the type of the field named
454 'VarName' inside the __Block_byref_x_VarName struct.
456 NOTE: In order for this to not completely fail on the debugger
457 side, the Debug Information Entry for the variable VarName needs to
458 have a DW_AT_location that tells the debugger how to unwind through
459 the pointers and __Block_byref_x_VarName struct to find the actual
460 value of the variable. The function addBlockByrefType does this. */
462 /// Find the type the programmer originally declared the variable to be
463 /// and return that type.
465 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
468 unsigned tag = Ty.getTag();
470 if (tag == dwarf::DW_TAG_pointer_type) {
471 DIDerivedType DTy = DIDerivedType(Ty.getNode());
472 subType = DTy.getTypeDerivedFrom();
475 DICompositeType blockStruct = DICompositeType(subType.getNode());
477 DIArray Elements = blockStruct.getTypeArray();
479 if (Elements.isNull())
482 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
483 DIDescriptor Element = Elements.getElement(i);
484 DIDerivedType DT = DIDerivedType(Element.getNode());
485 if (strcmp(Name.c_str(), DT.getName()) == 0)
486 return (DT.getTypeDerivedFrom());
492 /// addComplexAddress - Start with the address based on the location provided,
493 /// and generate the DWARF information necessary to find the actual variable
494 /// given the extra address information encoded in the DIVariable, starting from
495 /// the starting location. Add the DWARF information to the die.
497 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
499 const MachineLocation &Location) {
500 const DIVariable &VD = DV->getVariable();
501 DIType Ty = VD.getType();
503 // Decode the original location, and use that as the start of the byref
504 // variable's location.
505 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
506 DIEBlock *Block = new DIEBlock();
508 if (Location.isReg()) {
510 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
512 Reg = Reg - dwarf::DW_OP_reg0;
513 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
514 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
518 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
520 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
521 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
524 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
527 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
528 uint64_t Element = VD.getAddrElement(i);
530 if (Element == DIFactory::OpPlus) {
531 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
532 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
533 } else if (Element == DIFactory::OpDeref) {
534 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
535 } else llvm_unreachable("unknown DIFactory Opcode");
538 // Now attach the location information to the DIE.
539 addBlock(Die, Attribute, 0, Block);
542 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
543 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
544 gives the variable VarName either the struct, or a pointer to the struct, as
545 its type. This is necessary for various behind-the-scenes things the
546 compiler needs to do with by-reference variables in Blocks.
548 However, as far as the original *programmer* is concerned, the variable
549 should still have type 'SomeType', as originally declared.
551 The function getBlockByrefType dives into the __Block_byref_x_VarName
552 struct to find the original type of the variable, which is then assigned to
553 the variable's Debug Information Entry as its real type. So far, so good.
554 However now the debugger will expect the variable VarName to have the type
555 SomeType. So we need the location attribute for the variable to be an
556 expression that explains to the debugger how to navigate through the
557 pointers and struct to find the actual variable of type SomeType.
559 The following function does just that. We start by getting
560 the "normal" location for the variable. This will be the location
561 of either the struct __Block_byref_x_VarName or the pointer to the
562 struct __Block_byref_x_VarName.
564 The struct will look something like:
566 struct __Block_byref_x_VarName {
568 struct __Block_byref_x_VarName *forwarding;
569 ... <various other fields>
571 ... <maybe more fields>
574 If we are given the struct directly (as our starting point) we
575 need to tell the debugger to:
577 1). Add the offset of the forwarding field.
579 2). Follow that pointer to get the the real __Block_byref_x_VarName
580 struct to use (the real one may have been copied onto the heap).
582 3). Add the offset for the field VarName, to find the actual variable.
584 If we started with a pointer to the struct, then we need to
585 dereference that pointer first, before the other steps.
586 Translating this into DWARF ops, we will need to append the following
587 to the current location description for the variable:
589 DW_OP_deref -- optional, if we start with a pointer
590 DW_OP_plus_uconst <forward_fld_offset>
592 DW_OP_plus_uconst <varName_fld_offset>
594 That is what this function does. */
596 /// addBlockByrefAddress - Start with the address based on the location
597 /// provided, and generate the DWARF information necessary to find the
598 /// actual Block variable (navigating the Block struct) based on the
599 /// starting location. Add the DWARF information to the die. For
600 /// more information, read large comment just above here.
602 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
604 const MachineLocation &Location) {
605 const DIVariable &VD = DV->getVariable();
606 DIType Ty = VD.getType();
608 unsigned Tag = Ty.getTag();
609 bool isPointer = false;
611 const char *varName = VD.getName();
613 if (Tag == dwarf::DW_TAG_pointer_type) {
614 DIDerivedType DTy = DIDerivedType(Ty.getNode());
615 TmpTy = DTy.getTypeDerivedFrom();
619 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
621 // Find the __forwarding field and the variable field in the __Block_byref
623 DIArray Fields = blockStruct.getTypeArray();
624 DIDescriptor varField = DIDescriptor();
625 DIDescriptor forwardingField = DIDescriptor();
628 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
629 DIDescriptor Element = Fields.getElement(i);
630 DIDerivedType DT = DIDerivedType(Element.getNode());
631 const char *fieldName = DT.getName();
632 if (strcmp(fieldName, "__forwarding") == 0)
633 forwardingField = Element;
634 else if (strcmp(fieldName, varName) == 0)
638 assert(!varField.isNull() && "Can't find byref variable in Block struct");
639 assert(!forwardingField.isNull()
640 && "Can't find forwarding field in Block struct");
642 // Get the offsets for the forwarding field and the variable field.
643 unsigned int forwardingFieldOffset =
644 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
645 unsigned int varFieldOffset =
646 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
648 // Decode the original location, and use that as the start of the byref
649 // variable's location.
650 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
651 DIEBlock *Block = new DIEBlock();
653 if (Location.isReg()) {
655 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
657 Reg = Reg - dwarf::DW_OP_reg0;
658 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
659 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
663 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
665 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
666 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
669 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
672 // If we started with a pointer to the __Block_byref... struct, then
673 // the first thing we need to do is dereference the pointer (DW_OP_deref).
675 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
677 // Next add the offset for the '__forwarding' field:
678 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
679 // adding the offset if it's 0.
680 if (forwardingFieldOffset > 0) {
681 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
682 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
685 // Now dereference the __forwarding field to get to the real __Block_byref
686 // struct: DW_OP_deref.
687 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
689 // Now that we've got the real __Block_byref... struct, add the offset
690 // for the variable's field to get to the location of the actual variable:
691 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
692 if (varFieldOffset > 0) {
693 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
694 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
697 // Now attach the location information to the DIE.
698 addBlock(Die, Attribute, 0, Block);
701 /// addAddress - Add an address attribute to a die based on the location
703 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
704 const MachineLocation &Location) {
705 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
706 DIEBlock *Block = new DIEBlock();
708 if (Location.isReg()) {
710 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
712 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
713 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
717 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
719 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
720 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
723 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
726 addBlock(Die, Attribute, 0, Block);
729 /// addType - Add a new type attribute to the specified entity.
730 void DwarfDebug::addType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
734 // Check for pre-existence.
735 DIEEntry *Entry = DW_Unit->getDIEEntry(Ty.getNode());
737 // If it exists then use the existing value.
739 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
744 Entry = createDIEEntry();
745 DW_Unit->insertDIEEntry(Ty.getNode(), Entry);
748 DIE *Buffer = new DIE(dwarf::DW_TAG_base_type);
749 if (Ty.isBasicType())
750 constructTypeDIE(DW_Unit, *Buffer, DIBasicType(Ty.getNode()));
751 else if (Ty.isCompositeType())
752 constructTypeDIE(DW_Unit, *Buffer, DICompositeType(Ty.getNode()));
754 assert(Ty.isDerivedType() && "Unknown kind of DIType");
755 constructTypeDIE(DW_Unit, *Buffer, DIDerivedType(Ty.getNode()));
758 // Add debug information entry to entity and appropriate context.
760 DIDescriptor Context = Ty.getContext();
761 if (!Context.isNull())
762 Die = DW_Unit->getDIE(Context.getNode());
765 Die->addChild(Buffer);
767 DW_Unit->addDie(Buffer);
768 Entry->setEntry(Buffer);
769 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
772 /// constructTypeDIE - Construct basic type die from DIBasicType.
773 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
775 // Get core information.
776 const char *Name = BTy.getName();
777 Buffer.setTag(dwarf::DW_TAG_base_type);
778 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
781 // Add name if not anonymous or intermediate type.
783 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
784 uint64_t Size = BTy.getSizeInBits() >> 3;
785 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
788 /// constructTypeDIE - Construct derived type die from DIDerivedType.
789 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
791 // Get core information.
792 const char *Name = DTy.getName();
793 uint64_t Size = DTy.getSizeInBits() >> 3;
794 unsigned Tag = DTy.getTag();
796 // FIXME - Workaround for templates.
797 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
801 // Map to main type, void will not have a type.
802 DIType FromTy = DTy.getTypeDerivedFrom();
803 addType(DW_Unit, &Buffer, FromTy);
805 // Add name if not anonymous or intermediate type.
806 if (Name && Tag != dwarf::DW_TAG_pointer_type)
807 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
809 // Add size if non-zero (derived types might be zero-sized.)
811 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
813 // Add source line info if available and TyDesc is not a forward declaration.
814 if (!DTy.isForwardDecl() && Tag != dwarf::DW_TAG_pointer_type)
815 addSourceLine(&Buffer, &DTy);
818 /// constructTypeDIE - Construct type DIE from DICompositeType.
819 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
820 DICompositeType CTy) {
821 // Get core information.
822 const char *Name = CTy.getName();
824 uint64_t Size = CTy.getSizeInBits() >> 3;
825 unsigned Tag = CTy.getTag();
829 case dwarf::DW_TAG_vector_type:
830 case dwarf::DW_TAG_array_type:
831 constructArrayTypeDIE(DW_Unit, Buffer, &CTy);
833 case dwarf::DW_TAG_enumeration_type: {
834 DIArray Elements = CTy.getTypeArray();
836 // Add enumerators to enumeration type.
837 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
839 DIEnumerator Enum(Elements.getElement(i).getNode());
840 if (!Enum.isNull()) {
841 ElemDie = constructEnumTypeDIE(DW_Unit, &Enum);
842 Buffer.addChild(ElemDie);
847 case dwarf::DW_TAG_subroutine_type: {
849 DIArray Elements = CTy.getTypeArray();
850 DIDescriptor RTy = Elements.getElement(0);
851 addType(DW_Unit, &Buffer, DIType(RTy.getNode()));
853 // Add prototype flag.
854 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
857 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
858 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
859 DIDescriptor Ty = Elements.getElement(i);
860 addType(DW_Unit, Arg, DIType(Ty.getNode()));
861 Buffer.addChild(Arg);
865 case dwarf::DW_TAG_structure_type:
866 case dwarf::DW_TAG_union_type:
867 case dwarf::DW_TAG_class_type: {
868 // Add elements to structure type.
869 DIArray Elements = CTy.getTypeArray();
871 // A forward struct declared type may not have elements available.
872 if (Elements.isNull())
875 // Add elements to structure type.
876 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
877 DIDescriptor Element = Elements.getElement(i);
878 if (Element.isNull())
881 if (Element.getTag() == dwarf::DW_TAG_subprogram)
882 ElemDie = createSubprogramDIE(DW_Unit,
883 DISubprogram(Element.getNode()));
885 ElemDie = createMemberDIE(DW_Unit,
886 DIDerivedType(Element.getNode()));
887 Buffer.addChild(ElemDie);
890 if (CTy.isAppleBlockExtension())
891 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
893 unsigned RLang = CTy.getRunTimeLang();
895 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
896 dwarf::DW_FORM_data1, RLang);
903 // Add name if not anonymous or intermediate type.
905 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
907 if (Tag == dwarf::DW_TAG_enumeration_type ||
908 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
909 // Add size if non-zero (derived types might be zero-sized.)
911 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
913 // Add zero size if it is not a forward declaration.
914 if (CTy.isForwardDecl())
915 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
917 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
920 // Add source line info if available.
921 if (!CTy.isForwardDecl())
922 addSourceLine(&Buffer, &CTy);
926 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
927 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
928 int64_t L = SR.getLo();
929 int64_t H = SR.getHi();
930 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
932 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
934 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
936 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
938 Buffer.addChild(DW_Subrange);
941 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
942 void DwarfDebug::constructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
943 DICompositeType *CTy) {
944 Buffer.setTag(dwarf::DW_TAG_array_type);
945 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
946 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
948 // Emit derived type.
949 addType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
950 DIArray Elements = CTy->getTypeArray();
952 // Get an anonymous type for index type.
953 DIE *IdxTy = DW_Unit->getIndexTyDie();
955 // Construct an anonymous type for index type.
956 IdxTy = new DIE(dwarf::DW_TAG_base_type);
957 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
958 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
959 dwarf::DW_ATE_signed);
960 DW_Unit->addDie(IdxTy);
961 DW_Unit->setIndexTyDie(IdxTy);
964 // Add subranges to array type.
965 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
966 DIDescriptor Element = Elements.getElement(i);
967 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
968 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
972 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
973 DIE *DwarfDebug::constructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
974 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
975 const char *Name = ETy->getName();
976 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
977 int64_t Value = ETy->getEnumValue();
978 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
982 /// createGlobalVariableDIE - Create new DIE using GV.
983 DIE *DwarfDebug::createGlobalVariableDIE(CompileUnit *DW_Unit,
984 const DIGlobalVariable &GV) {
985 // If the global variable was optmized out then no need to create debug info entry.
986 if (!GV.getGlobal()) return NULL;
987 if (!GV.getDisplayName()) return NULL;
989 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
990 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
991 GV.getDisplayName());
993 const char *LinkageName = GV.getLinkageName();
995 // Skip special LLVM prefix that is used to inform the asm printer to not
996 // emit usual symbol prefix before the symbol name. This happens for
997 // Objective-C symbol names and symbol whose name is replaced using GCC's
998 // __asm__ attribute.
999 if (LinkageName[0] == 1)
1000 LinkageName = &LinkageName[1];
1001 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1004 addType(DW_Unit, GVDie, GV.getType());
1005 if (!GV.isLocalToUnit())
1006 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1007 addSourceLine(GVDie, &GV);
1010 DIEBlock *Block = new DIEBlock();
1011 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1012 addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1013 Asm->Mang->getMangledName(GV.getGlobal()));
1014 addBlock(GVDie, dwarf::DW_AT_location, 0, Block);
1019 /// createMemberDIE - Create new member DIE.
1020 DIE *DwarfDebug::createMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
1021 DIE *MemberDie = new DIE(DT.getTag());
1022 if (const char *Name = DT.getName())
1023 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1025 addType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1027 addSourceLine(MemberDie, &DT);
1029 DIEBlock *MemLocationDie = new DIEBlock();
1030 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1032 uint64_t Size = DT.getSizeInBits();
1033 uint64_t FieldSize = DT.getOriginalTypeSize();
1035 if (Size != FieldSize) {
1037 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1038 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1040 uint64_t Offset = DT.getOffsetInBits();
1041 uint64_t FieldOffset = Offset;
1042 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1043 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1044 FieldOffset = (HiMark - FieldSize);
1045 Offset -= FieldOffset;
1047 // Maybe we need to work from the other end.
1048 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1049 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1051 // Here WD_AT_data_member_location points to the anonymous
1052 // field that includes this bit field.
1053 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1056 // This is not a bitfield.
1057 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1059 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1061 if (DT.isProtected())
1062 addUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1063 dwarf::DW_ACCESS_protected);
1064 else if (DT.isPrivate())
1065 addUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1066 dwarf::DW_ACCESS_private);
1071 /// createSubprogramDIE - Create new DIE using SP.
1072 DIE *DwarfDebug::createSubprogramDIE(CompileUnit *DW_Unit,
1073 const DISubprogram &SP,
1076 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1078 const char * Name = SP.getName();
1079 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1081 const char *LinkageName = SP.getLinkageName();
1083 // Skip special LLVM prefix that is used to inform the asm printer to not emit
1084 // usual symbol prefix before the symbol name. This happens for Objective-C
1085 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
1086 if (LinkageName[0] == 1)
1087 LinkageName = &LinkageName[1];
1088 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1091 addSourceLine(SPDie, &SP);
1093 DICompositeType SPTy = SP.getType();
1094 DIArray Args = SPTy.getTypeArray();
1096 // Add prototyped tag, if C or ObjC.
1097 unsigned Lang = SP.getCompileUnit().getLanguage();
1098 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1099 Lang == dwarf::DW_LANG_ObjC)
1100 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1103 unsigned SPTag = SPTy.getTag();
1104 if (!IsConstructor) {
1105 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1106 addType(DW_Unit, SPDie, SPTy);
1108 addType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
1111 if (!SP.isDefinition()) {
1112 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1114 // Add arguments. Do not add arguments for subprogram definition. They will
1115 // be handled through RecordVariable.
1116 if (SPTag == dwarf::DW_TAG_subroutine_type)
1117 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1118 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1119 addType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1120 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1121 SPDie->addChild(Arg);
1125 // DW_TAG_inlined_subroutine may refer to this DIE.
1126 DW_Unit->insertDIE(SP.getNode(), SPDie);
1130 /// findCompileUnit - Get the compile unit for the given descriptor.
1132 CompileUnit &DwarfDebug::findCompileUnit(DICompileUnit Unit) const {
1133 DenseMap<Value *, CompileUnit *>::const_iterator I =
1134 CompileUnitMap.find(Unit.getNode());
1135 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1139 /// createDbgScopeVariable - Create a new scope variable.
1141 DIE *DwarfDebug::createDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1142 // Get the descriptor.
1143 const DIVariable &VD = DV->getVariable();
1144 const char *Name = VD.getName();
1148 // Translate tag to proper Dwarf tag. The result variable is dropped for
1151 switch (VD.getTag()) {
1152 case dwarf::DW_TAG_return_variable:
1154 case dwarf::DW_TAG_arg_variable:
1155 Tag = dwarf::DW_TAG_formal_parameter;
1157 case dwarf::DW_TAG_auto_variable: // fall thru
1159 Tag = dwarf::DW_TAG_variable;
1163 // Define variable debug information entry.
1164 DIE *VariableDie = new DIE(Tag);
1165 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1167 // Add source line info if available.
1168 addSourceLine(VariableDie, &VD);
1170 // Add variable type.
1171 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1172 // addresses instead.
1173 if (VD.isBlockByrefVariable())
1174 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name));
1176 addType(Unit, VariableDie, VD.getType());
1178 // Add variable address.
1179 // Variables for abstract instances of inlined functions don't get a
1181 MachineLocation Location;
1182 Location.set(RI->getFrameRegister(*MF),
1183 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1186 if (VD.hasComplexAddress())
1187 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1188 else if (VD.isBlockByrefVariable())
1189 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1191 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1196 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1197 /// Initialize scope and update scope hierarchy.
1198 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1199 MDNode *InlinedAt) {
1200 assert (N && "Invalid Scope encoding!");
1201 assert (MI && "Missing machine instruction!");
1202 bool GetConcreteScope = (MI && InlinedAt);
1204 DbgScope *NScope = NULL;
1207 NScope = DbgScopeMap.lookup(InlinedAt);
1209 NScope = DbgScopeMap.lookup(N);
1210 assert (NScope && "Unable to find working scope!");
1212 if (NScope->getFirstInsn())
1215 DbgScope *Parent = NULL;
1216 if (GetConcreteScope) {
1217 DILocation IL(InlinedAt);
1218 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1219 IL.getOrigLocation().getNode());
1220 assert (Parent && "Unable to find Parent scope!");
1221 NScope->setParent(Parent);
1222 Parent->addScope(NScope);
1223 } else if (DIDescriptor(N).isLexicalBlock()) {
1224 DILexicalBlock DB(N);
1225 if (!DB.getContext().isNull()) {
1226 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1227 NScope->setParent(Parent);
1228 Parent->addScope(NScope);
1232 NScope->setFirstInsn(MI);
1234 if (!Parent && !InlinedAt) {
1235 StringRef SPName = DISubprogram(N).getLinkageName();
1236 if (SPName == MF->getFunction()->getName())
1237 CurrentFnDbgScope = NScope;
1240 if (GetConcreteScope) {
1241 ConcreteScopes[InlinedAt] = NScope;
1242 getOrCreateAbstractScope(N);
1248 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1249 assert (N && "Invalid Scope encoding!");
1251 DbgScope *AScope = AbstractScopes.lookup(N);
1255 DbgScope *Parent = NULL;
1257 DIDescriptor Scope(N);
1258 if (Scope.isLexicalBlock()) {
1259 DILexicalBlock DB(N);
1260 DIDescriptor ParentDesc = DB.getContext();
1261 if (!ParentDesc.isNull())
1262 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1265 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1268 Parent->addScope(AScope);
1269 AScope->setAbstractScope();
1270 AbstractScopes[N] = AScope;
1271 if (DIDescriptor(N).isSubprogram())
1272 AbstractScopesList.push_back(AScope);
1276 static DISubprogram getDISubprogram(MDNode *N) {
1280 return DISubprogram();
1282 if (D.isCompileUnit())
1283 return DISubprogram();
1285 if (D.isSubprogram())
1286 return DISubprogram(N);
1288 if (D.isLexicalBlock())
1289 return getDISubprogram(DILexicalBlock(N).getContext().getNode());
1291 llvm_unreachable("Unexpected Descriptor!");
1294 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1295 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1296 /// If there are global variables in this scope then create and insert
1297 /// DIEs for these variables.
1298 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1300 DIE *SPDie = ModuleCU->getDIE(SPNode);
1301 assert (SPDie && "Unable to find subprogram DIE!");
1302 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1303 DWLabel("func_begin", SubprogramCount));
1304 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1305 DWLabel("func_end", SubprogramCount));
1306 MachineLocation Location(RI->getFrameRegister(*MF));
1307 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1309 if (!DISubprogram(SPNode).isLocalToUnit())
1310 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1312 // If there are global variables at this scope then add their dies.
1313 for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(),
1314 SGE = ScopedGVs.end(); SGI != SGE; ++SGI) {
1315 MDNode *N = dyn_cast_or_null<MDNode>(*SGI);
1317 DIGlobalVariable GV(N);
1318 if (GV.getContext().getNode() == SPNode) {
1319 DIE *ScopedGVDie = createGlobalVariableDIE(ModuleCU, GV);
1321 SPDie->addChild(ScopedGVDie);
1327 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1328 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1329 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1330 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1331 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1333 // Ignore empty scopes.
1334 if (StartID == EndID && StartID != 0)
1337 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1338 if (Scope->isAbstractScope())
1341 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1343 DWLabel("label", StartID)
1344 : DWLabel("func_begin", SubprogramCount));
1345 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1347 DWLabel("label", EndID)
1348 : DWLabel("func_end", SubprogramCount));
1355 /// constructInlinedScopeDIE - This scope represents inlined body of
1356 /// a function. Construct DIE to represent this concrete inlined copy
1357 /// of the function.
1358 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1359 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1360 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1361 assert (StartID && "Invalid starting label for an inlined scope!");
1362 assert (EndID && "Invalid end label for an inlined scope!");
1363 // Ignore empty scopes.
1364 if (StartID == EndID && StartID != 0)
1367 DIScope DS(Scope->getScopeNode());
1370 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1372 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1373 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1374 assert (OriginDIE && "Unable to find Origin DIE!");
1375 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1376 dwarf::DW_FORM_ref4, OriginDIE);
1378 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1379 DWLabel("label", StartID));
1380 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1381 DWLabel("label", EndID));
1383 InlinedSubprogramDIEs.insert(OriginDIE);
1385 // Track the start label for this inlined function.
1386 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1387 I = InlineInfo.find(InlinedSP.getNode());
1389 if (I == InlineInfo.end()) {
1390 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID, ScopeDIE));
1391 InlinedSPNodes.push_back(InlinedSP.getNode());
1393 I->second.push_back(std::make_pair(StartID, ScopeDIE));
1395 StringPool.insert(InlinedSP.getName());
1396 StringPool.insert(InlinedSP.getLinkageName());
1397 DILocation DL(Scope->getInlinedAt());
1398 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1399 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1405 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1406 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV,
1407 DbgScope *Scope, CompileUnit *Unit) {
1408 // Get the descriptor.
1409 const DIVariable &VD = DV->getVariable();
1410 const char *Name = VD.getName();
1414 // Translate tag to proper Dwarf tag. The result variable is dropped for
1417 switch (VD.getTag()) {
1418 case dwarf::DW_TAG_return_variable:
1420 case dwarf::DW_TAG_arg_variable:
1421 Tag = dwarf::DW_TAG_formal_parameter;
1423 case dwarf::DW_TAG_auto_variable: // fall thru
1425 Tag = dwarf::DW_TAG_variable;
1429 // Define variable debug information entry.
1430 DIE *VariableDie = new DIE(Tag);
1434 if (DbgVariable *AV = DV->getAbstractVariable())
1435 AbsDIE = AV->getDIE();
1438 DIScope DS(Scope->getScopeNode());
1439 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1440 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1442 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1443 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1444 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1445 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1446 dwarf::DW_FORM_ref4, AbsDIE);
1449 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1450 addSourceLine(VariableDie, &VD);
1452 // Add variable type.
1453 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1454 // addresses instead.
1455 if (VD.isBlockByrefVariable())
1456 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name));
1458 addType(Unit, VariableDie, VD.getType());
1461 // Add variable address.
1462 if (!Scope->isAbstractScope()) {
1463 MachineLocation Location;
1464 Location.set(RI->getFrameRegister(*MF),
1465 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1468 if (VD.hasComplexAddress())
1469 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1470 else if (VD.isBlockByrefVariable())
1471 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1473 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1475 DV->setDIE(VariableDie);
1480 /// constructScopeDIE - Construct a DIE for this scope.
1481 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1484 DIScope DS(Scope->getScopeNode());
1488 DIE *ScopeDIE = NULL;
1489 if (Scope->getInlinedAt())
1490 ScopeDIE = constructInlinedScopeDIE(Scope);
1491 else if (DS.isSubprogram()) {
1492 if (Scope->isAbstractScope())
1493 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1495 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1498 ScopeDIE = constructLexicalScopeDIE(Scope);
1499 if (!ScopeDIE) return NULL;
1502 // Add variables to scope.
1503 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1504 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1505 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope, ModuleCU);
1507 ScopeDIE->addChild(VariableDIE);
1510 // Add nested scopes.
1511 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1512 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1513 // Define the Scope debug information entry.
1514 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1516 ScopeDIE->addChild(NestedDIE);
1521 /// GetOrCreateSourceID - Look up the source id with the given directory and
1522 /// source file names. If none currently exists, create a new id and insert it
1523 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1525 unsigned DwarfDebug::GetOrCreateSourceID(const char *DirName,
1526 const char *FileName) {
1528 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1529 if (DI != DirectoryIdMap.end()) {
1530 DId = DI->getValue();
1532 DId = DirectoryNames.size() + 1;
1533 DirectoryIdMap[DirName] = DId;
1534 DirectoryNames.push_back(DirName);
1538 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1539 if (FI != SourceFileIdMap.end()) {
1540 FId = FI->getValue();
1542 FId = SourceFileNames.size() + 1;
1543 SourceFileIdMap[FileName] = FId;
1544 SourceFileNames.push_back(FileName);
1547 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1548 SourceIdMap.find(std::make_pair(DId, FId));
1549 if (SI != SourceIdMap.end())
1552 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1553 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1554 SourceIds.push_back(std::make_pair(DId, FId));
1559 void DwarfDebug::constructCompileUnit(MDNode *N) {
1560 DICompileUnit DIUnit(N);
1561 const char *FN = DIUnit.getFilename();
1562 const char *Dir = DIUnit.getDirectory();
1563 unsigned ID = GetOrCreateSourceID(Dir, FN);
1565 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1566 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1567 DWLabel("section_line", 0), DWLabel("section_line", 0),
1569 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1570 DIUnit.getProducer());
1571 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1572 DIUnit.getLanguage());
1573 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1576 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1577 if (DIUnit.isOptimized())
1578 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1580 if (const char *Flags = DIUnit.getFlags())
1581 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1583 unsigned RVer = DIUnit.getRunTimeVersion();
1585 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1586 dwarf::DW_FORM_data1, RVer);
1588 CompileUnit *Unit = new CompileUnit(ID, Die);
1589 if (!ModuleCU && DIUnit.isMain()) {
1590 // Use first compile unit marked as isMain as the compile unit
1595 CompileUnitMap[DIUnit.getNode()] = Unit;
1596 CompileUnits.push_back(Unit);
1599 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1600 DIGlobalVariable DI_GV(N);
1602 // If debug information is malformed then ignore it.
1603 if (DI_GV.Verify() == false)
1606 // Check for pre-existence.
1607 if (ModuleCU->getDIE(DI_GV.getNode()))
1610 DIE *VariableDie = createGlobalVariableDIE(ModuleCU, DI_GV);
1613 ModuleCU->insertDIE(N, VariableDie);
1615 // Add to context owner.
1616 ModuleCU->getCUDie()->addChild(VariableDie);
1618 // Expose as global. FIXME - need to check external flag.
1619 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1623 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1626 // Check for pre-existence.
1627 if (ModuleCU->getDIE(N))
1630 if (!SP.isDefinition())
1631 // This is a method declaration which will be handled while constructing
1635 DIE *SubprogramDie = createSubprogramDIE(ModuleCU, SP);
1638 ModuleCU->insertDIE(N, SubprogramDie);
1640 // Add to context owner.
1641 ModuleCU->getCUDie()->addChild(SubprogramDie);
1643 // Expose as global.
1644 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1648 /// beginModule - Emit all Dwarf sections that should come prior to the
1649 /// content. Create global DIEs and emit initial debug info sections.
1650 /// This is inovked by the target AsmPrinter.
1651 void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1654 if (TimePassesIsEnabled)
1655 DebugTimer->startTimer();
1657 if (!MAI->doesSupportDebugInformation())
1660 DebugInfoFinder DbgFinder;
1661 DbgFinder.processModule(*M);
1663 // Create all the compile unit DIEs.
1664 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1665 E = DbgFinder.compile_unit_end(); I != E; ++I)
1666 constructCompileUnit(*I);
1668 if (CompileUnits.empty()) {
1669 if (TimePassesIsEnabled)
1670 DebugTimer->stopTimer();
1675 // If main compile unit for this module is not seen than randomly
1676 // select first compile unit.
1678 ModuleCU = CompileUnits[0];
1680 // Create DIEs for each of the externally visible global variables.
1681 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1682 E = DbgFinder.global_variable_end(); I != E; ++I) {
1683 DIGlobalVariable GV(*I);
1684 if (GV.getContext().getNode() != GV.getCompileUnit().getNode())
1685 ScopedGVs.push_back(*I);
1687 constructGlobalVariableDIE(*I);
1690 // Create DIEs for each subprogram.
1691 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1692 E = DbgFinder.subprogram_end(); I != E; ++I)
1693 constructSubprogramDIE(*I);
1697 MMI->setDebugInfoAvailability(true);
1699 // Prime section data.
1700 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1702 // Print out .file directives to specify files for .loc directives. These are
1703 // printed out early so that they precede any .loc directives.
1704 if (MAI->hasDotLocAndDotFile()) {
1705 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1706 // Remember source id starts at 1.
1707 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1708 sys::Path FullPath(getSourceDirectoryName(Id.first));
1710 FullPath.appendComponent(getSourceFileName(Id.second));
1711 assert(AppendOk && "Could not append filename to directory!");
1713 Asm->EmitFile(i, FullPath.str());
1718 // Emit initial sections
1721 if (TimePassesIsEnabled)
1722 DebugTimer->stopTimer();
1725 /// endModule - Emit all Dwarf sections that should come after the content.
1727 void DwarfDebug::endModule() {
1731 if (TimePassesIsEnabled)
1732 DebugTimer->startTimer();
1734 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1735 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1736 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1738 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1741 // Standard sections final addresses.
1742 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1743 EmitLabel("text_end", 0);
1744 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1745 EmitLabel("data_end", 0);
1747 // End text sections.
1748 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1749 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1750 EmitLabel("section_end", i);
1753 // Emit common frame information.
1754 emitCommonDebugFrame();
1756 // Emit function debug frame information
1757 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1758 E = DebugFrames.end(); I != E; ++I)
1759 emitFunctionDebugFrame(*I);
1761 // Compute DIE offsets and sizes.
1762 computeSizeAndOffsets();
1764 // Emit all the DIEs into a debug info section
1767 // Corresponding abbreviations into a abbrev section.
1768 emitAbbreviations();
1770 // Emit source line correspondence into a debug line section.
1773 // Emit info into a debug pubnames section.
1774 emitDebugPubNames();
1776 // Emit info into a debug str section.
1779 // Emit info into a debug loc section.
1782 // Emit info into a debug aranges section.
1785 // Emit info into a debug ranges section.
1788 // Emit info into a debug macinfo section.
1791 // Emit inline info.
1792 emitDebugInlineInfo();
1794 if (TimePassesIsEnabled)
1795 DebugTimer->stopTimer();
1798 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1799 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var, unsigned FrameIdx,
1800 DILocation &ScopeLoc) {
1802 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1804 return AbsDbgVariable;
1806 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1810 AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1811 Scope->addVariable(AbsDbgVariable);
1812 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1813 return AbsDbgVariable;
1816 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1817 void DwarfDebug::collectVariableInfo() {
1820 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1821 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1822 VE = VMap.end(); VI != VE; ++VI) {
1823 MetadataBase *MB = VI->first;
1824 MDNode *Var = dyn_cast_or_null<MDNode>(MB);
1826 DIVariable DV (Var);
1827 std::pair< unsigned, MDNode *> VP = VI->second;
1828 DILocation ScopeLoc(VP.second);
1831 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1833 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1834 // If variable scope is not found then skip this variable.
1838 DbgVariable *RegVar = new DbgVariable(DV, VP.first);
1839 Scope->addVariable(RegVar);
1840 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, ScopeLoc))
1841 RegVar->setAbstractVariable(AbsDbgVariable);
1845 /// beginScope - Process beginning of a scope starting at Label.
1846 void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) {
1847 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1848 if (I == DbgScopeBeginMap.end())
1850 ScopeVector &SD = DbgScopeBeginMap[MI];
1851 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1853 (*SDI)->setStartLabelID(Label);
1856 /// endScope - Process end of a scope.
1857 void DwarfDebug::endScope(const MachineInstr *MI) {
1858 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1859 if (I == DbgScopeEndMap.end())
1862 unsigned Label = MMI->NextLabelID();
1863 Asm->printLabel(Label);
1865 SmallVector<DbgScope *, 2> &SD = I->second;
1866 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1868 (*SDI)->setEndLabelID(Label);
1872 /// createDbgScope - Create DbgScope for the scope.
1873 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1876 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1879 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1880 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1881 if (DIDescriptor(Scope).isLexicalBlock())
1882 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
1886 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1890 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1891 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1892 DILocation DL(InlinedAt);
1893 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
1896 /// extractScopeInformation - Scan machine instructions in this function
1897 /// and collect DbgScopes. Return true, if atleast one scope was found.
1898 bool DwarfDebug::extractScopeInformation(MachineFunction *MF) {
1899 // If scope information was extracted using .dbg intrinsics then there is not
1900 // any need to extract these information by scanning each instruction.
1901 if (!DbgScopeMap.empty())
1904 // Scan each instruction and create scopes. First build working set of scopes.
1905 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1907 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1909 const MachineInstr *MInsn = II;
1910 DebugLoc DL = MInsn->getDebugLoc();
1911 if (DL.isUnknown()) continue;
1912 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1913 if (!DLT.Scope) continue;
1914 // There is no need to create another DIE for compile unit. For all
1915 // other scopes, create one DbgScope now. This will be translated
1916 // into a scope DIE at the end.
1917 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
1918 createDbgScope(DLT.Scope, DLT.InlinedAtLoc);
1923 // Build scope hierarchy using working set of scopes.
1924 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1926 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1928 const MachineInstr *MInsn = II;
1929 DebugLoc DL = MInsn->getDebugLoc();
1930 if (DL.isUnknown()) continue;
1931 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1932 if (!DLT.Scope) continue;
1933 // There is no need to create another DIE for compile unit. For all
1934 // other scopes, create one DbgScope now. This will be translated
1935 // into a scope DIE at the end.
1936 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
1937 DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
1938 Scope->setLastInsn(MInsn);
1942 // If a scope's last instruction is not set then use its child scope's
1943 // last instruction as this scope's last instrunction.
1944 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1945 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1946 if (DI->second->isAbstractScope())
1948 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
1949 DI->second->fixInstructionMarkers();
1950 assert (DI->second->getLastInsn() && "Invalid last instruction!");
1953 // Each scope has first instruction and last instruction to mark beginning
1954 // and end of a scope respectively. Create an inverse map that list scopes
1955 // starts (and ends) with an instruction. One instruction may start (or end)
1957 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1958 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1959 DbgScope *S = DI->second;
1960 if (S->isAbstractScope())
1962 const MachineInstr *MI = S->getFirstInsn();
1963 assert (MI && "DbgScope does not have first instruction!");
1965 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
1966 if (IDI != DbgScopeBeginMap.end())
1967 IDI->second.push_back(S);
1969 DbgScopeBeginMap[MI].push_back(S);
1971 MI = S->getLastInsn();
1972 assert (MI && "DbgScope does not have last instruction!");
1973 IDI = DbgScopeEndMap.find(MI);
1974 if (IDI != DbgScopeEndMap.end())
1975 IDI->second.push_back(S);
1977 DbgScopeEndMap[MI].push_back(S);
1980 return !DbgScopeMap.empty();
1983 /// beginFunction - Gather pre-function debug information. Assumes being
1984 /// emitted immediately after the function entry point.
1985 void DwarfDebug::beginFunction(MachineFunction *MF) {
1988 if (!ShouldEmitDwarfDebug()) return;
1990 if (TimePassesIsEnabled)
1991 DebugTimer->startTimer();
1993 if (!extractScopeInformation(MF))
1996 collectVariableInfo();
1998 // Begin accumulating function debug information.
1999 MMI->BeginFunction(MF);
2001 // Assumes in correct section after the entry point.
2002 EmitLabel("func_begin", ++SubprogramCount);
2004 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2006 DebugLoc FDL = MF->getDefaultDebugLoc();
2007 if (!FDL.isUnknown()) {
2008 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2009 unsigned LabelID = 0;
2010 DISubprogram SP = getDISubprogram(DLT.Scope);
2012 LabelID = recordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
2014 LabelID = recordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
2015 Asm->printLabel(LabelID);
2018 if (TimePassesIsEnabled)
2019 DebugTimer->stopTimer();
2022 /// endFunction - Gather and emit post-function debug information.
2024 void DwarfDebug::endFunction(MachineFunction *MF) {
2025 if (!ShouldEmitDwarfDebug()) return;
2027 if (TimePassesIsEnabled)
2028 DebugTimer->startTimer();
2030 if (DbgScopeMap.empty())
2033 // Define end label for subprogram.
2034 EmitLabel("func_end", SubprogramCount);
2036 // Get function line info.
2037 if (!Lines.empty()) {
2038 // Get section line info.
2039 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2040 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2041 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2042 // Append the function info to section info.
2043 SectionLineInfos.insert(SectionLineInfos.end(),
2044 Lines.begin(), Lines.end());
2047 // Construct abstract scopes.
2048 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2049 AE = AbstractScopesList.end(); AI != AE; ++AI)
2050 constructScopeDIE(*AI);
2052 constructScopeDIE(CurrentFnDbgScope);
2054 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2055 MMI->getFrameMoves()));
2058 if (CurrentFnDbgScope) {
2059 CurrentFnDbgScope = NULL;
2060 DbgScopeMap.clear();
2061 DbgScopeBeginMap.clear();
2062 DbgScopeEndMap.clear();
2063 ConcreteScopes.clear();
2064 AbstractScopesList.clear();
2069 if (TimePassesIsEnabled)
2070 DebugTimer->stopTimer();
2073 /// recordSourceLine - Records location information and associates it with a
2074 /// label. Returns a unique label ID used to generate a label and provide
2075 /// correspondence to the source line list.
2076 unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2081 if (TimePassesIsEnabled)
2082 DebugTimer->startTimer();
2084 const char *Dir = NULL;
2085 const char *Fn = NULL;
2087 DIDescriptor Scope(S);
2088 if (Scope.isCompileUnit()) {
2089 DICompileUnit CU(S);
2090 Dir = CU.getDirectory();
2091 Fn = CU.getFilename();
2092 } else if (Scope.isSubprogram()) {
2094 Dir = SP.getDirectory();
2095 Fn = SP.getFilename();
2096 } else if (Scope.isLexicalBlock()) {
2097 DILexicalBlock DB(S);
2098 Dir = DB.getDirectory();
2099 Fn = DB.getFilename();
2101 assert (0 && "Unexpected scope info");
2103 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2104 unsigned ID = MMI->NextLabelID();
2105 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2107 if (TimePassesIsEnabled)
2108 DebugTimer->stopTimer();
2113 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2114 /// timed. Look up the source id with the given directory and source file
2115 /// names. If none currently exists, create a new id and insert it in the
2116 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2118 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2119 const std::string &FileName) {
2120 if (TimePassesIsEnabled)
2121 DebugTimer->startTimer();
2123 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2125 if (TimePassesIsEnabled)
2126 DebugTimer->stopTimer();
2131 //===----------------------------------------------------------------------===//
2133 //===----------------------------------------------------------------------===//
2135 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2137 unsigned DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2138 // Get the children.
2139 const std::vector<DIE *> &Children = Die->getChildren();
2141 // If not last sibling and has children then add sibling offset attribute.
2142 if (!Last && !Children.empty()) Die->addSiblingOffset();
2144 // Record the abbreviation.
2145 assignAbbrevNumber(Die->getAbbrev());
2147 // Get the abbreviation for this DIE.
2148 unsigned AbbrevNumber = Die->getAbbrevNumber();
2149 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2152 Die->setOffset(Offset);
2154 // Start the size with the size of abbreviation code.
2155 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2157 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2158 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2160 // Size the DIE attribute values.
2161 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2162 // Size attribute value.
2163 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2165 // Size the DIE children if any.
2166 if (!Children.empty()) {
2167 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2168 "Children flag not set");
2170 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2171 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2173 // End of children marker.
2174 Offset += sizeof(int8_t);
2177 Die->setSize(Offset - Die->getOffset());
2181 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2183 void DwarfDebug::computeSizeAndOffsets() {
2184 // Compute size of compile unit header.
2185 static unsigned Offset =
2186 sizeof(int32_t) + // Length of Compilation Unit Info
2187 sizeof(int16_t) + // DWARF version number
2188 sizeof(int32_t) + // Offset Into Abbrev. Section
2189 sizeof(int8_t); // Pointer Size (in bytes)
2191 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2192 CompileUnitOffsets[ModuleCU] = 0;
2195 /// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
2196 /// tools to recognize the object file contains Dwarf information.
2197 void DwarfDebug::emitInitial() {
2198 // Check to see if we already emitted intial headers.
2199 if (didInitial) return;
2202 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2204 // Dwarf sections base addresses.
2205 if (MAI->doesDwarfRequireFrameSection()) {
2206 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2207 EmitLabel("section_debug_frame", 0);
2210 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2211 EmitLabel("section_info", 0);
2212 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2213 EmitLabel("section_abbrev", 0);
2214 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2215 EmitLabel("section_aranges", 0);
2217 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2218 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2219 EmitLabel("section_macinfo", 0);
2222 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2223 EmitLabel("section_line", 0);
2224 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2225 EmitLabel("section_loc", 0);
2226 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2227 EmitLabel("section_pubnames", 0);
2228 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2229 EmitLabel("section_str", 0);
2230 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2231 EmitLabel("section_ranges", 0);
2233 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2234 EmitLabel("text_begin", 0);
2235 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2236 EmitLabel("data_begin", 0);
2239 /// emitDIE - Recusively Emits a debug information entry.
2241 void DwarfDebug::emitDIE(DIE *Die) {
2242 // Get the abbreviation for this DIE.
2243 unsigned AbbrevNumber = Die->getAbbrevNumber();
2244 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2248 // Emit the code (index) for the abbreviation.
2249 Asm->EmitULEB128Bytes(AbbrevNumber);
2251 if (Asm->isVerbose())
2252 Asm->EOL(std::string("Abbrev [" +
2253 utostr(AbbrevNumber) +
2254 "] 0x" + utohexstr(Die->getOffset()) +
2255 ":0x" + utohexstr(Die->getSize()) + " " +
2256 dwarf::TagString(Abbrev->getTag())));
2260 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2261 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2263 // Emit the DIE attribute values.
2264 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2265 unsigned Attr = AbbrevData[i].getAttribute();
2266 unsigned Form = AbbrevData[i].getForm();
2267 assert(Form && "Too many attributes for DIE (check abbreviation)");
2270 case dwarf::DW_AT_sibling:
2271 Asm->EmitInt32(Die->getSiblingOffset());
2273 case dwarf::DW_AT_abstract_origin: {
2274 DIEEntry *E = cast<DIEEntry>(Values[i]);
2275 DIE *Origin = E->getEntry();
2276 unsigned Addr = Origin->getOffset();
2277 Asm->EmitInt32(Addr);
2281 // Emit an attribute using the defined form.
2282 Values[i]->EmitValue(this, Form);
2286 Asm->EOL(dwarf::AttributeString(Attr));
2289 // Emit the DIE children if any.
2290 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2291 const std::vector<DIE *> &Children = Die->getChildren();
2293 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2294 emitDIE(Children[j]);
2296 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2300 /// emitDebugInfo / emitDebugInfoPerCU - Emit the debug info section.
2302 void DwarfDebug::emitDebugInfoPerCU(CompileUnit *Unit) {
2303 DIE *Die = Unit->getCUDie();
2305 // Emit the compile units header.
2306 EmitLabel("info_begin", Unit->getID());
2308 // Emit size of content not including length itself
2309 unsigned ContentSize = Die->getSize() +
2310 sizeof(int16_t) + // DWARF version number
2311 sizeof(int32_t) + // Offset Into Abbrev. Section
2312 sizeof(int8_t) + // Pointer Size (in bytes)
2313 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2315 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2316 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2317 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2318 Asm->EOL("Offset Into Abbrev. Section");
2319 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2322 // FIXME - extra padding for gdb bug.
2323 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2324 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2325 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2326 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2327 EmitLabel("info_end", Unit->getID());
2332 void DwarfDebug::emitDebugInfo() {
2333 // Start debug info section.
2334 Asm->OutStreamer.SwitchSection(
2335 Asm->getObjFileLowering().getDwarfInfoSection());
2337 emitDebugInfoPerCU(ModuleCU);
2340 /// emitAbbreviations - Emit the abbreviation section.
2342 void DwarfDebug::emitAbbreviations() const {
2343 // Check to see if it is worth the effort.
2344 if (!Abbreviations.empty()) {
2345 // Start the debug abbrev section.
2346 Asm->OutStreamer.SwitchSection(
2347 Asm->getObjFileLowering().getDwarfAbbrevSection());
2349 EmitLabel("abbrev_begin", 0);
2351 // For each abbrevation.
2352 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2353 // Get abbreviation data
2354 const DIEAbbrev *Abbrev = Abbreviations[i];
2356 // Emit the abbrevations code (base 1 index.)
2357 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2358 Asm->EOL("Abbreviation Code");
2360 // Emit the abbreviations data.
2366 // Mark end of abbreviations.
2367 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2369 EmitLabel("abbrev_end", 0);
2374 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2375 /// the line matrix.
2377 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2378 // Define last address of section.
2379 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2380 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2381 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2382 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2384 // Mark end of matrix.
2385 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2386 Asm->EmitULEB128Bytes(1); Asm->EOL();
2387 Asm->EmitInt8(1); Asm->EOL();
2390 /// emitDebugLines - Emit source line information.
2392 void DwarfDebug::emitDebugLines() {
2393 // If the target is using .loc/.file, the assembler will be emitting the
2394 // .debug_line table automatically.
2395 if (MAI->hasDotLocAndDotFile())
2398 // Minimum line delta, thus ranging from -10..(255-10).
2399 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2400 // Maximum line delta, thus ranging from -10..(255-10).
2401 const int MaxLineDelta = 255 + MinLineDelta;
2403 // Start the dwarf line section.
2404 Asm->OutStreamer.SwitchSection(
2405 Asm->getObjFileLowering().getDwarfLineSection());
2407 // Construct the section header.
2408 EmitDifference("line_end", 0, "line_begin", 0, true);
2409 Asm->EOL("Length of Source Line Info");
2410 EmitLabel("line_begin", 0);
2412 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2414 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2415 Asm->EOL("Prolog Length");
2416 EmitLabel("line_prolog_begin", 0);
2418 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2420 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2422 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2424 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2426 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2428 // Line number standard opcode encodings argument count
2429 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2430 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2431 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2432 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2433 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2434 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2435 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2436 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2437 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2439 // Emit directories.
2440 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2441 Asm->EmitString(getSourceDirectoryName(DI));
2442 Asm->EOL("Directory");
2445 Asm->EmitInt8(0); Asm->EOL("End of directories");
2448 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2449 // Remember source id starts at 1.
2450 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2451 Asm->EmitString(getSourceFileName(Id.second));
2453 Asm->EmitULEB128Bytes(Id.first);
2454 Asm->EOL("Directory #");
2455 Asm->EmitULEB128Bytes(0);
2456 Asm->EOL("Mod date");
2457 Asm->EmitULEB128Bytes(0);
2458 Asm->EOL("File size");
2461 Asm->EmitInt8(0); Asm->EOL("End of files");
2463 EmitLabel("line_prolog_end", 0);
2465 // A sequence for each text section.
2466 unsigned SecSrcLinesSize = SectionSourceLines.size();
2468 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2469 // Isolate current sections line info.
2470 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2472 /*if (Asm->isVerbose()) {
2473 const MCSection *S = SectionMap[j + 1];
2474 O << '\t' << MAI->getCommentString() << " Section"
2475 << S->getName() << '\n';
2479 // Dwarf assumes we start with first line of first source file.
2480 unsigned Source = 1;
2483 // Construct rows of the address, source, line, column matrix.
2484 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2485 const SrcLineInfo &LineInfo = LineInfos[i];
2486 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2487 if (!LabelID) continue;
2489 if (LineInfo.getLine() == 0) continue;
2491 if (!Asm->isVerbose())
2494 std::pair<unsigned, unsigned> SourceID =
2495 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2496 O << '\t' << MAI->getCommentString() << ' '
2497 << getSourceDirectoryName(SourceID.first) << ' '
2498 << getSourceFileName(SourceID.second)
2499 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2502 // Define the line address.
2503 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2504 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2505 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2506 EmitReference("label", LabelID); Asm->EOL("Location label");
2508 // If change of source, then switch to the new source.
2509 if (Source != LineInfo.getSourceID()) {
2510 Source = LineInfo.getSourceID();
2511 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2512 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2515 // If change of line.
2516 if (Line != LineInfo.getLine()) {
2517 // Determine offset.
2518 int Offset = LineInfo.getLine() - Line;
2519 int Delta = Offset - MinLineDelta;
2522 Line = LineInfo.getLine();
2524 // If delta is small enough and in range...
2525 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2526 // ... then use fast opcode.
2527 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2529 // ... otherwise use long hand.
2530 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2531 Asm->EOL("DW_LNS_advance_line");
2532 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2533 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2536 // Copy the previous row (different address or source)
2537 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2541 emitEndOfLineMatrix(j + 1);
2544 if (SecSrcLinesSize == 0)
2545 // Because we're emitting a debug_line section, we still need a line
2546 // table. The linker and friends expect it to exist. If there's nothing to
2547 // put into it, emit an empty table.
2548 emitEndOfLineMatrix(1);
2550 EmitLabel("line_end", 0);
2554 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2556 void DwarfDebug::emitCommonDebugFrame() {
2557 if (!MAI->doesDwarfRequireFrameSection())
2561 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2562 TargetFrameInfo::StackGrowsUp ?
2563 TD->getPointerSize() : -TD->getPointerSize();
2565 // Start the dwarf frame section.
2566 Asm->OutStreamer.SwitchSection(
2567 Asm->getObjFileLowering().getDwarfFrameSection());
2569 EmitLabel("debug_frame_common", 0);
2570 EmitDifference("debug_frame_common_end", 0,
2571 "debug_frame_common_begin", 0, true);
2572 Asm->EOL("Length of Common Information Entry");
2574 EmitLabel("debug_frame_common_begin", 0);
2575 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2576 Asm->EOL("CIE Identifier Tag");
2577 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2578 Asm->EOL("CIE Version");
2579 Asm->EmitString("");
2580 Asm->EOL("CIE Augmentation");
2581 Asm->EmitULEB128Bytes(1);
2582 Asm->EOL("CIE Code Alignment Factor");
2583 Asm->EmitSLEB128Bytes(stackGrowth);
2584 Asm->EOL("CIE Data Alignment Factor");
2585 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2586 Asm->EOL("CIE RA Column");
2588 std::vector<MachineMove> Moves;
2589 RI->getInitialFrameState(Moves);
2591 EmitFrameMoves(NULL, 0, Moves, false);
2593 Asm->EmitAlignment(2, 0, 0, false);
2594 EmitLabel("debug_frame_common_end", 0);
2599 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2602 DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2603 if (!MAI->doesDwarfRequireFrameSection())
2606 // Start the dwarf frame section.
2607 Asm->OutStreamer.SwitchSection(
2608 Asm->getObjFileLowering().getDwarfFrameSection());
2610 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2611 "debug_frame_begin", DebugFrameInfo.Number, true);
2612 Asm->EOL("Length of Frame Information Entry");
2614 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2616 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2618 Asm->EOL("FDE CIE offset");
2620 EmitReference("func_begin", DebugFrameInfo.Number);
2621 Asm->EOL("FDE initial location");
2622 EmitDifference("func_end", DebugFrameInfo.Number,
2623 "func_begin", DebugFrameInfo.Number);
2624 Asm->EOL("FDE address range");
2626 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2629 Asm->EmitAlignment(2, 0, 0, false);
2630 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2635 void DwarfDebug::emitDebugPubNamesPerCU(CompileUnit *Unit) {
2636 EmitDifference("pubnames_end", Unit->getID(),
2637 "pubnames_begin", Unit->getID(), true);
2638 Asm->EOL("Length of Public Names Info");
2640 EmitLabel("pubnames_begin", Unit->getID());
2642 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2644 EmitSectionOffset("info_begin", "section_info",
2645 Unit->getID(), 0, true, false);
2646 Asm->EOL("Offset of Compilation Unit Info");
2648 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2650 Asm->EOL("Compilation Unit Length");
2652 StringMap<DIE*> &Globals = Unit->getGlobals();
2653 for (StringMap<DIE*>::const_iterator
2654 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2655 const char *Name = GI->getKeyData();
2656 DIE * Entity = GI->second;
2658 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2659 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2662 Asm->EmitInt32(0); Asm->EOL("End Mark");
2663 EmitLabel("pubnames_end", Unit->getID());
2668 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2670 void DwarfDebug::emitDebugPubNames() {
2671 // Start the dwarf pubnames section.
2672 Asm->OutStreamer.SwitchSection(
2673 Asm->getObjFileLowering().getDwarfPubNamesSection());
2675 emitDebugPubNamesPerCU(ModuleCU);
2678 /// emitDebugStr - Emit visible names into a debug str section.
2680 void DwarfDebug::emitDebugStr() {
2681 // Check to see if it is worth the effort.
2682 if (!StringPool.empty()) {
2683 // Start the dwarf str section.
2684 Asm->OutStreamer.SwitchSection(
2685 Asm->getObjFileLowering().getDwarfStrSection());
2687 // For each of strings in the string pool.
2688 for (unsigned StringID = 1, N = StringPool.size();
2689 StringID <= N; ++StringID) {
2690 // Emit a label for reference from debug information entries.
2691 EmitLabel("string", StringID);
2693 // Emit the string itself.
2694 const std::string &String = StringPool[StringID];
2695 Asm->EmitString(String); Asm->EOL();
2702 /// emitDebugLoc - Emit visible names into a debug loc section.
2704 void DwarfDebug::emitDebugLoc() {
2705 // Start the dwarf loc section.
2706 Asm->OutStreamer.SwitchSection(
2707 Asm->getObjFileLowering().getDwarfLocSection());
2711 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2713 void DwarfDebug::EmitDebugARanges() {
2714 // Start the dwarf aranges section.
2715 Asm->OutStreamer.SwitchSection(
2716 Asm->getObjFileLowering().getDwarfARangesSection());
2720 CompileUnit *Unit = GetBaseCompileUnit();
2722 // Don't include size of length
2723 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2725 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2727 EmitReference("info_begin", Unit->getID());
2728 Asm->EOL("Offset of Compilation Unit Info");
2730 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2732 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2734 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2735 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2738 EmitReference("text_begin", 0); Asm->EOL("Address");
2739 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2741 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2742 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2748 /// emitDebugRanges - Emit visible names into a debug ranges section.
2750 void DwarfDebug::emitDebugRanges() {
2751 // Start the dwarf ranges section.
2752 Asm->OutStreamer.SwitchSection(
2753 Asm->getObjFileLowering().getDwarfRangesSection());
2757 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2759 void DwarfDebug::emitDebugMacInfo() {
2760 if (const MCSection *LineInfo =
2761 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2762 // Start the dwarf macinfo section.
2763 Asm->OutStreamer.SwitchSection(LineInfo);
2768 /// emitDebugInlineInfo - Emit inline info using following format.
2770 /// 1. length of section
2771 /// 2. Dwarf version number
2772 /// 3. address size.
2774 /// Entries (one "entry" for each function that was inlined):
2776 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2777 /// otherwise offset into __debug_str for regular function name.
2778 /// 2. offset into __debug_str section for regular function name.
2779 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2780 /// instances for the function.
2782 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2783 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2784 /// __debug_info section, and the low_pc is the starting address for the
2785 /// inlining instance.
2786 void DwarfDebug::emitDebugInlineInfo() {
2787 if (!MAI->doesDwarfUsesInlineInfoSection())
2793 Asm->OutStreamer.SwitchSection(
2794 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2796 EmitDifference("debug_inlined_end", 1,
2797 "debug_inlined_begin", 1, true);
2798 Asm->EOL("Length of Debug Inlined Information Entry");
2800 EmitLabel("debug_inlined_begin", 1);
2802 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2803 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2805 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2806 E = InlinedSPNodes.end(); I != E; ++I) {
2808 // for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
2809 // I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2811 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II = InlineInfo.find(Node);
2812 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2813 DISubprogram SP(Node);
2814 const char *LName = SP.getLinkageName();
2815 const char *Name = SP.getName();
2818 Asm->EmitString(Name);
2820 // Skip special LLVM prefix that is used to inform the asm printer to not
2821 // emit usual symbol prefix before the symbol name. This happens for
2822 // Objective-C symbol names and symbol whose name is replaced using GCC's
2823 // __asm__ attribute.
2826 // Asm->EmitString(LName);
2827 EmitSectionOffset("string", "section_str",
2828 StringPool.idFor(LName), false, true);
2831 Asm->EOL("MIPS linkage name");
2832 // Asm->EmitString(Name);
2833 EmitSectionOffset("string", "section_str",
2834 StringPool.idFor(Name), false, true);
2835 Asm->EOL("Function name");
2836 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2838 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2839 LE = Labels.end(); LI != LE; ++LI) {
2840 DIE *SP = LI->second;
2841 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2843 if (TD->getPointerSize() == sizeof(int32_t))
2844 O << MAI->getData32bitsDirective();
2846 O << MAI->getData64bitsDirective();
2848 PrintLabelName("label", LI->first); Asm->EOL("low_pc");
2852 EmitLabel("debug_inlined_end", 1);