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
124 void setIndexTyDie(DIE *D) {
130 //===----------------------------------------------------------------------===//
131 /// DbgVariable - This class is used to track local variable information.
134 DIVariable Var; // Variable Descriptor.
135 unsigned FrameIndex; // Variable frame index.
136 DbgVariable *AbstractVar; // Abstract variable for this variable.
139 DbgVariable(DIVariable V, unsigned I)
140 : Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0) {}
143 DIVariable getVariable() const { return Var; }
144 unsigned getFrameIndex() const { return FrameIndex; }
145 void setAbstractVariable(DbgVariable *V) { AbstractVar = V; }
146 DbgVariable *getAbstractVariable() const { return AbstractVar; }
147 void setDIE(DIE *D) { TheDIE = D; }
148 DIE *getDIE() const { return TheDIE; }
151 //===----------------------------------------------------------------------===//
152 /// DbgScope - This class is used to track scope information.
155 DbgScope *Parent; // Parent to this scope.
156 DIDescriptor Desc; // Debug info descriptor for scope.
157 WeakVH InlinedAtLocation; // Location at which scope is inlined.
158 bool AbstractScope; // Abstract Scope
159 unsigned StartLabelID; // Label ID of the beginning of scope.
160 unsigned EndLabelID; // Label ID of the end of scope.
161 const MachineInstr *LastInsn; // Last instruction of this scope.
162 const MachineInstr *FirstInsn; // First instruction of this scope.
163 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
164 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
166 // Private state for dump()
167 mutable unsigned IndentLevel;
169 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
170 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
171 StartLabelID(0), EndLabelID(0),
172 LastInsn(0), FirstInsn(0), IndentLevel(0) {}
176 DbgScope *getParent() const { return Parent; }
177 void setParent(DbgScope *P) { Parent = P; }
178 DIDescriptor getDesc() const { return Desc; }
179 MDNode *getInlinedAt() const {
180 return dyn_cast_or_null<MDNode>(InlinedAtLocation);
182 MDNode *getScopeNode() const { return Desc.getNode(); }
183 unsigned getStartLabelID() const { return StartLabelID; }
184 unsigned getEndLabelID() const { return EndLabelID; }
185 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
186 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
187 void setStartLabelID(unsigned S) { StartLabelID = S; }
188 void setEndLabelID(unsigned E) { EndLabelID = E; }
189 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
190 const MachineInstr *getLastInsn() { return LastInsn; }
191 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
192 void setAbstractScope() { AbstractScope = true; }
193 bool isAbstractScope() const { return AbstractScope; }
194 const MachineInstr *getFirstInsn() { return FirstInsn; }
196 /// addScope - Add a scope to the scope.
198 void addScope(DbgScope *S) { Scopes.push_back(S); }
200 /// addVariable - Add a variable to the scope.
202 void addVariable(DbgVariable *V) { Variables.push_back(V); }
204 void fixInstructionMarkers() {
205 assert (getFirstInsn() && "First instruction is missing!");
209 // If a scope does not have an instruction to mark an end then use
210 // the end of last child scope.
211 SmallVector<DbgScope *, 4> &Scopes = getScopes();
212 assert (!Scopes.empty() && "Inner most scope does not have last insn!");
213 DbgScope *L = Scopes.back();
214 if (!L->getLastInsn())
215 L->fixInstructionMarkers();
216 setLastInsn(L->getLastInsn());
225 void DbgScope::dump() const {
226 raw_ostream &err = errs();
227 err.indent(IndentLevel);
228 MDNode *N = Desc.getNode();
230 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
232 err << "Abstract Scope\n";
236 err << "Children ...\n";
237 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
238 if (Scopes[i] != this)
245 DbgScope::~DbgScope() {
246 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
248 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
252 } // end llvm namespace
254 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
255 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
256 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
257 DIEValues(), StringPool(),
258 SectionSourceLines(), didInitial(false), shouldEmit(false),
259 CurrentFnDbgScope(0), DebugTimer(0) {
260 if (TimePassesIsEnabled)
261 DebugTimer = new Timer("Dwarf Debug Writer",
262 getDwarfTimerGroup());
264 DwarfDebug::~DwarfDebug() {
265 for (unsigned j = 0, M = DIEValues.size(); j < M; ++j)
271 /// assignAbbrevNumber - Define a unique number for the abbreviation.
273 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
274 // Profile the node so that we can make it unique.
278 // Check the set for priors.
279 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
281 // If it's newly added.
282 if (InSet == &Abbrev) {
283 // Add to abbreviation list.
284 Abbreviations.push_back(&Abbrev);
286 // Assign the vector position + 1 as its number.
287 Abbrev.setNumber(Abbreviations.size());
289 // Assign existing abbreviation number.
290 Abbrev.setNumber(InSet->getNumber());
294 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
295 /// information entry.
296 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
297 DIEEntry *Value = new DIEEntry(Entry);
298 DIEValues.push_back(Value);
302 /// addUInt - Add an unsigned integer attribute data and value.
304 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
305 unsigned Form, uint64_t Integer) {
306 if (!Form) Form = DIEInteger::BestForm(false, Integer);
307 DIEValue *Value = new DIEInteger(Integer);
308 DIEValues.push_back(Value);
309 Die->addValue(Attribute, Form, Value);
312 /// addSInt - Add an signed integer attribute data and value.
314 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
315 unsigned Form, int64_t Integer) {
316 if (!Form) Form = DIEInteger::BestForm(true, Integer);
317 DIEValue *Value = new DIEInteger(Integer);
318 DIEValues.push_back(Value);
319 Die->addValue(Attribute, Form, Value);
322 /// addString - Add a string attribute data and value.
324 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
325 const std::string &String) {
326 DIEValue *Value = new DIEString(String);
327 DIEValues.push_back(Value);
328 Die->addValue(Attribute, Form, Value);
331 /// addLabel - Add a Dwarf label attribute data and value.
333 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
334 const DWLabel &Label) {
335 DIEValue *Value = new DIEDwarfLabel(Label);
336 DIEValues.push_back(Value);
337 Die->addValue(Attribute, Form, Value);
340 /// addObjectLabel - Add an non-Dwarf label attribute data and value.
342 void DwarfDebug::addObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
343 const std::string &Label) {
344 DIEValue *Value = new DIEObjectLabel(Label);
345 DIEValues.push_back(Value);
346 Die->addValue(Attribute, Form, Value);
349 /// addSectionOffset - Add a section offset label attribute data and value.
351 void DwarfDebug::addSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
352 const DWLabel &Label, const DWLabel &Section,
353 bool isEH, bool useSet) {
354 DIEValue *Value = new DIESectionOffset(Label, Section, isEH, useSet);
355 DIEValues.push_back(Value);
356 Die->addValue(Attribute, Form, Value);
359 /// addDelta - Add a label delta attribute data and value.
361 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
362 const DWLabel &Hi, const DWLabel &Lo) {
363 DIEValue *Value = new DIEDelta(Hi, Lo);
364 DIEValues.push_back(Value);
365 Die->addValue(Attribute, Form, Value);
368 /// addBlock - Add block data.
370 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
372 Block->ComputeSize(TD);
373 DIEValues.push_back(Block);
374 Die->addValue(Attribute, Block->BestForm(), Block);
377 /// addSourceLine - Add location information to specified debug information
379 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
380 // If there is no compile unit specified, don't add a line #.
381 if (V->getCompileUnit().isNull())
384 unsigned Line = V->getLineNumber();
385 unsigned FileID = findCompileUnit(V->getCompileUnit()).getID();
386 assert(FileID && "Invalid file id");
387 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
388 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
391 /// addSourceLine - Add location information to specified debug information
393 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
394 // If there is no compile unit specified, don't add a line #.
395 if (G->getCompileUnit().isNull())
398 unsigned Line = G->getLineNumber();
399 unsigned FileID = findCompileUnit(G->getCompileUnit()).getID();
400 assert(FileID && "Invalid file id");
401 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
402 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
405 /// addSourceLine - Add location information to specified debug information
407 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
408 // If there is no compile unit specified, don't add a line #.
409 if (SP->getCompileUnit().isNull())
411 // If the line number is 0, don't add it.
412 if (SP->getLineNumber() == 0)
416 unsigned Line = SP->getLineNumber();
417 unsigned FileID = findCompileUnit(SP->getCompileUnit()).getID();
418 assert(FileID && "Invalid file id");
419 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
420 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
423 /// addSourceLine - Add location information to specified debug information
425 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
426 // If there is no compile unit specified, don't add a line #.
427 DICompileUnit CU = Ty->getCompileUnit();
431 unsigned Line = Ty->getLineNumber();
432 unsigned FileID = findCompileUnit(CU).getID();
433 assert(FileID && "Invalid file id");
434 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
435 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
438 /* Byref variables, in Blocks, are declared by the programmer as
439 "SomeType VarName;", but the compiler creates a
440 __Block_byref_x_VarName struct, and gives the variable VarName
441 either the struct, or a pointer to the struct, as its type. This
442 is necessary for various behind-the-scenes things the compiler
443 needs to do with by-reference variables in blocks.
445 However, as far as the original *programmer* is concerned, the
446 variable should still have type 'SomeType', as originally declared.
448 The following function dives into the __Block_byref_x_VarName
449 struct to find the original type of the variable. This will be
450 passed back to the code generating the type for the Debug
451 Information Entry for the variable 'VarName'. 'VarName' will then
452 have the original type 'SomeType' in its debug information.
454 The original type 'SomeType' will be the type of the field named
455 'VarName' inside the __Block_byref_x_VarName struct.
457 NOTE: In order for this to not completely fail on the debugger
458 side, the Debug Information Entry for the variable VarName needs to
459 have a DW_AT_location that tells the debugger how to unwind through
460 the pointers and __Block_byref_x_VarName struct to find the actual
461 value of the variable. The function addBlockByrefType does this. */
463 /// Find the type the programmer originally declared the variable to be
464 /// and return that type.
466 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
469 unsigned tag = Ty.getTag();
471 if (tag == dwarf::DW_TAG_pointer_type) {
472 DIDerivedType DTy = DIDerivedType(Ty.getNode());
473 subType = DTy.getTypeDerivedFrom();
476 DICompositeType blockStruct = DICompositeType(subType.getNode());
478 DIArray Elements = blockStruct.getTypeArray();
480 if (Elements.isNull())
483 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
484 DIDescriptor Element = Elements.getElement(i);
485 DIDerivedType DT = DIDerivedType(Element.getNode());
486 if (strcmp(Name.c_str(), DT.getName()) == 0)
487 return (DT.getTypeDerivedFrom());
493 /// addComplexAddress - Start with the address based on the location provided,
494 /// and generate the DWARF information necessary to find the actual variable
495 /// given the extra address information encoded in the DIVariable, starting from
496 /// the starting location. Add the DWARF information to the die.
498 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
500 const MachineLocation &Location) {
501 const DIVariable &VD = DV->getVariable();
502 DIType Ty = VD.getType();
504 // Decode the original location, and use that as the start of the byref
505 // variable's location.
506 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
507 DIEBlock *Block = new DIEBlock();
509 if (Location.isReg()) {
511 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
513 Reg = Reg - dwarf::DW_OP_reg0;
514 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
515 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
519 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
521 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
522 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
525 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
528 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
529 uint64_t Element = VD.getAddrElement(i);
531 if (Element == DIFactory::OpPlus) {
532 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
533 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
534 } else if (Element == DIFactory::OpDeref) {
535 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
536 } else llvm_unreachable("unknown DIFactory Opcode");
539 // Now attach the location information to the DIE.
540 addBlock(Die, Attribute, 0, Block);
543 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
544 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
545 gives the variable VarName either the struct, or a pointer to the struct, as
546 its type. This is necessary for various behind-the-scenes things the
547 compiler needs to do with by-reference variables in Blocks.
549 However, as far as the original *programmer* is concerned, the variable
550 should still have type 'SomeType', as originally declared.
552 The function getBlockByrefType dives into the __Block_byref_x_VarName
553 struct to find the original type of the variable, which is then assigned to
554 the variable's Debug Information Entry as its real type. So far, so good.
555 However now the debugger will expect the variable VarName to have the type
556 SomeType. So we need the location attribute for the variable to be an
557 expression that explains to the debugger how to navigate through the
558 pointers and struct to find the actual variable of type SomeType.
560 The following function does just that. We start by getting
561 the "normal" location for the variable. This will be the location
562 of either the struct __Block_byref_x_VarName or the pointer to the
563 struct __Block_byref_x_VarName.
565 The struct will look something like:
567 struct __Block_byref_x_VarName {
569 struct __Block_byref_x_VarName *forwarding;
570 ... <various other fields>
572 ... <maybe more fields>
575 If we are given the struct directly (as our starting point) we
576 need to tell the debugger to:
578 1). Add the offset of the forwarding field.
580 2). Follow that pointer to get the the real __Block_byref_x_VarName
581 struct to use (the real one may have been copied onto the heap).
583 3). Add the offset for the field VarName, to find the actual variable.
585 If we started with a pointer to the struct, then we need to
586 dereference that pointer first, before the other steps.
587 Translating this into DWARF ops, we will need to append the following
588 to the current location description for the variable:
590 DW_OP_deref -- optional, if we start with a pointer
591 DW_OP_plus_uconst <forward_fld_offset>
593 DW_OP_plus_uconst <varName_fld_offset>
595 That is what this function does. */
597 /// addBlockByrefAddress - Start with the address based on the location
598 /// provided, and generate the DWARF information necessary to find the
599 /// actual Block variable (navigating the Block struct) based on the
600 /// starting location. Add the DWARF information to the die. For
601 /// more information, read large comment just above here.
603 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
605 const MachineLocation &Location) {
606 const DIVariable &VD = DV->getVariable();
607 DIType Ty = VD.getType();
609 unsigned Tag = Ty.getTag();
610 bool isPointer = false;
612 const char *varName = VD.getName();
614 if (Tag == dwarf::DW_TAG_pointer_type) {
615 DIDerivedType DTy = DIDerivedType(Ty.getNode());
616 TmpTy = DTy.getTypeDerivedFrom();
620 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
622 // Find the __forwarding field and the variable field in the __Block_byref
624 DIArray Fields = blockStruct.getTypeArray();
625 DIDescriptor varField = DIDescriptor();
626 DIDescriptor forwardingField = DIDescriptor();
629 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
630 DIDescriptor Element = Fields.getElement(i);
631 DIDerivedType DT = DIDerivedType(Element.getNode());
632 const char *fieldName = DT.getName();
633 if (strcmp(fieldName, "__forwarding") == 0)
634 forwardingField = Element;
635 else if (strcmp(fieldName, varName) == 0)
639 assert(!varField.isNull() && "Can't find byref variable in Block struct");
640 assert(!forwardingField.isNull()
641 && "Can't find forwarding field in Block struct");
643 // Get the offsets for the forwarding field and the variable field.
644 unsigned int forwardingFieldOffset =
645 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
646 unsigned int varFieldOffset =
647 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
649 // Decode the original location, and use that as the start of the byref
650 // variable's location.
651 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
652 DIEBlock *Block = new DIEBlock();
654 if (Location.isReg()) {
656 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
658 Reg = Reg - dwarf::DW_OP_reg0;
659 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
660 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
664 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
666 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
667 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
670 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
673 // If we started with a pointer to the __Block_byref... struct, then
674 // the first thing we need to do is dereference the pointer (DW_OP_deref).
676 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
678 // Next add the offset for the '__forwarding' field:
679 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
680 // adding the offset if it's 0.
681 if (forwardingFieldOffset > 0) {
682 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
683 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
686 // Now dereference the __forwarding field to get to the real __Block_byref
687 // struct: DW_OP_deref.
688 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
690 // Now that we've got the real __Block_byref... struct, add the offset
691 // for the variable's field to get to the location of the actual variable:
692 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
693 if (varFieldOffset > 0) {
694 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
695 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
698 // Now attach the location information to the DIE.
699 addBlock(Die, Attribute, 0, Block);
702 /// addAddress - Add an address attribute to a die based on the location
704 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
705 const MachineLocation &Location) {
706 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
707 DIEBlock *Block = new DIEBlock();
709 if (Location.isReg()) {
711 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
713 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
714 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
718 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
720 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
721 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
724 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
727 addBlock(Die, Attribute, 0, Block);
730 /// addType - Add a new type attribute to the specified entity.
731 void DwarfDebug::addType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
735 // Check for pre-existence.
736 DIEEntry *Entry = DW_Unit->getDIEEntry(Ty.getNode());
738 // If it exists then use the existing value.
740 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
745 Entry = createDIEEntry();
746 DW_Unit->insertDIEEntry(Ty.getNode(), Entry);
749 DIE *Buffer = new DIE(dwarf::DW_TAG_base_type);
750 if (Ty.isBasicType())
751 constructTypeDIE(DW_Unit, *Buffer, DIBasicType(Ty.getNode()));
752 else if (Ty.isCompositeType())
753 constructTypeDIE(DW_Unit, *Buffer, DICompositeType(Ty.getNode()));
755 assert(Ty.isDerivedType() && "Unknown kind of DIType");
756 constructTypeDIE(DW_Unit, *Buffer, DIDerivedType(Ty.getNode()));
759 // Add debug information entry to entity and appropriate context.
761 DIDescriptor Context = Ty.getContext();
762 if (!Context.isNull())
763 Die = DW_Unit->getDIE(Context.getNode());
766 Die->addChild(Buffer);
768 DW_Unit->addDie(Buffer);
769 Entry->setEntry(Buffer);
770 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
773 /// constructTypeDIE - Construct basic type die from DIBasicType.
774 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
776 // Get core information.
777 const char *Name = BTy.getName();
778 Buffer.setTag(dwarf::DW_TAG_base_type);
779 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
782 // Add name if not anonymous or intermediate type.
784 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
785 uint64_t Size = BTy.getSizeInBits() >> 3;
786 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
789 /// constructTypeDIE - Construct derived type die from DIDerivedType.
790 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
792 // Get core information.
793 const char *Name = DTy.getName();
794 uint64_t Size = DTy.getSizeInBits() >> 3;
795 unsigned Tag = DTy.getTag();
797 // FIXME - Workaround for templates.
798 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
802 // Map to main type, void will not have a type.
803 DIType FromTy = DTy.getTypeDerivedFrom();
804 addType(DW_Unit, &Buffer, FromTy);
806 // Add name if not anonymous or intermediate type.
807 if (Name && Tag != dwarf::DW_TAG_pointer_type)
808 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
810 // Add size if non-zero (derived types might be zero-sized.)
812 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
814 // Add source line info if available and TyDesc is not a forward declaration.
815 if (!DTy.isForwardDecl() && Tag != dwarf::DW_TAG_pointer_type)
816 addSourceLine(&Buffer, &DTy);
819 /// constructTypeDIE - Construct type DIE from DICompositeType.
820 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
821 DICompositeType CTy) {
822 // Get core information.
823 const char *Name = CTy.getName();
825 uint64_t Size = CTy.getSizeInBits() >> 3;
826 unsigned Tag = CTy.getTag();
830 case dwarf::DW_TAG_vector_type:
831 case dwarf::DW_TAG_array_type:
832 constructArrayTypeDIE(DW_Unit, Buffer, &CTy);
834 case dwarf::DW_TAG_enumeration_type: {
835 DIArray Elements = CTy.getTypeArray();
837 // Add enumerators to enumeration type.
838 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
840 DIEnumerator Enum(Elements.getElement(i).getNode());
841 if (!Enum.isNull()) {
842 ElemDie = constructEnumTypeDIE(DW_Unit, &Enum);
843 Buffer.addChild(ElemDie);
848 case dwarf::DW_TAG_subroutine_type: {
850 DIArray Elements = CTy.getTypeArray();
851 DIDescriptor RTy = Elements.getElement(0);
852 addType(DW_Unit, &Buffer, DIType(RTy.getNode()));
854 // Add prototype flag.
855 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
858 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
859 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
860 DIDescriptor Ty = Elements.getElement(i);
861 addType(DW_Unit, Arg, DIType(Ty.getNode()));
862 Buffer.addChild(Arg);
866 case dwarf::DW_TAG_structure_type:
867 case dwarf::DW_TAG_union_type:
868 case dwarf::DW_TAG_class_type: {
869 // Add elements to structure type.
870 DIArray Elements = CTy.getTypeArray();
872 // A forward struct declared type may not have elements available.
873 if (Elements.isNull())
876 // Add elements to structure type.
877 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
878 DIDescriptor Element = Elements.getElement(i);
879 if (Element.isNull())
882 if (Element.getTag() == dwarf::DW_TAG_subprogram)
883 ElemDie = createSubprogramDIE(DW_Unit,
884 DISubprogram(Element.getNode()));
886 ElemDie = createMemberDIE(DW_Unit,
887 DIDerivedType(Element.getNode()));
888 Buffer.addChild(ElemDie);
891 if (CTy.isAppleBlockExtension())
892 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
894 unsigned RLang = CTy.getRunTimeLang();
896 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
897 dwarf::DW_FORM_data1, RLang);
904 // Add name if not anonymous or intermediate type.
906 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
908 if (Tag == dwarf::DW_TAG_enumeration_type ||
909 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
910 // Add size if non-zero (derived types might be zero-sized.)
912 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
914 // Add zero size if it is not a forward declaration.
915 if (CTy.isForwardDecl())
916 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
918 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
921 // Add source line info if available.
922 if (!CTy.isForwardDecl())
923 addSourceLine(&Buffer, &CTy);
927 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
928 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
929 int64_t L = SR.getLo();
930 int64_t H = SR.getHi();
931 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
933 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
935 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
937 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
939 Buffer.addChild(DW_Subrange);
942 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
943 void DwarfDebug::constructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
944 DICompositeType *CTy) {
945 Buffer.setTag(dwarf::DW_TAG_array_type);
946 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
947 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
949 // Emit derived type.
950 addType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
951 DIArray Elements = CTy->getTypeArray();
953 // Get an anonymous type for index type.
954 DIE *IdxTy = DW_Unit->getIndexTyDie();
956 // Construct an anonymous type for index type.
957 IdxTy = new DIE(dwarf::DW_TAG_base_type);
958 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
959 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
960 dwarf::DW_ATE_signed);
961 DW_Unit->addDie(IdxTy);
962 DW_Unit->setIndexTyDie(IdxTy);
965 // Add subranges to array type.
966 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
967 DIDescriptor Element = Elements.getElement(i);
968 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
969 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
973 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
974 DIE *DwarfDebug::constructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
975 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
976 const char *Name = ETy->getName();
977 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
978 int64_t Value = ETy->getEnumValue();
979 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
983 /// createGlobalVariableDIE - Create new DIE using GV.
984 DIE *DwarfDebug::createGlobalVariableDIE(CompileUnit *DW_Unit,
985 const DIGlobalVariable &GV) {
986 // If the global variable was optmized out then no need to create debug info
988 if (!GV.getGlobal()) return NULL;
989 if (!GV.getDisplayName()) return NULL;
991 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
992 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
993 GV.getDisplayName());
995 const char *LinkageName = GV.getLinkageName();
997 // Skip special LLVM prefix that is used to inform the asm printer to not
998 // emit usual symbol prefix before the symbol name. This happens for
999 // Objective-C symbol names and symbol whose name is replaced using GCC's
1000 // __asm__ attribute.
1001 if (LinkageName[0] == 1)
1002 LinkageName = &LinkageName[1];
1003 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1006 addType(DW_Unit, GVDie, GV.getType());
1007 if (!GV.isLocalToUnit())
1008 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1009 addSourceLine(GVDie, &GV);
1012 DIEBlock *Block = new DIEBlock();
1013 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1014 addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1015 Asm->Mang->getMangledName(GV.getGlobal()));
1016 addBlock(GVDie, dwarf::DW_AT_location, 0, Block);
1021 /// createMemberDIE - Create new member DIE.
1022 DIE *DwarfDebug::createMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
1023 DIE *MemberDie = new DIE(DT.getTag());
1024 if (const char *Name = DT.getName())
1025 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1027 addType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1029 addSourceLine(MemberDie, &DT);
1031 DIEBlock *MemLocationDie = new DIEBlock();
1032 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1034 uint64_t Size = DT.getSizeInBits();
1035 uint64_t FieldSize = DT.getOriginalTypeSize();
1037 if (Size != FieldSize) {
1039 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1040 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1042 uint64_t Offset = DT.getOffsetInBits();
1043 uint64_t FieldOffset = Offset;
1044 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1045 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1046 FieldOffset = (HiMark - FieldSize);
1047 Offset -= FieldOffset;
1049 // Maybe we need to work from the other end.
1050 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1051 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1053 // Here WD_AT_data_member_location points to the anonymous
1054 // field that includes this bit field.
1055 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1058 // This is not a bitfield.
1059 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1061 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1063 if (DT.isProtected())
1064 addUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1065 dwarf::DW_ACCESS_protected);
1066 else if (DT.isPrivate())
1067 addUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
1068 dwarf::DW_ACCESS_private);
1073 /// createSubprogramDIE - Create new DIE using SP.
1074 DIE *DwarfDebug::createSubprogramDIE(CompileUnit *DW_Unit,
1075 const DISubprogram &SP,
1078 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1080 const char * Name = SP.getName();
1081 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1083 const char *LinkageName = SP.getLinkageName();
1085 // Skip special LLVM prefix that is used to inform the asm printer to not
1086 // emit usual symbol prefix before the symbol name. This happens for
1087 // Objective-C symbol names and symbol whose name is replaced using GCC's
1088 // __asm__ attribute.
1089 if (LinkageName[0] == 1)
1090 LinkageName = &LinkageName[1];
1091 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1094 addSourceLine(SPDie, &SP);
1096 DICompositeType SPTy = SP.getType();
1097 DIArray Args = SPTy.getTypeArray();
1099 // Add prototyped tag, if C or ObjC.
1100 unsigned Lang = SP.getCompileUnit().getLanguage();
1101 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1102 Lang == dwarf::DW_LANG_ObjC)
1103 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1106 unsigned SPTag = SPTy.getTag();
1107 if (!IsConstructor) {
1108 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1109 addType(DW_Unit, SPDie, SPTy);
1111 addType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
1114 if (!SP.isDefinition()) {
1115 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1117 // Add arguments. Do not add arguments for subprogram definition. They will
1118 // be handled through RecordVariable.
1119 if (SPTag == dwarf::DW_TAG_subroutine_type)
1120 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1121 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1122 addType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1123 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1124 SPDie->addChild(Arg);
1128 // DW_TAG_inlined_subroutine may refer to this DIE.
1129 DW_Unit->insertDIE(SP.getNode(), SPDie);
1133 /// findCompileUnit - Get the compile unit for the given descriptor.
1135 CompileUnit &DwarfDebug::findCompileUnit(DICompileUnit Unit) const {
1136 DenseMap<Value *, CompileUnit *>::const_iterator I =
1137 CompileUnitMap.find(Unit.getNode());
1138 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1142 /// createDbgScopeVariable - Create a new scope variable.
1144 DIE *DwarfDebug::createDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1145 // Get the descriptor.
1146 const DIVariable &VD = DV->getVariable();
1147 const char *Name = VD.getName();
1151 // Translate tag to proper Dwarf tag. The result variable is dropped for
1154 switch (VD.getTag()) {
1155 case dwarf::DW_TAG_return_variable:
1157 case dwarf::DW_TAG_arg_variable:
1158 Tag = dwarf::DW_TAG_formal_parameter;
1160 case dwarf::DW_TAG_auto_variable: // fall thru
1162 Tag = dwarf::DW_TAG_variable;
1166 // Define variable debug information entry.
1167 DIE *VariableDie = new DIE(Tag);
1168 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1170 // Add source line info if available.
1171 addSourceLine(VariableDie, &VD);
1173 // Add variable type.
1174 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1175 // addresses instead.
1176 if (VD.isBlockByrefVariable())
1177 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name));
1179 addType(Unit, VariableDie, VD.getType());
1181 // Add variable address.
1182 // Variables for abstract instances of inlined functions don't get a
1184 MachineLocation Location;
1186 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1187 Location.set(FrameReg, Offset);
1190 if (VD.hasComplexAddress())
1191 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1192 else if (VD.isBlockByrefVariable())
1193 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1195 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1200 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1201 /// Initialize scope and update scope hierarchy.
1202 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1203 MDNode *InlinedAt) {
1204 assert (N && "Invalid Scope encoding!");
1205 assert (MI && "Missing machine instruction!");
1206 bool GetConcreteScope = (MI && InlinedAt);
1208 DbgScope *NScope = NULL;
1211 NScope = DbgScopeMap.lookup(InlinedAt);
1213 NScope = DbgScopeMap.lookup(N);
1214 assert (NScope && "Unable to find working scope!");
1216 if (NScope->getFirstInsn())
1219 DbgScope *Parent = NULL;
1220 if (GetConcreteScope) {
1221 DILocation IL(InlinedAt);
1222 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1223 IL.getOrigLocation().getNode());
1224 assert (Parent && "Unable to find Parent scope!");
1225 NScope->setParent(Parent);
1226 Parent->addScope(NScope);
1227 } else if (DIDescriptor(N).isLexicalBlock()) {
1228 DILexicalBlock DB(N);
1229 if (!DB.getContext().isNull()) {
1230 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1231 NScope->setParent(Parent);
1232 Parent->addScope(NScope);
1236 NScope->setFirstInsn(MI);
1238 if (!Parent && !InlinedAt) {
1239 StringRef SPName = DISubprogram(N).getLinkageName();
1240 if (SPName == MF->getFunction()->getName())
1241 CurrentFnDbgScope = NScope;
1244 if (GetConcreteScope) {
1245 ConcreteScopes[InlinedAt] = NScope;
1246 getOrCreateAbstractScope(N);
1252 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1253 assert (N && "Invalid Scope encoding!");
1255 DbgScope *AScope = AbstractScopes.lookup(N);
1259 DbgScope *Parent = NULL;
1261 DIDescriptor Scope(N);
1262 if (Scope.isLexicalBlock()) {
1263 DILexicalBlock DB(N);
1264 DIDescriptor ParentDesc = DB.getContext();
1265 if (!ParentDesc.isNull())
1266 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1269 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1272 Parent->addScope(AScope);
1273 AScope->setAbstractScope();
1274 AbstractScopes[N] = AScope;
1275 if (DIDescriptor(N).isSubprogram())
1276 AbstractScopesList.push_back(AScope);
1280 static DISubprogram getDISubprogram(MDNode *N) {
1284 return DISubprogram();
1286 if (D.isCompileUnit())
1287 return DISubprogram();
1289 if (D.isSubprogram())
1290 return DISubprogram(N);
1292 if (D.isLexicalBlock())
1293 return getDISubprogram(DILexicalBlock(N).getContext().getNode());
1295 llvm_unreachable("Unexpected Descriptor!");
1298 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1299 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1300 /// If there are global variables in this scope then create and insert
1301 /// DIEs for these variables.
1302 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1304 DIE *SPDie = ModuleCU->getDIE(SPNode);
1305 assert (SPDie && "Unable to find subprogram DIE!");
1306 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1307 DWLabel("func_begin", SubprogramCount));
1308 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1309 DWLabel("func_end", SubprogramCount));
1310 MachineLocation Location(RI->getFrameRegister(*MF));
1311 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1313 if (!DISubprogram(SPNode).isLocalToUnit())
1314 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1316 // If there are global variables at this scope then add their dies.
1317 for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(),
1318 SGE = ScopedGVs.end(); SGI != SGE; ++SGI) {
1319 MDNode *N = dyn_cast_or_null<MDNode>(*SGI);
1321 DIGlobalVariable GV(N);
1322 if (GV.getContext().getNode() == SPNode) {
1323 DIE *ScopedGVDie = createGlobalVariableDIE(ModuleCU, GV);
1325 SPDie->addChild(ScopedGVDie);
1331 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1332 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1333 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1334 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1335 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1337 // Ignore empty scopes.
1338 if (StartID == EndID && StartID != 0)
1341 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1342 if (Scope->isAbstractScope())
1345 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1347 DWLabel("label", StartID)
1348 : DWLabel("func_begin", SubprogramCount));
1349 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1351 DWLabel("label", EndID)
1352 : DWLabel("func_end", SubprogramCount));
1359 /// constructInlinedScopeDIE - This scope represents inlined body of
1360 /// a function. Construct DIE to represent this concrete inlined copy
1361 /// of the function.
1362 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1363 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1364 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1365 assert (StartID && "Invalid starting label for an inlined scope!");
1366 assert (EndID && "Invalid end label for an inlined scope!");
1367 // Ignore empty scopes.
1368 if (StartID == EndID && StartID != 0)
1371 DIScope DS(Scope->getScopeNode());
1374 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1376 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1377 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1378 assert (OriginDIE && "Unable to find Origin DIE!");
1379 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1380 dwarf::DW_FORM_ref4, OriginDIE);
1382 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1383 DWLabel("label", StartID));
1384 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1385 DWLabel("label", EndID));
1387 InlinedSubprogramDIEs.insert(OriginDIE);
1389 // Track the start label for this inlined function.
1390 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1391 I = InlineInfo.find(InlinedSP.getNode());
1393 if (I == InlineInfo.end()) {
1394 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID,
1396 InlinedSPNodes.push_back(InlinedSP.getNode());
1398 I->second.push_back(std::make_pair(StartID, ScopeDIE));
1400 StringPool.insert(InlinedSP.getName());
1401 StringPool.insert(InlinedSP.getLinkageName());
1402 DILocation DL(Scope->getInlinedAt());
1403 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1404 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1410 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1411 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV,
1412 DbgScope *Scope, CompileUnit *Unit) {
1413 // Get the descriptor.
1414 const DIVariable &VD = DV->getVariable();
1415 const char *Name = VD.getName();
1419 // Translate tag to proper Dwarf tag. The result variable is dropped for
1422 switch (VD.getTag()) {
1423 case dwarf::DW_TAG_return_variable:
1425 case dwarf::DW_TAG_arg_variable:
1426 Tag = dwarf::DW_TAG_formal_parameter;
1428 case dwarf::DW_TAG_auto_variable: // fall thru
1430 Tag = dwarf::DW_TAG_variable;
1434 // Define variable debug information entry.
1435 DIE *VariableDie = new DIE(Tag);
1439 if (DbgVariable *AV = DV->getAbstractVariable())
1440 AbsDIE = AV->getDIE();
1443 DIScope DS(Scope->getScopeNode());
1444 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1445 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1447 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1448 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1449 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1450 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1451 dwarf::DW_FORM_ref4, AbsDIE);
1454 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1455 addSourceLine(VariableDie, &VD);
1457 // Add variable type.
1458 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1459 // addresses instead.
1460 if (VD.isBlockByrefVariable())
1461 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name));
1463 addType(Unit, VariableDie, VD.getType());
1466 // Add variable address.
1467 if (!Scope->isAbstractScope()) {
1468 MachineLocation Location;
1470 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1471 Location.set(FrameReg, Offset);
1473 if (VD.hasComplexAddress())
1474 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1475 else if (VD.isBlockByrefVariable())
1476 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1478 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1480 DV->setDIE(VariableDie);
1485 /// constructScopeDIE - Construct a DIE for this scope.
1486 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1489 DIScope DS(Scope->getScopeNode());
1493 DIE *ScopeDIE = NULL;
1494 if (Scope->getInlinedAt())
1495 ScopeDIE = constructInlinedScopeDIE(Scope);
1496 else if (DS.isSubprogram()) {
1497 if (Scope->isAbstractScope())
1498 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1500 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1503 ScopeDIE = constructLexicalScopeDIE(Scope);
1504 if (!ScopeDIE) return NULL;
1507 // Add variables to scope.
1508 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1509 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1510 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope, ModuleCU);
1512 ScopeDIE->addChild(VariableDIE);
1515 // Add nested scopes.
1516 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1517 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1518 // Define the Scope debug information entry.
1519 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1521 ScopeDIE->addChild(NestedDIE);
1526 /// GetOrCreateSourceID - Look up the source id with the given directory and
1527 /// source file names. If none currently exists, create a new id and insert it
1528 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1530 unsigned DwarfDebug::GetOrCreateSourceID(const char *DirName,
1531 const char *FileName) {
1533 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1534 if (DI != DirectoryIdMap.end()) {
1535 DId = DI->getValue();
1537 DId = DirectoryNames.size() + 1;
1538 DirectoryIdMap[DirName] = DId;
1539 DirectoryNames.push_back(DirName);
1543 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1544 if (FI != SourceFileIdMap.end()) {
1545 FId = FI->getValue();
1547 FId = SourceFileNames.size() + 1;
1548 SourceFileIdMap[FileName] = FId;
1549 SourceFileNames.push_back(FileName);
1552 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1553 SourceIdMap.find(std::make_pair(DId, FId));
1554 if (SI != SourceIdMap.end())
1557 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1558 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1559 SourceIds.push_back(std::make_pair(DId, FId));
1564 void DwarfDebug::constructCompileUnit(MDNode *N) {
1565 DICompileUnit DIUnit(N);
1566 const char *FN = DIUnit.getFilename();
1567 const char *Dir = DIUnit.getDirectory();
1568 unsigned ID = GetOrCreateSourceID(Dir, FN);
1570 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1571 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1572 DWLabel("section_line", 0), DWLabel("section_line", 0),
1574 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1575 DIUnit.getProducer());
1576 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1577 DIUnit.getLanguage());
1578 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1581 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1582 if (DIUnit.isOptimized())
1583 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1585 if (const char *Flags = DIUnit.getFlags())
1586 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1588 unsigned RVer = DIUnit.getRunTimeVersion();
1590 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1591 dwarf::DW_FORM_data1, RVer);
1593 CompileUnit *Unit = new CompileUnit(ID, Die);
1594 if (!ModuleCU && DIUnit.isMain()) {
1595 // Use first compile unit marked as isMain as the compile unit
1600 CompileUnitMap[DIUnit.getNode()] = Unit;
1601 CompileUnits.push_back(Unit);
1604 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1605 DIGlobalVariable DI_GV(N);
1607 // If debug information is malformed then ignore it.
1608 if (DI_GV.Verify() == false)
1611 // Check for pre-existence.
1612 if (ModuleCU->getDIE(DI_GV.getNode()))
1615 DIE *VariableDie = createGlobalVariableDIE(ModuleCU, DI_GV);
1618 ModuleCU->insertDIE(N, VariableDie);
1620 // Add to context owner.
1621 ModuleCU->getCUDie()->addChild(VariableDie);
1623 // Expose as global. FIXME - need to check external flag.
1624 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1628 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1631 // Check for pre-existence.
1632 if (ModuleCU->getDIE(N))
1635 if (!SP.isDefinition())
1636 // This is a method declaration which will be handled while constructing
1640 DIE *SubprogramDie = createSubprogramDIE(ModuleCU, SP);
1643 ModuleCU->insertDIE(N, SubprogramDie);
1645 // Add to context owner.
1646 ModuleCU->getCUDie()->addChild(SubprogramDie);
1648 // Expose as global.
1649 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1653 /// beginModule - Emit all Dwarf sections that should come prior to the
1654 /// content. Create global DIEs and emit initial debug info sections.
1655 /// This is inovked by the target AsmPrinter.
1656 void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1659 if (TimePassesIsEnabled)
1660 DebugTimer->startTimer();
1662 if (!MAI->doesSupportDebugInformation())
1665 DebugInfoFinder DbgFinder;
1666 DbgFinder.processModule(*M);
1668 // Create all the compile unit DIEs.
1669 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1670 E = DbgFinder.compile_unit_end(); I != E; ++I)
1671 constructCompileUnit(*I);
1673 if (CompileUnits.empty()) {
1674 if (TimePassesIsEnabled)
1675 DebugTimer->stopTimer();
1680 // If main compile unit for this module is not seen than randomly
1681 // select first compile unit.
1683 ModuleCU = CompileUnits[0];
1685 // Create DIEs for each of the externally visible global variables.
1686 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1687 E = DbgFinder.global_variable_end(); I != E; ++I) {
1688 DIGlobalVariable GV(*I);
1689 if (GV.getContext().getNode() != GV.getCompileUnit().getNode())
1690 ScopedGVs.push_back(*I);
1692 constructGlobalVariableDIE(*I);
1695 // Create DIEs for each subprogram.
1696 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1697 E = DbgFinder.subprogram_end(); I != E; ++I)
1698 constructSubprogramDIE(*I);
1702 MMI->setDebugInfoAvailability(true);
1704 // Prime section data.
1705 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1707 // Print out .file directives to specify files for .loc directives. These are
1708 // printed out early so that they precede any .loc directives.
1709 if (MAI->hasDotLocAndDotFile()) {
1710 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1711 // Remember source id starts at 1.
1712 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1713 sys::Path FullPath(getSourceDirectoryName(Id.first));
1715 FullPath.appendComponent(getSourceFileName(Id.second));
1716 assert(AppendOk && "Could not append filename to directory!");
1718 Asm->EmitFile(i, FullPath.str());
1723 // Emit initial sections
1726 if (TimePassesIsEnabled)
1727 DebugTimer->stopTimer();
1730 /// endModule - Emit all Dwarf sections that should come after the content.
1732 void DwarfDebug::endModule() {
1736 if (TimePassesIsEnabled)
1737 DebugTimer->startTimer();
1739 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1740 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1741 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1743 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1746 // Standard sections final addresses.
1747 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1748 EmitLabel("text_end", 0);
1749 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1750 EmitLabel("data_end", 0);
1752 // End text sections.
1753 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1754 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1755 EmitLabel("section_end", i);
1758 // Emit common frame information.
1759 emitCommonDebugFrame();
1761 // Emit function debug frame information
1762 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1763 E = DebugFrames.end(); I != E; ++I)
1764 emitFunctionDebugFrame(*I);
1766 // Compute DIE offsets and sizes.
1767 computeSizeAndOffsets();
1769 // Emit all the DIEs into a debug info section
1772 // Corresponding abbreviations into a abbrev section.
1773 emitAbbreviations();
1775 // Emit source line correspondence into a debug line section.
1778 // Emit info into a debug pubnames section.
1779 emitDebugPubNames();
1781 // Emit info into a debug str section.
1784 // Emit info into a debug loc section.
1787 // Emit info into a debug aranges section.
1790 // Emit info into a debug ranges section.
1793 // Emit info into a debug macinfo section.
1796 // Emit inline info.
1797 emitDebugInlineInfo();
1799 if (TimePassesIsEnabled)
1800 DebugTimer->stopTimer();
1803 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1804 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1806 DILocation &ScopeLoc) {
1808 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1810 return AbsDbgVariable;
1812 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1816 AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1817 Scope->addVariable(AbsDbgVariable);
1818 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1819 return AbsDbgVariable;
1822 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1823 void DwarfDebug::collectVariableInfo() {
1826 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1827 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1828 VE = VMap.end(); VI != VE; ++VI) {
1829 MetadataBase *MB = VI->first;
1830 MDNode *Var = dyn_cast_or_null<MDNode>(MB);
1832 DIVariable DV (Var);
1833 std::pair< unsigned, MDNode *> VP = VI->second;
1834 DILocation ScopeLoc(VP.second);
1837 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1839 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1840 // If variable scope is not found then skip this variable.
1844 DbgVariable *RegVar = new DbgVariable(DV, VP.first);
1845 Scope->addVariable(RegVar);
1846 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first,
1848 RegVar->setAbstractVariable(AbsDbgVariable);
1852 /// beginScope - Process beginning of a scope starting at Label.
1853 void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) {
1854 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1855 if (I == DbgScopeBeginMap.end())
1857 ScopeVector &SD = DbgScopeBeginMap[MI];
1858 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1860 (*SDI)->setStartLabelID(Label);
1863 /// endScope - Process end of a scope.
1864 void DwarfDebug::endScope(const MachineInstr *MI) {
1865 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1866 if (I == DbgScopeEndMap.end())
1869 unsigned Label = MMI->NextLabelID();
1870 Asm->printLabel(Label);
1872 SmallVector<DbgScope *, 2> &SD = I->second;
1873 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1875 (*SDI)->setEndLabelID(Label);
1879 /// createDbgScope - Create DbgScope for the scope.
1880 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1883 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1886 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1887 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1888 if (DIDescriptor(Scope).isLexicalBlock())
1889 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
1893 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1897 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1898 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1899 DILocation DL(InlinedAt);
1900 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
1903 /// extractScopeInformation - Scan machine instructions in this function
1904 /// and collect DbgScopes. Return true, if atleast one scope was found.
1905 bool DwarfDebug::extractScopeInformation(MachineFunction *MF) {
1906 // If scope information was extracted using .dbg intrinsics then there is not
1907 // any need to extract these information by scanning each instruction.
1908 if (!DbgScopeMap.empty())
1911 // Scan each instruction and create scopes. First build working set of scopes.
1912 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1914 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1916 const MachineInstr *MInsn = II;
1917 DebugLoc DL = MInsn->getDebugLoc();
1918 if (DL.isUnknown()) continue;
1919 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1920 if (!DLT.Scope) continue;
1921 // There is no need to create another DIE for compile unit. For all
1922 // other scopes, create one DbgScope now. This will be translated
1923 // into a scope DIE at the end.
1924 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
1925 createDbgScope(DLT.Scope, DLT.InlinedAtLoc);
1930 // Build scope hierarchy using working set of scopes.
1931 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1933 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1935 const MachineInstr *MInsn = II;
1936 DebugLoc DL = MInsn->getDebugLoc();
1937 if (DL.isUnknown()) continue;
1938 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1939 if (!DLT.Scope) continue;
1940 // There is no need to create another DIE for compile unit. For all
1941 // other scopes, create one DbgScope now. This will be translated
1942 // into a scope DIE at the end.
1943 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
1944 DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
1945 Scope->setLastInsn(MInsn);
1949 // If a scope's last instruction is not set then use its child scope's
1950 // last instruction as this scope's last instrunction.
1951 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1952 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1953 if (DI->second->isAbstractScope())
1955 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
1956 DI->second->fixInstructionMarkers();
1957 assert (DI->second->getLastInsn() && "Invalid last instruction!");
1960 // Each scope has first instruction and last instruction to mark beginning
1961 // and end of a scope respectively. Create an inverse map that list scopes
1962 // starts (and ends) with an instruction. One instruction may start (or end)
1964 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1965 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1966 DbgScope *S = DI->second;
1967 if (S->isAbstractScope())
1969 const MachineInstr *MI = S->getFirstInsn();
1970 assert (MI && "DbgScope does not have first instruction!");
1972 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
1973 if (IDI != DbgScopeBeginMap.end())
1974 IDI->second.push_back(S);
1976 DbgScopeBeginMap[MI].push_back(S);
1978 MI = S->getLastInsn();
1979 assert (MI && "DbgScope does not have last instruction!");
1980 IDI = DbgScopeEndMap.find(MI);
1981 if (IDI != DbgScopeEndMap.end())
1982 IDI->second.push_back(S);
1984 DbgScopeEndMap[MI].push_back(S);
1987 return !DbgScopeMap.empty();
1990 /// beginFunction - Gather pre-function debug information. Assumes being
1991 /// emitted immediately after the function entry point.
1992 void DwarfDebug::beginFunction(MachineFunction *MF) {
1995 if (!ShouldEmitDwarfDebug()) return;
1997 if (TimePassesIsEnabled)
1998 DebugTimer->startTimer();
2000 if (!extractScopeInformation(MF))
2003 collectVariableInfo();
2005 // Begin accumulating function debug information.
2006 MMI->BeginFunction(MF);
2008 // Assumes in correct section after the entry point.
2009 EmitLabel("func_begin", ++SubprogramCount);
2011 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2013 DebugLoc FDL = MF->getDefaultDebugLoc();
2014 if (!FDL.isUnknown()) {
2015 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2016 unsigned LabelID = 0;
2017 DISubprogram SP = getDISubprogram(DLT.Scope);
2019 LabelID = recordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
2021 LabelID = recordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
2022 Asm->printLabel(LabelID);
2025 if (TimePassesIsEnabled)
2026 DebugTimer->stopTimer();
2029 /// endFunction - Gather and emit post-function debug information.
2031 void DwarfDebug::endFunction(MachineFunction *MF) {
2032 if (!ShouldEmitDwarfDebug()) return;
2034 if (TimePassesIsEnabled)
2035 DebugTimer->startTimer();
2037 if (DbgScopeMap.empty())
2040 // Define end label for subprogram.
2041 EmitLabel("func_end", SubprogramCount);
2043 // Get function line info.
2044 if (!Lines.empty()) {
2045 // Get section line info.
2046 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2047 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2048 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2049 // Append the function info to section info.
2050 SectionLineInfos.insert(SectionLineInfos.end(),
2051 Lines.begin(), Lines.end());
2054 // Construct abstract scopes.
2055 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2056 AE = AbstractScopesList.end(); AI != AE; ++AI)
2057 constructScopeDIE(*AI);
2059 constructScopeDIE(CurrentFnDbgScope);
2061 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2062 MMI->getFrameMoves()));
2065 if (CurrentFnDbgScope) {
2066 CurrentFnDbgScope = NULL;
2067 DbgScopeMap.clear();
2068 DbgScopeBeginMap.clear();
2069 DbgScopeEndMap.clear();
2070 ConcreteScopes.clear();
2071 AbstractScopesList.clear();
2076 if (TimePassesIsEnabled)
2077 DebugTimer->stopTimer();
2080 /// recordSourceLine - Records location information and associates it with a
2081 /// label. Returns a unique label ID used to generate a label and provide
2082 /// correspondence to the source line list.
2083 unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2088 if (TimePassesIsEnabled)
2089 DebugTimer->startTimer();
2091 const char *Dir = NULL;
2092 const char *Fn = NULL;
2094 DIDescriptor Scope(S);
2095 if (Scope.isCompileUnit()) {
2096 DICompileUnit CU(S);
2097 Dir = CU.getDirectory();
2098 Fn = CU.getFilename();
2099 } else if (Scope.isSubprogram()) {
2101 Dir = SP.getDirectory();
2102 Fn = SP.getFilename();
2103 } else if (Scope.isLexicalBlock()) {
2104 DILexicalBlock DB(S);
2105 Dir = DB.getDirectory();
2106 Fn = DB.getFilename();
2108 assert (0 && "Unexpected scope info");
2110 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2111 unsigned ID = MMI->NextLabelID();
2112 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2114 if (TimePassesIsEnabled)
2115 DebugTimer->stopTimer();
2120 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2121 /// timed. Look up the source id with the given directory and source file
2122 /// names. If none currently exists, create a new id and insert it in the
2123 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2125 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2126 const std::string &FileName) {
2127 if (TimePassesIsEnabled)
2128 DebugTimer->startTimer();
2130 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2132 if (TimePassesIsEnabled)
2133 DebugTimer->stopTimer();
2138 //===----------------------------------------------------------------------===//
2140 //===----------------------------------------------------------------------===//
2142 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2145 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2146 // Get the children.
2147 const std::vector<DIE *> &Children = Die->getChildren();
2149 // If not last sibling and has children then add sibling offset attribute.
2150 if (!Last && !Children.empty()) Die->addSiblingOffset();
2152 // Record the abbreviation.
2153 assignAbbrevNumber(Die->getAbbrev());
2155 // Get the abbreviation for this DIE.
2156 unsigned AbbrevNumber = Die->getAbbrevNumber();
2157 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2160 Die->setOffset(Offset);
2162 // Start the size with the size of abbreviation code.
2163 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2165 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2166 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2168 // Size the DIE attribute values.
2169 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2170 // Size attribute value.
2171 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2173 // Size the DIE children if any.
2174 if (!Children.empty()) {
2175 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2176 "Children flag not set");
2178 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2179 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2181 // End of children marker.
2182 Offset += sizeof(int8_t);
2185 Die->setSize(Offset - Die->getOffset());
2189 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2191 void DwarfDebug::computeSizeAndOffsets() {
2192 // Compute size of compile unit header.
2193 static unsigned Offset =
2194 sizeof(int32_t) + // Length of Compilation Unit Info
2195 sizeof(int16_t) + // DWARF version number
2196 sizeof(int32_t) + // Offset Into Abbrev. Section
2197 sizeof(int8_t); // Pointer Size (in bytes)
2199 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2200 CompileUnitOffsets[ModuleCU] = 0;
2203 /// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
2204 /// tools to recognize the object file contains Dwarf information.
2205 void DwarfDebug::emitInitial() {
2206 // Check to see if we already emitted intial headers.
2207 if (didInitial) return;
2210 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2212 // Dwarf sections base addresses.
2213 if (MAI->doesDwarfRequireFrameSection()) {
2214 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2215 EmitLabel("section_debug_frame", 0);
2218 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2219 EmitLabel("section_info", 0);
2220 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2221 EmitLabel("section_abbrev", 0);
2222 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2223 EmitLabel("section_aranges", 0);
2225 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2226 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2227 EmitLabel("section_macinfo", 0);
2230 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2231 EmitLabel("section_line", 0);
2232 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2233 EmitLabel("section_loc", 0);
2234 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2235 EmitLabel("section_pubnames", 0);
2236 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2237 EmitLabel("section_str", 0);
2238 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2239 EmitLabel("section_ranges", 0);
2241 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2242 EmitLabel("text_begin", 0);
2243 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2244 EmitLabel("data_begin", 0);
2247 /// emitDIE - Recusively Emits a debug information entry.
2249 void DwarfDebug::emitDIE(DIE *Die) {
2250 // Get the abbreviation for this DIE.
2251 unsigned AbbrevNumber = Die->getAbbrevNumber();
2252 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2256 // Emit the code (index) for the abbreviation.
2257 Asm->EmitULEB128Bytes(AbbrevNumber);
2259 if (Asm->isVerbose())
2260 Asm->EOL(std::string("Abbrev [" +
2261 utostr(AbbrevNumber) +
2262 "] 0x" + utohexstr(Die->getOffset()) +
2263 ":0x" + utohexstr(Die->getSize()) + " " +
2264 dwarf::TagString(Abbrev->getTag())));
2268 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2269 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2271 // Emit the DIE attribute values.
2272 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2273 unsigned Attr = AbbrevData[i].getAttribute();
2274 unsigned Form = AbbrevData[i].getForm();
2275 assert(Form && "Too many attributes for DIE (check abbreviation)");
2278 case dwarf::DW_AT_sibling:
2279 Asm->EmitInt32(Die->getSiblingOffset());
2281 case dwarf::DW_AT_abstract_origin: {
2282 DIEEntry *E = cast<DIEEntry>(Values[i]);
2283 DIE *Origin = E->getEntry();
2284 unsigned Addr = Origin->getOffset();
2285 Asm->EmitInt32(Addr);
2289 // Emit an attribute using the defined form.
2290 Values[i]->EmitValue(this, Form);
2294 Asm->EOL(dwarf::AttributeString(Attr));
2297 // Emit the DIE children if any.
2298 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2299 const std::vector<DIE *> &Children = Die->getChildren();
2301 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2302 emitDIE(Children[j]);
2304 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2308 /// emitDebugInfo / emitDebugInfoPerCU - Emit the debug info section.
2310 void DwarfDebug::emitDebugInfoPerCU(CompileUnit *Unit) {
2311 DIE *Die = Unit->getCUDie();
2313 // Emit the compile units header.
2314 EmitLabel("info_begin", Unit->getID());
2316 // Emit size of content not including length itself
2317 unsigned ContentSize = Die->getSize() +
2318 sizeof(int16_t) + // DWARF version number
2319 sizeof(int32_t) + // Offset Into Abbrev. Section
2320 sizeof(int8_t) + // Pointer Size (in bytes)
2321 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2323 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2324 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2325 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2326 Asm->EOL("Offset Into Abbrev. Section");
2327 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2330 // FIXME - extra padding for gdb bug.
2331 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2332 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2333 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2334 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2335 EmitLabel("info_end", Unit->getID());
2340 void DwarfDebug::emitDebugInfo() {
2341 // Start debug info section.
2342 Asm->OutStreamer.SwitchSection(
2343 Asm->getObjFileLowering().getDwarfInfoSection());
2345 emitDebugInfoPerCU(ModuleCU);
2348 /// emitAbbreviations - Emit the abbreviation section.
2350 void DwarfDebug::emitAbbreviations() const {
2351 // Check to see if it is worth the effort.
2352 if (!Abbreviations.empty()) {
2353 // Start the debug abbrev section.
2354 Asm->OutStreamer.SwitchSection(
2355 Asm->getObjFileLowering().getDwarfAbbrevSection());
2357 EmitLabel("abbrev_begin", 0);
2359 // For each abbrevation.
2360 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2361 // Get abbreviation data
2362 const DIEAbbrev *Abbrev = Abbreviations[i];
2364 // Emit the abbrevations code (base 1 index.)
2365 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2366 Asm->EOL("Abbreviation Code");
2368 // Emit the abbreviations data.
2374 // Mark end of abbreviations.
2375 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2377 EmitLabel("abbrev_end", 0);
2382 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2383 /// the line matrix.
2385 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2386 // Define last address of section.
2387 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2388 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2389 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2390 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2392 // Mark end of matrix.
2393 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2394 Asm->EmitULEB128Bytes(1); Asm->EOL();
2395 Asm->EmitInt8(1); Asm->EOL();
2398 /// emitDebugLines - Emit source line information.
2400 void DwarfDebug::emitDebugLines() {
2401 // If the target is using .loc/.file, the assembler will be emitting the
2402 // .debug_line table automatically.
2403 if (MAI->hasDotLocAndDotFile())
2406 // Minimum line delta, thus ranging from -10..(255-10).
2407 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2408 // Maximum line delta, thus ranging from -10..(255-10).
2409 const int MaxLineDelta = 255 + MinLineDelta;
2411 // Start the dwarf line section.
2412 Asm->OutStreamer.SwitchSection(
2413 Asm->getObjFileLowering().getDwarfLineSection());
2415 // Construct the section header.
2416 EmitDifference("line_end", 0, "line_begin", 0, true);
2417 Asm->EOL("Length of Source Line Info");
2418 EmitLabel("line_begin", 0);
2420 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2422 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2423 Asm->EOL("Prolog Length");
2424 EmitLabel("line_prolog_begin", 0);
2426 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2428 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2430 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2432 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2434 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2436 // Line number standard opcode encodings argument count
2437 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2438 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2439 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2440 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2441 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2442 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2443 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2444 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2445 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2447 // Emit directories.
2448 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2449 Asm->EmitString(getSourceDirectoryName(DI));
2450 Asm->EOL("Directory");
2453 Asm->EmitInt8(0); Asm->EOL("End of directories");
2456 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2457 // Remember source id starts at 1.
2458 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2459 Asm->EmitString(getSourceFileName(Id.second));
2461 Asm->EmitULEB128Bytes(Id.first);
2462 Asm->EOL("Directory #");
2463 Asm->EmitULEB128Bytes(0);
2464 Asm->EOL("Mod date");
2465 Asm->EmitULEB128Bytes(0);
2466 Asm->EOL("File size");
2469 Asm->EmitInt8(0); Asm->EOL("End of files");
2471 EmitLabel("line_prolog_end", 0);
2473 // A sequence for each text section.
2474 unsigned SecSrcLinesSize = SectionSourceLines.size();
2476 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2477 // Isolate current sections line info.
2478 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2480 /*if (Asm->isVerbose()) {
2481 const MCSection *S = SectionMap[j + 1];
2482 O << '\t' << MAI->getCommentString() << " Section"
2483 << S->getName() << '\n';
2487 // Dwarf assumes we start with first line of first source file.
2488 unsigned Source = 1;
2491 // Construct rows of the address, source, line, column matrix.
2492 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2493 const SrcLineInfo &LineInfo = LineInfos[i];
2494 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2495 if (!LabelID) continue;
2497 if (LineInfo.getLine() == 0) continue;
2499 if (!Asm->isVerbose())
2502 std::pair<unsigned, unsigned> SourceID =
2503 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2504 O << '\t' << MAI->getCommentString() << ' '
2505 << getSourceDirectoryName(SourceID.first) << ' '
2506 << getSourceFileName(SourceID.second)
2507 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2510 // Define the line address.
2511 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2512 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2513 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2514 EmitReference("label", LabelID); Asm->EOL("Location label");
2516 // If change of source, then switch to the new source.
2517 if (Source != LineInfo.getSourceID()) {
2518 Source = LineInfo.getSourceID();
2519 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2520 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2523 // If change of line.
2524 if (Line != LineInfo.getLine()) {
2525 // Determine offset.
2526 int Offset = LineInfo.getLine() - Line;
2527 int Delta = Offset - MinLineDelta;
2530 Line = LineInfo.getLine();
2532 // If delta is small enough and in range...
2533 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2534 // ... then use fast opcode.
2535 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2537 // ... otherwise use long hand.
2538 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2539 Asm->EOL("DW_LNS_advance_line");
2540 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2541 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2544 // Copy the previous row (different address or source)
2545 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2549 emitEndOfLineMatrix(j + 1);
2552 if (SecSrcLinesSize == 0)
2553 // Because we're emitting a debug_line section, we still need a line
2554 // table. The linker and friends expect it to exist. If there's nothing to
2555 // put into it, emit an empty table.
2556 emitEndOfLineMatrix(1);
2558 EmitLabel("line_end", 0);
2562 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2564 void DwarfDebug::emitCommonDebugFrame() {
2565 if (!MAI->doesDwarfRequireFrameSection())
2569 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2570 TargetFrameInfo::StackGrowsUp ?
2571 TD->getPointerSize() : -TD->getPointerSize();
2573 // Start the dwarf frame section.
2574 Asm->OutStreamer.SwitchSection(
2575 Asm->getObjFileLowering().getDwarfFrameSection());
2577 EmitLabel("debug_frame_common", 0);
2578 EmitDifference("debug_frame_common_end", 0,
2579 "debug_frame_common_begin", 0, true);
2580 Asm->EOL("Length of Common Information Entry");
2582 EmitLabel("debug_frame_common_begin", 0);
2583 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2584 Asm->EOL("CIE Identifier Tag");
2585 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2586 Asm->EOL("CIE Version");
2587 Asm->EmitString("");
2588 Asm->EOL("CIE Augmentation");
2589 Asm->EmitULEB128Bytes(1);
2590 Asm->EOL("CIE Code Alignment Factor");
2591 Asm->EmitSLEB128Bytes(stackGrowth);
2592 Asm->EOL("CIE Data Alignment Factor");
2593 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2594 Asm->EOL("CIE RA Column");
2596 std::vector<MachineMove> Moves;
2597 RI->getInitialFrameState(Moves);
2599 EmitFrameMoves(NULL, 0, Moves, false);
2601 Asm->EmitAlignment(2, 0, 0, false);
2602 EmitLabel("debug_frame_common_end", 0);
2607 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2610 DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2611 if (!MAI->doesDwarfRequireFrameSection())
2614 // Start the dwarf frame section.
2615 Asm->OutStreamer.SwitchSection(
2616 Asm->getObjFileLowering().getDwarfFrameSection());
2618 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2619 "debug_frame_begin", DebugFrameInfo.Number, true);
2620 Asm->EOL("Length of Frame Information Entry");
2622 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2624 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2626 Asm->EOL("FDE CIE offset");
2628 EmitReference("func_begin", DebugFrameInfo.Number);
2629 Asm->EOL("FDE initial location");
2630 EmitDifference("func_end", DebugFrameInfo.Number,
2631 "func_begin", DebugFrameInfo.Number);
2632 Asm->EOL("FDE address range");
2634 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2637 Asm->EmitAlignment(2, 0, 0, false);
2638 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2643 void DwarfDebug::emitDebugPubNamesPerCU(CompileUnit *Unit) {
2644 EmitDifference("pubnames_end", Unit->getID(),
2645 "pubnames_begin", Unit->getID(), true);
2646 Asm->EOL("Length of Public Names Info");
2648 EmitLabel("pubnames_begin", Unit->getID());
2650 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2652 EmitSectionOffset("info_begin", "section_info",
2653 Unit->getID(), 0, true, false);
2654 Asm->EOL("Offset of Compilation Unit Info");
2656 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2658 Asm->EOL("Compilation Unit Length");
2660 StringMap<DIE*> &Globals = Unit->getGlobals();
2661 for (StringMap<DIE*>::const_iterator
2662 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2663 const char *Name = GI->getKeyData();
2664 DIE * Entity = GI->second;
2666 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2667 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2670 Asm->EmitInt32(0); Asm->EOL("End Mark");
2671 EmitLabel("pubnames_end", Unit->getID());
2676 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2678 void DwarfDebug::emitDebugPubNames() {
2679 // Start the dwarf pubnames section.
2680 Asm->OutStreamer.SwitchSection(
2681 Asm->getObjFileLowering().getDwarfPubNamesSection());
2683 emitDebugPubNamesPerCU(ModuleCU);
2686 /// emitDebugStr - Emit visible names into a debug str section.
2688 void DwarfDebug::emitDebugStr() {
2689 // Check to see if it is worth the effort.
2690 if (!StringPool.empty()) {
2691 // Start the dwarf str section.
2692 Asm->OutStreamer.SwitchSection(
2693 Asm->getObjFileLowering().getDwarfStrSection());
2695 // For each of strings in the string pool.
2696 for (unsigned StringID = 1, N = StringPool.size();
2697 StringID <= N; ++StringID) {
2698 // Emit a label for reference from debug information entries.
2699 EmitLabel("string", StringID);
2701 // Emit the string itself.
2702 const std::string &String = StringPool[StringID];
2703 Asm->EmitString(String); Asm->EOL();
2710 /// emitDebugLoc - Emit visible names into a debug loc section.
2712 void DwarfDebug::emitDebugLoc() {
2713 // Start the dwarf loc section.
2714 Asm->OutStreamer.SwitchSection(
2715 Asm->getObjFileLowering().getDwarfLocSection());
2719 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2721 void DwarfDebug::EmitDebugARanges() {
2722 // Start the dwarf aranges section.
2723 Asm->OutStreamer.SwitchSection(
2724 Asm->getObjFileLowering().getDwarfARangesSection());
2728 CompileUnit *Unit = GetBaseCompileUnit();
2730 // Don't include size of length
2731 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2733 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2735 EmitReference("info_begin", Unit->getID());
2736 Asm->EOL("Offset of Compilation Unit Info");
2738 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2740 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2742 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2743 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2746 EmitReference("text_begin", 0); Asm->EOL("Address");
2747 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2749 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2750 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2756 /// emitDebugRanges - Emit visible names into a debug ranges section.
2758 void DwarfDebug::emitDebugRanges() {
2759 // Start the dwarf ranges section.
2760 Asm->OutStreamer.SwitchSection(
2761 Asm->getObjFileLowering().getDwarfRangesSection());
2765 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2767 void DwarfDebug::emitDebugMacInfo() {
2768 if (const MCSection *LineInfo =
2769 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2770 // Start the dwarf macinfo section.
2771 Asm->OutStreamer.SwitchSection(LineInfo);
2776 /// emitDebugInlineInfo - Emit inline info using following format.
2778 /// 1. length of section
2779 /// 2. Dwarf version number
2780 /// 3. address size.
2782 /// Entries (one "entry" for each function that was inlined):
2784 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2785 /// otherwise offset into __debug_str for regular function name.
2786 /// 2. offset into __debug_str section for regular function name.
2787 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2788 /// instances for the function.
2790 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2791 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2792 /// __debug_info section, and the low_pc is the starting address for the
2793 /// inlining instance.
2794 void DwarfDebug::emitDebugInlineInfo() {
2795 if (!MAI->doesDwarfUsesInlineInfoSection())
2801 Asm->OutStreamer.SwitchSection(
2802 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2804 EmitDifference("debug_inlined_end", 1,
2805 "debug_inlined_begin", 1, true);
2806 Asm->EOL("Length of Debug Inlined Information Entry");
2808 EmitLabel("debug_inlined_begin", 1);
2810 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2811 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2813 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2814 E = InlinedSPNodes.end(); I != E; ++I) {
2816 // for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
2817 // I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2819 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2820 = InlineInfo.find(Node);
2821 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2822 DISubprogram SP(Node);
2823 const char *LName = SP.getLinkageName();
2824 const char *Name = SP.getName();
2827 Asm->EmitString(Name);
2829 // Skip special LLVM prefix that is used to inform the asm printer to not
2830 // emit usual symbol prefix before the symbol name. This happens for
2831 // Objective-C symbol names and symbol whose name is replaced using GCC's
2832 // __asm__ attribute.
2835 // Asm->EmitString(LName);
2836 EmitSectionOffset("string", "section_str",
2837 StringPool.idFor(LName), false, true);
2840 Asm->EOL("MIPS linkage name");
2841 // Asm->EmitString(Name);
2842 EmitSectionOffset("string", "section_str",
2843 StringPool.idFor(Name), false, true);
2844 Asm->EOL("Function name");
2845 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2847 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2848 LE = Labels.end(); LI != LE; ++LI) {
2849 DIE *SP = LI->second;
2850 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2852 if (TD->getPointerSize() == sizeof(int32_t))
2853 O << MAI->getData32bitsDirective();
2855 O << MAI->getData64bitsDirective();
2857 PrintLabelName("label", LI->first); Asm->EOL("low_pc");
2861 EmitLabel("debug_inlined_end", 1);