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;
75 /// GlobalTypes - A map of globally visible types for this unit.
77 StringMap<DIE*> GlobalTypes;
80 CompileUnit(unsigned I, DIE *D)
81 : ID(I), CUDie(D), IndexTyDie(0) {}
82 ~CompileUnit() { delete CUDie; delete IndexTyDie; }
85 unsigned getID() const { return ID; }
86 DIE* getCUDie() const { return CUDie; }
87 const StringMap<DIE*> &getGlobals() const { return Globals; }
88 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
90 /// hasContent - Return true if this compile unit has something to write out.
92 bool hasContent() const { return !CUDie->getChildren().empty(); }
94 /// addGlobal - Add a new global entity to the compile unit.
96 void addGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
98 /// addGlobalType - Add a new global type to the compile unit.
100 void addGlobalType(const std::string &Name, DIE *Die) {
101 GlobalTypes[Name] = Die;
104 /// getDIE - Returns the debug information entry map slot for the
105 /// specified debug variable.
106 DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
108 /// insertDIE - Insert DIE into the map.
109 void insertDIE(MDNode *N, DIE *D) {
110 GVToDieMap.insert(std::make_pair(N, D));
113 /// getDIEEntry - Returns the debug information entry for the speciefied
115 DIEEntry *getDIEEntry(MDNode *N) { return GVToDIEEntryMap.lookup(N); }
117 /// insertDIEEntry - Insert debug information entry into the map.
118 void insertDIEEntry(MDNode *N, DIEEntry *E) {
119 GVToDIEEntryMap.insert(std::make_pair(N, E));
122 /// addDie - Adds or interns the DIE to the compile unit.
124 void addDie(DIE *Buffer) {
125 this->CUDie->addChild(Buffer);
128 // getIndexTyDie - Get an anonymous type for index type.
129 DIE *getIndexTyDie() {
133 // setIndexTyDie - Set D as anonymous type for index which can be reused
135 void setIndexTyDie(DIE *D) {
141 //===----------------------------------------------------------------------===//
142 /// DbgVariable - This class is used to track local variable information.
145 DIVariable Var; // Variable Descriptor.
146 unsigned FrameIndex; // Variable frame index.
147 DbgVariable *AbstractVar; // Abstract variable for this variable.
150 DbgVariable(DIVariable V, unsigned I)
151 : Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0) {}
154 DIVariable getVariable() const { return Var; }
155 unsigned getFrameIndex() const { return FrameIndex; }
156 void setAbstractVariable(DbgVariable *V) { AbstractVar = V; }
157 DbgVariable *getAbstractVariable() const { return AbstractVar; }
158 void setDIE(DIE *D) { TheDIE = D; }
159 DIE *getDIE() const { return TheDIE; }
162 //===----------------------------------------------------------------------===//
163 /// DbgScope - This class is used to track scope information.
166 DbgScope *Parent; // Parent to this scope.
167 DIDescriptor Desc; // Debug info descriptor for scope.
168 WeakVH InlinedAtLocation; // Location at which scope is inlined.
169 bool AbstractScope; // Abstract Scope
170 unsigned StartLabelID; // Label ID of the beginning of scope.
171 unsigned EndLabelID; // Label ID of the end of scope.
172 const MachineInstr *LastInsn; // Last instruction of this scope.
173 const MachineInstr *FirstInsn; // First instruction of this scope.
174 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
175 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
177 // Private state for dump()
178 mutable unsigned IndentLevel;
180 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
181 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
182 StartLabelID(0), EndLabelID(0),
183 LastInsn(0), FirstInsn(0), IndentLevel(0) {}
187 DbgScope *getParent() const { return Parent; }
188 void setParent(DbgScope *P) { Parent = P; }
189 DIDescriptor getDesc() const { return Desc; }
190 MDNode *getInlinedAt() const {
191 return dyn_cast_or_null<MDNode>(InlinedAtLocation);
193 MDNode *getScopeNode() const { return Desc.getNode(); }
194 unsigned getStartLabelID() const { return StartLabelID; }
195 unsigned getEndLabelID() const { return EndLabelID; }
196 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
197 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
198 void setStartLabelID(unsigned S) { StartLabelID = S; }
199 void setEndLabelID(unsigned E) { EndLabelID = E; }
200 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
201 const MachineInstr *getLastInsn() { return LastInsn; }
202 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
203 void setAbstractScope() { AbstractScope = true; }
204 bool isAbstractScope() const { return AbstractScope; }
205 const MachineInstr *getFirstInsn() { return FirstInsn; }
207 /// addScope - Add a scope to the scope.
209 void addScope(DbgScope *S) { Scopes.push_back(S); }
211 /// addVariable - Add a variable to the scope.
213 void addVariable(DbgVariable *V) { Variables.push_back(V); }
215 void fixInstructionMarkers() {
216 assert (getFirstInsn() && "First instruction is missing!");
220 // If a scope does not have an instruction to mark an end then use
221 // the end of last child scope.
222 SmallVector<DbgScope *, 4> &Scopes = getScopes();
223 assert (!Scopes.empty() && "Inner most scope does not have last insn!");
224 DbgScope *L = Scopes.back();
225 if (!L->getLastInsn())
226 L->fixInstructionMarkers();
227 setLastInsn(L->getLastInsn());
236 void DbgScope::dump() const {
237 raw_ostream &err = errs();
238 err.indent(IndentLevel);
239 MDNode *N = Desc.getNode();
241 err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
243 err << "Abstract Scope\n";
247 err << "Children ...\n";
248 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
249 if (Scopes[i] != this)
256 DbgScope::~DbgScope() {
257 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
259 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
263 } // end llvm namespace
265 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
266 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
267 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
268 DIEValues(), StringPool(),
269 SectionSourceLines(), didInitial(false), shouldEmit(false),
270 CurrentFnDbgScope(0), DebugTimer(0) {
271 if (TimePassesIsEnabled)
272 DebugTimer = new Timer("Dwarf Debug Writer",
273 getDwarfTimerGroup());
275 DwarfDebug::~DwarfDebug() {
276 for (unsigned j = 0, M = DIEValues.size(); j < M; ++j)
282 /// assignAbbrevNumber - Define a unique number for the abbreviation.
284 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
285 // Profile the node so that we can make it unique.
289 // Check the set for priors.
290 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
292 // If it's newly added.
293 if (InSet == &Abbrev) {
294 // Add to abbreviation list.
295 Abbreviations.push_back(&Abbrev);
297 // Assign the vector position + 1 as its number.
298 Abbrev.setNumber(Abbreviations.size());
300 // Assign existing abbreviation number.
301 Abbrev.setNumber(InSet->getNumber());
305 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
306 /// information entry.
307 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
308 DIEEntry *Value = new DIEEntry(Entry);
309 DIEValues.push_back(Value);
313 /// addUInt - Add an unsigned integer attribute data and value.
315 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
316 unsigned Form, uint64_t Integer) {
317 if (!Form) Form = DIEInteger::BestForm(false, Integer);
318 DIEValue *Value = new DIEInteger(Integer);
319 DIEValues.push_back(Value);
320 Die->addValue(Attribute, Form, Value);
323 /// addSInt - Add an signed integer attribute data and value.
325 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
326 unsigned Form, int64_t Integer) {
327 if (!Form) Form = DIEInteger::BestForm(true, Integer);
328 DIEValue *Value = new DIEInteger(Integer);
329 DIEValues.push_back(Value);
330 Die->addValue(Attribute, Form, Value);
333 /// addString - Add a string attribute data and value. DIEString only
334 /// keeps string reference.
335 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
336 const StringRef String) {
337 DIEValue *Value = new DIEString(String);
338 DIEValues.push_back(Value);
339 Die->addValue(Attribute, Form, Value);
342 /// addLabel - Add a Dwarf label attribute data and value.
344 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
345 const DWLabel &Label) {
346 DIEValue *Value = new DIEDwarfLabel(Label);
347 DIEValues.push_back(Value);
348 Die->addValue(Attribute, Form, Value);
351 /// addObjectLabel - Add an non-Dwarf label attribute data and value.
353 void DwarfDebug::addObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
354 const std::string &Label) {
355 DIEValue *Value = new DIEObjectLabel(Label);
356 DIEValues.push_back(Value);
357 Die->addValue(Attribute, Form, Value);
360 /// addSectionOffset - Add a section offset label attribute data and value.
362 void DwarfDebug::addSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
363 const DWLabel &Label, const DWLabel &Section,
364 bool isEH, bool useSet) {
365 DIEValue *Value = new DIESectionOffset(Label, Section, isEH, useSet);
366 DIEValues.push_back(Value);
367 Die->addValue(Attribute, Form, Value);
370 /// addDelta - Add a label delta attribute data and value.
372 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
373 const DWLabel &Hi, const DWLabel &Lo) {
374 DIEValue *Value = new DIEDelta(Hi, Lo);
375 DIEValues.push_back(Value);
376 Die->addValue(Attribute, Form, Value);
379 /// addBlock - Add block data.
381 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
383 Block->ComputeSize(TD);
384 DIEValues.push_back(Block);
385 Die->addValue(Attribute, Block->BestForm(), Block);
388 /// addSourceLine - Add location information to specified debug information
390 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
391 // If there is no compile unit specified, don't add a line #.
392 if (V->getCompileUnit().isNull())
395 unsigned Line = V->getLineNumber();
396 unsigned FileID = findCompileUnit(V->getCompileUnit()).getID();
397 assert(FileID && "Invalid file id");
398 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
399 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
402 /// addSourceLine - Add location information to specified debug information
404 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
405 // If there is no compile unit specified, don't add a line #.
406 if (G->getCompileUnit().isNull())
409 unsigned Line = G->getLineNumber();
410 unsigned FileID = findCompileUnit(G->getCompileUnit()).getID();
411 assert(FileID && "Invalid file id");
412 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
413 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
416 /// addSourceLine - Add location information to specified debug information
418 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
419 // If there is no compile unit specified, don't add a line #.
420 if (SP->getCompileUnit().isNull())
422 // If the line number is 0, don't add it.
423 if (SP->getLineNumber() == 0)
427 unsigned Line = SP->getLineNumber();
428 unsigned FileID = findCompileUnit(SP->getCompileUnit()).getID();
429 assert(FileID && "Invalid file id");
430 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
431 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
434 /// addSourceLine - Add location information to specified debug information
436 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
437 // If there is no compile unit specified, don't add a line #.
438 DICompileUnit CU = Ty->getCompileUnit();
442 unsigned Line = Ty->getLineNumber();
443 unsigned FileID = findCompileUnit(CU).getID();
444 assert(FileID && "Invalid file id");
445 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
446 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
449 /// addSourceLine - Add location information to specified debug information
451 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
452 // If there is no compile unit specified, don't add a line #.
453 if (NS->getCompileUnit().isNull())
456 unsigned Line = NS->getLineNumber();
457 StringRef FN = NS->getFilename();
458 StringRef Dir = NS->getDirectory();
460 unsigned FileID = GetOrCreateSourceID(Dir, FN);
461 assert(FileID && "Invalid file id");
462 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
463 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
466 /* Byref variables, in Blocks, are declared by the programmer as
467 "SomeType VarName;", but the compiler creates a
468 __Block_byref_x_VarName struct, and gives the variable VarName
469 either the struct, or a pointer to the struct, as its type. This
470 is necessary for various behind-the-scenes things the compiler
471 needs to do with by-reference variables in blocks.
473 However, as far as the original *programmer* is concerned, the
474 variable should still have type 'SomeType', as originally declared.
476 The following function dives into the __Block_byref_x_VarName
477 struct to find the original type of the variable. This will be
478 passed back to the code generating the type for the Debug
479 Information Entry for the variable 'VarName'. 'VarName' will then
480 have the original type 'SomeType' in its debug information.
482 The original type 'SomeType' will be the type of the field named
483 'VarName' inside the __Block_byref_x_VarName struct.
485 NOTE: In order for this to not completely fail on the debugger
486 side, the Debug Information Entry for the variable VarName needs to
487 have a DW_AT_location that tells the debugger how to unwind through
488 the pointers and __Block_byref_x_VarName struct to find the actual
489 value of the variable. The function addBlockByrefType does this. */
491 /// Find the type the programmer originally declared the variable to be
492 /// and return that type.
494 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
497 unsigned tag = Ty.getTag();
499 if (tag == dwarf::DW_TAG_pointer_type) {
500 DIDerivedType DTy = DIDerivedType(Ty.getNode());
501 subType = DTy.getTypeDerivedFrom();
504 DICompositeType blockStruct = DICompositeType(subType.getNode());
506 DIArray Elements = blockStruct.getTypeArray();
508 if (Elements.isNull())
511 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
512 DIDescriptor Element = Elements.getElement(i);
513 DIDerivedType DT = DIDerivedType(Element.getNode());
514 if (Name == DT.getName())
515 return (DT.getTypeDerivedFrom());
521 /// addComplexAddress - Start with the address based on the location provided,
522 /// and generate the DWARF information necessary to find the actual variable
523 /// given the extra address information encoded in the DIVariable, starting from
524 /// the starting location. Add the DWARF information to the die.
526 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
528 const MachineLocation &Location) {
529 const DIVariable &VD = DV->getVariable();
530 DIType Ty = VD.getType();
532 // Decode the original location, and use that as the start of the byref
533 // variable's location.
534 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
535 DIEBlock *Block = new DIEBlock();
537 if (Location.isReg()) {
539 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
541 Reg = Reg - dwarf::DW_OP_reg0;
542 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
543 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
547 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
549 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
550 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
553 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
556 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
557 uint64_t Element = VD.getAddrElement(i);
559 if (Element == DIFactory::OpPlus) {
560 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
561 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
562 } else if (Element == DIFactory::OpDeref) {
563 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
564 } else llvm_unreachable("unknown DIFactory Opcode");
567 // Now attach the location information to the DIE.
568 addBlock(Die, Attribute, 0, Block);
571 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
572 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
573 gives the variable VarName either the struct, or a pointer to the struct, as
574 its type. This is necessary for various behind-the-scenes things the
575 compiler needs to do with by-reference variables in Blocks.
577 However, as far as the original *programmer* is concerned, the variable
578 should still have type 'SomeType', as originally declared.
580 The function getBlockByrefType dives into the __Block_byref_x_VarName
581 struct to find the original type of the variable, which is then assigned to
582 the variable's Debug Information Entry as its real type. So far, so good.
583 However now the debugger will expect the variable VarName to have the type
584 SomeType. So we need the location attribute for the variable to be an
585 expression that explains to the debugger how to navigate through the
586 pointers and struct to find the actual variable of type SomeType.
588 The following function does just that. We start by getting
589 the "normal" location for the variable. This will be the location
590 of either the struct __Block_byref_x_VarName or the pointer to the
591 struct __Block_byref_x_VarName.
593 The struct will look something like:
595 struct __Block_byref_x_VarName {
597 struct __Block_byref_x_VarName *forwarding;
598 ... <various other fields>
600 ... <maybe more fields>
603 If we are given the struct directly (as our starting point) we
604 need to tell the debugger to:
606 1). Add the offset of the forwarding field.
608 2). Follow that pointer to get the the real __Block_byref_x_VarName
609 struct to use (the real one may have been copied onto the heap).
611 3). Add the offset for the field VarName, to find the actual variable.
613 If we started with a pointer to the struct, then we need to
614 dereference that pointer first, before the other steps.
615 Translating this into DWARF ops, we will need to append the following
616 to the current location description for the variable:
618 DW_OP_deref -- optional, if we start with a pointer
619 DW_OP_plus_uconst <forward_fld_offset>
621 DW_OP_plus_uconst <varName_fld_offset>
623 That is what this function does. */
625 /// addBlockByrefAddress - Start with the address based on the location
626 /// provided, and generate the DWARF information necessary to find the
627 /// actual Block variable (navigating the Block struct) based on the
628 /// starting location. Add the DWARF information to the die. For
629 /// more information, read large comment just above here.
631 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
633 const MachineLocation &Location) {
634 const DIVariable &VD = DV->getVariable();
635 DIType Ty = VD.getType();
637 unsigned Tag = Ty.getTag();
638 bool isPointer = false;
640 StringRef varName = VD.getName();
642 if (Tag == dwarf::DW_TAG_pointer_type) {
643 DIDerivedType DTy = DIDerivedType(Ty.getNode());
644 TmpTy = DTy.getTypeDerivedFrom();
648 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
650 // Find the __forwarding field and the variable field in the __Block_byref
652 DIArray Fields = blockStruct.getTypeArray();
653 DIDescriptor varField = DIDescriptor();
654 DIDescriptor forwardingField = DIDescriptor();
657 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
658 DIDescriptor Element = Fields.getElement(i);
659 DIDerivedType DT = DIDerivedType(Element.getNode());
660 StringRef fieldName = DT.getName();
661 if (fieldName == "__forwarding")
662 forwardingField = Element;
663 else if (fieldName == varName)
667 assert(!varField.isNull() && "Can't find byref variable in Block struct");
668 assert(!forwardingField.isNull()
669 && "Can't find forwarding field in Block struct");
671 // Get the offsets for the forwarding field and the variable field.
672 unsigned int forwardingFieldOffset =
673 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
674 unsigned int varFieldOffset =
675 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
677 // Decode the original location, and use that as the start of the byref
678 // variable's location.
679 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
680 DIEBlock *Block = new DIEBlock();
682 if (Location.isReg()) {
684 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
686 Reg = Reg - dwarf::DW_OP_reg0;
687 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
688 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
692 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
694 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
695 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
698 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
701 // If we started with a pointer to the __Block_byref... struct, then
702 // the first thing we need to do is dereference the pointer (DW_OP_deref).
704 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
706 // Next add the offset for the '__forwarding' field:
707 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
708 // adding the offset if it's 0.
709 if (forwardingFieldOffset > 0) {
710 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
711 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
714 // Now dereference the __forwarding field to get to the real __Block_byref
715 // struct: DW_OP_deref.
716 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
718 // Now that we've got the real __Block_byref... struct, add the offset
719 // for the variable's field to get to the location of the actual variable:
720 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
721 if (varFieldOffset > 0) {
722 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
723 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
726 // Now attach the location information to the DIE.
727 addBlock(Die, Attribute, 0, Block);
730 /// addAddress - Add an address attribute to a die based on the location
732 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
733 const MachineLocation &Location) {
734 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
735 DIEBlock *Block = new DIEBlock();
737 if (Location.isReg()) {
739 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
741 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
742 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
746 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
748 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
749 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
752 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
755 addBlock(Die, Attribute, 0, Block);
758 /// addType - Add a new type attribute to the specified entity.
759 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
763 // Check for pre-existence.
764 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
766 // If it exists then use the existing value.
768 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
773 Entry = createDIEEntry();
774 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
777 DIE *Buffer = new DIE(dwarf::DW_TAG_base_type);
778 ModuleCU->insertDIE(Ty.getNode(), Buffer);
779 if (Ty.isBasicType())
780 constructTypeDIE(*Buffer, DIBasicType(Ty.getNode()));
781 else if (Ty.isCompositeType())
782 constructTypeDIE(*Buffer, DICompositeType(Ty.getNode()));
784 assert(Ty.isDerivedType() && "Unknown kind of DIType");
785 constructTypeDIE(*Buffer, DIDerivedType(Ty.getNode()));
788 // Add debug information entry to entity and appropriate context.
790 DIDescriptor Context = Ty.getContext();
791 if (!Context.isNull()) {
792 if (Context.isNameSpace()) {
793 DINameSpace NS(Context.getNode());
794 Die = getOrCreateNameSpace(NS);
796 Die = ModuleCU->getDIE(Context.getNode());
799 Die->addChild(Buffer);
801 ModuleCU->addDie(Buffer);
802 Entry->setEntry(Buffer);
803 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
806 /// constructTypeDIE - Construct basic type die from DIBasicType.
807 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
808 // Get core information.
809 StringRef Name = BTy.getName();
810 Buffer.setTag(dwarf::DW_TAG_base_type);
811 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
814 // Add name if not anonymous or intermediate type.
816 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
817 uint64_t Size = BTy.getSizeInBits() >> 3;
818 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
821 /// constructTypeDIE - Construct derived type die from DIDerivedType.
822 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
823 // Get core information.
824 StringRef Name = DTy.getName();
825 uint64_t Size = DTy.getSizeInBits() >> 3;
826 unsigned Tag = DTy.getTag();
828 // FIXME - Workaround for templates.
829 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
833 // Map to main type, void will not have a type.
834 DIType FromTy = DTy.getTypeDerivedFrom();
835 addType(&Buffer, FromTy);
837 // Add name if not anonymous or intermediate type.
839 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
841 // Add size if non-zero (derived types might be zero-sized.)
843 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
845 // Add source line info if available and TyDesc is not a forward declaration.
846 if (!DTy.isForwardDecl())
847 addSourceLine(&Buffer, &DTy);
850 /// constructTypeDIE - Construct type DIE from DICompositeType.
851 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
852 // Get core information.
853 StringRef Name = CTy.getName();
855 uint64_t Size = CTy.getSizeInBits() >> 3;
856 unsigned Tag = CTy.getTag();
860 case dwarf::DW_TAG_vector_type:
861 case dwarf::DW_TAG_array_type:
862 constructArrayTypeDIE(Buffer, &CTy);
864 case dwarf::DW_TAG_enumeration_type: {
865 DIArray Elements = CTy.getTypeArray();
867 // Add enumerators to enumeration type.
868 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
870 DIEnumerator Enum(Elements.getElement(i).getNode());
871 if (!Enum.isNull()) {
872 ElemDie = constructEnumTypeDIE(&Enum);
873 Buffer.addChild(ElemDie);
878 case dwarf::DW_TAG_subroutine_type: {
880 DIArray Elements = CTy.getTypeArray();
881 DIDescriptor RTy = Elements.getElement(0);
882 addType(&Buffer, DIType(RTy.getNode()));
884 // Add prototype flag.
885 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
888 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
889 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
890 DIDescriptor Ty = Elements.getElement(i);
891 addType(Arg, DIType(Ty.getNode()));
892 Buffer.addChild(Arg);
896 case dwarf::DW_TAG_structure_type:
897 case dwarf::DW_TAG_union_type:
898 case dwarf::DW_TAG_class_type: {
899 // Add elements to structure type.
900 DIArray Elements = CTy.getTypeArray();
902 // A forward struct declared type may not have elements available.
903 if (Elements.isNull())
906 // Add elements to structure type.
907 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
908 DIDescriptor Element = Elements.getElement(i);
909 if (Element.isNull())
912 if (Element.getTag() == dwarf::DW_TAG_subprogram)
913 ElemDie = createMemberSubprogramDIE(DISubprogram(Element.getNode()));
915 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
916 Buffer.addChild(ElemDie);
919 if (CTy.isAppleBlockExtension())
920 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
922 unsigned RLang = CTy.getRunTimeLang();
924 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
925 dwarf::DW_FORM_data1, RLang);
932 // Add name if not anonymous or intermediate type.
934 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
936 if (Tag == dwarf::DW_TAG_enumeration_type ||
937 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
938 // Add size if non-zero (derived types might be zero-sized.)
940 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
942 // Add zero size if it is not a forward declaration.
943 if (CTy.isForwardDecl())
944 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
946 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
949 // Add source line info if available.
950 if (!CTy.isForwardDecl())
951 addSourceLine(&Buffer, &CTy);
955 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
956 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
957 int64_t L = SR.getLo();
958 int64_t H = SR.getHi();
959 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
961 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
963 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
964 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
966 Buffer.addChild(DW_Subrange);
969 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
970 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
971 DICompositeType *CTy) {
972 Buffer.setTag(dwarf::DW_TAG_array_type);
973 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
974 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
976 // Emit derived type.
977 addType(&Buffer, CTy->getTypeDerivedFrom());
978 DIArray Elements = CTy->getTypeArray();
980 // Get an anonymous type for index type.
981 DIE *IdxTy = ModuleCU->getIndexTyDie();
983 // Construct an anonymous type for index type.
984 IdxTy = new DIE(dwarf::DW_TAG_base_type);
985 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
986 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
987 dwarf::DW_ATE_signed);
988 ModuleCU->addDie(IdxTy);
989 ModuleCU->setIndexTyDie(IdxTy);
992 // Add subranges to array type.
993 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
994 DIDescriptor Element = Elements.getElement(i);
995 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
996 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1000 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1001 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator *ETy) {
1002 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1003 StringRef Name = ETy->getName();
1004 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1005 int64_t Value = ETy->getEnumValue();
1006 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1010 /// createGlobalVariableDIE - Create new DIE using GV.
1011 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1012 // If the global variable was optmized out then no need to create debug info
1014 if (!GV.getGlobal()) return NULL;
1015 if (GV.getDisplayName().empty()) return NULL;
1017 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1018 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1019 GV.getDisplayName());
1021 StringRef LinkageName = GV.getLinkageName();
1022 if (!LinkageName.empty()) {
1023 // Skip special LLVM prefix that is used to inform the asm printer to not
1024 // emit usual symbol prefix before the symbol name. This happens for
1025 // Objective-C symbol names and symbol whose name is replaced using GCC's
1026 // __asm__ attribute.
1027 if (LinkageName[0] == 1)
1028 LinkageName = LinkageName.substr(1);
1029 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1032 addType(GVDie, GV.getType());
1033 if (!GV.isLocalToUnit())
1034 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1035 addSourceLine(GVDie, &GV);
1038 DIEBlock *Block = new DIEBlock();
1039 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1040 addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1041 Asm->Mang->getMangledName(GV.getGlobal()));
1042 addBlock(GVDie, dwarf::DW_AT_location, 0, Block);
1047 /// createMemberDIE - Create new member DIE.
1048 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1049 DIE *MemberDie = new DIE(DT.getTag());
1050 StringRef Name = DT.getName();
1052 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1054 addType(MemberDie, DT.getTypeDerivedFrom());
1056 addSourceLine(MemberDie, &DT);
1058 DIEBlock *MemLocationDie = new DIEBlock();
1059 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1061 uint64_t Size = DT.getSizeInBits();
1062 uint64_t FieldSize = DT.getOriginalTypeSize();
1064 if (Size != FieldSize) {
1066 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1067 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1069 uint64_t Offset = DT.getOffsetInBits();
1070 uint64_t FieldOffset = Offset;
1071 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1072 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1073 FieldOffset = (HiMark - FieldSize);
1074 Offset -= FieldOffset;
1076 // Maybe we need to work from the other end.
1077 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1078 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1080 // Here WD_AT_data_member_location points to the anonymous
1081 // field that includes this bit field.
1082 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1085 // This is not a bitfield.
1086 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1088 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1090 if (DT.isProtected())
1091 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1092 dwarf::DW_ACCESS_protected);
1093 else if (DT.isPrivate())
1094 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1095 dwarf::DW_ACCESS_private);
1096 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1097 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1098 dwarf::DW_ACCESS_public);
1100 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1101 dwarf::DW_VIRTUALITY_virtual);
1105 /// createRawSubprogramDIE - Create new partially incomplete DIE. This is
1106 /// a helper routine used by createMemberSubprogramDIE and
1107 /// createSubprogramDIE.
1108 DIE *DwarfDebug::createRawSubprogramDIE(const DISubprogram &SP) {
1109 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1110 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1112 StringRef LinkageName = SP.getLinkageName();
1113 if (!LinkageName.empty()) {
1114 // Skip special LLVM prefix that is used to inform the asm printer to not
1115 // emit usual symbol prefix before the symbol name. This happens for
1116 // Objective-C symbol names and symbol whose name is replaced using GCC's
1117 // __asm__ attribute.
1118 if (LinkageName[0] == 1)
1119 LinkageName = LinkageName.substr(1);
1120 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1123 addSourceLine(SPDie, &SP);
1125 // Add prototyped tag, if C or ObjC.
1126 unsigned Lang = SP.getCompileUnit().getLanguage();
1127 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1128 Lang == dwarf::DW_LANG_ObjC)
1129 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1132 DICompositeType SPTy = SP.getType();
1133 DIArray Args = SPTy.getTypeArray();
1134 unsigned SPTag = SPTy.getTag();
1136 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1137 addType(SPDie, SPTy);
1139 addType(SPDie, DIType(Args.getElement(0).getNode()));
1141 unsigned VK = SP.getVirtuality();
1143 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1144 DIEBlock *Block = new DIEBlock();
1145 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1146 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1147 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1148 ContainingTypeMap.insert(std::make_pair(SPDie, WeakVH(SP.getContainingType().getNode())));
1154 /// createMemberSubprogramDIE - Create new member DIE using SP. This routine
1155 /// always returns a die with DW_AT_declaration attribute.
1156 DIE *DwarfDebug::createMemberSubprogramDIE(const DISubprogram &SP) {
1157 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1159 SPDie = createSubprogramDIE(SP);
1161 // If SPDie has DW_AT_declaration then reuse it.
1162 if (!SP.isDefinition())
1165 // Otherwise create new DIE for the declaration. First push definition
1166 // DIE at the top level.
1167 if (TopLevelDIEs.insert(SPDie))
1168 TopLevelDIEsVector.push_back(SPDie);
1170 SPDie = createRawSubprogramDIE(SP);
1173 DICompositeType SPTy = SP.getType();
1174 DIArray Args = SPTy.getTypeArray();
1175 unsigned SPTag = SPTy.getTag();
1176 if (SPTag == dwarf::DW_TAG_subroutine_type)
1177 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1178 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1179 addType(Arg, DIType(Args.getElement(i).getNode()));
1180 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1181 SPDie->addChild(Arg);
1184 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1188 /// createSubprogramDIE - Create new DIE using SP.
1189 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP) {
1190 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1194 SPDie = createRawSubprogramDIE(SP);
1196 if (!SP.isDefinition()) {
1197 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1199 // Add arguments. Do not add arguments for subprogram definition. They will
1200 // be handled while processing variables.
1201 DICompositeType SPTy = SP.getType();
1202 DIArray Args = SPTy.getTypeArray();
1203 unsigned SPTag = SPTy.getTag();
1205 if (SPTag == dwarf::DW_TAG_subroutine_type)
1206 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1207 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1208 addType(Arg, DIType(Args.getElement(i).getNode()));
1209 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1210 SPDie->addChild(Arg);
1214 // DW_TAG_inlined_subroutine may refer to this DIE.
1215 ModuleCU->insertDIE(SP.getNode(), SPDie);
1219 /// findCompileUnit - Get the compile unit for the given descriptor.
1221 CompileUnit &DwarfDebug::findCompileUnit(DICompileUnit Unit) const {
1222 DenseMap<Value *, CompileUnit *>::const_iterator I =
1223 CompileUnitMap.find(Unit.getNode());
1224 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1228 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1229 /// Initialize scope and update scope hierarchy.
1230 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1231 MDNode *InlinedAt) {
1232 assert (N && "Invalid Scope encoding!");
1233 assert (MI && "Missing machine instruction!");
1234 bool GetConcreteScope = (MI && InlinedAt);
1236 DbgScope *NScope = NULL;
1239 NScope = DbgScopeMap.lookup(InlinedAt);
1241 NScope = DbgScopeMap.lookup(N);
1242 assert (NScope && "Unable to find working scope!");
1244 if (NScope->getFirstInsn())
1247 DbgScope *Parent = NULL;
1248 if (GetConcreteScope) {
1249 DILocation IL(InlinedAt);
1250 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1251 IL.getOrigLocation().getNode());
1252 assert (Parent && "Unable to find Parent scope!");
1253 NScope->setParent(Parent);
1254 Parent->addScope(NScope);
1255 } else if (DIDescriptor(N).isLexicalBlock()) {
1256 DILexicalBlock DB(N);
1257 if (!DB.getContext().isNull()) {
1258 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1259 NScope->setParent(Parent);
1260 Parent->addScope(NScope);
1264 NScope->setFirstInsn(MI);
1266 if (!Parent && !InlinedAt) {
1267 StringRef SPName = DISubprogram(N).getLinkageName();
1268 if (SPName == MF->getFunction()->getName())
1269 CurrentFnDbgScope = NScope;
1272 if (GetConcreteScope) {
1273 ConcreteScopes[InlinedAt] = NScope;
1274 getOrCreateAbstractScope(N);
1280 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1281 assert (N && "Invalid Scope encoding!");
1283 DbgScope *AScope = AbstractScopes.lookup(N);
1287 DbgScope *Parent = NULL;
1289 DIDescriptor Scope(N);
1290 if (Scope.isLexicalBlock()) {
1291 DILexicalBlock DB(N);
1292 DIDescriptor ParentDesc = DB.getContext();
1293 if (!ParentDesc.isNull())
1294 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1297 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1300 Parent->addScope(AScope);
1301 AScope->setAbstractScope();
1302 AbstractScopes[N] = AScope;
1303 if (DIDescriptor(N).isSubprogram())
1304 AbstractScopesList.push_back(AScope);
1308 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1309 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1310 /// If there are global variables in this scope then create and insert
1311 /// DIEs for these variables.
1312 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1314 DIE *SPDie = ModuleCU->getDIE(SPNode);
1315 assert (SPDie && "Unable to find subprogram DIE!");
1316 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1317 DWLabel("func_begin", SubprogramCount));
1318 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1319 DWLabel("func_end", SubprogramCount));
1320 MachineLocation Location(RI->getFrameRegister(*MF));
1321 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1323 if (!DISubprogram(SPNode).isLocalToUnit())
1324 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1326 // If there are global variables at this scope then add their dies.
1327 for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(),
1328 SGE = ScopedGVs.end(); SGI != SGE; ++SGI) {
1329 MDNode *N = dyn_cast_or_null<MDNode>(*SGI);
1331 DIGlobalVariable GV(N);
1332 if (GV.getContext().getNode() == SPNode) {
1333 DIE *ScopedGVDie = createGlobalVariableDIE(GV);
1335 SPDie->addChild(ScopedGVDie);
1342 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1343 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1344 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1345 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1346 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1348 // Ignore empty scopes.
1349 if (StartID == EndID && StartID != 0)
1352 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1353 if (Scope->isAbstractScope())
1356 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1358 DWLabel("label", StartID)
1359 : DWLabel("func_begin", SubprogramCount));
1360 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1362 DWLabel("label", EndID)
1363 : DWLabel("func_end", SubprogramCount));
1370 /// constructInlinedScopeDIE - This scope represents inlined body of
1371 /// a function. Construct DIE to represent this concrete inlined copy
1372 /// of the function.
1373 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1374 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1375 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1376 assert (StartID && "Invalid starting label for an inlined scope!");
1377 assert (EndID && "Invalid end label for an inlined scope!");
1378 // Ignore empty scopes.
1379 if (StartID == EndID && StartID != 0)
1382 DIScope DS(Scope->getScopeNode());
1385 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1387 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1388 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1389 assert (OriginDIE && "Unable to find Origin DIE!");
1390 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1391 dwarf::DW_FORM_ref4, OriginDIE);
1393 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1394 DWLabel("label", StartID));
1395 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1396 DWLabel("label", EndID));
1398 InlinedSubprogramDIEs.insert(OriginDIE);
1400 // Track the start label for this inlined function.
1401 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1402 I = InlineInfo.find(InlinedSP.getNode());
1404 if (I == InlineInfo.end()) {
1405 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID,
1407 InlinedSPNodes.push_back(InlinedSP.getNode());
1409 I->second.push_back(std::make_pair(StartID, ScopeDIE));
1411 StringPool.insert(InlinedSP.getName());
1412 StringPool.insert(InlinedSP.getLinkageName());
1413 DILocation DL(Scope->getInlinedAt());
1414 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1415 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1421 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1422 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1423 // Get the descriptor.
1424 const DIVariable &VD = DV->getVariable();
1425 StringRef Name = VD.getName();
1429 // Translate tag to proper Dwarf tag. The result variable is dropped for
1432 switch (VD.getTag()) {
1433 case dwarf::DW_TAG_return_variable:
1435 case dwarf::DW_TAG_arg_variable:
1436 Tag = dwarf::DW_TAG_formal_parameter;
1438 case dwarf::DW_TAG_auto_variable: // fall thru
1440 Tag = dwarf::DW_TAG_variable;
1444 // Define variable debug information entry.
1445 DIE *VariableDie = new DIE(Tag);
1449 if (DbgVariable *AV = DV->getAbstractVariable())
1450 AbsDIE = AV->getDIE();
1453 DIScope DS(Scope->getScopeNode());
1454 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1455 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1457 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1458 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1459 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1460 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1461 dwarf::DW_FORM_ref4, AbsDIE);
1464 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1465 addSourceLine(VariableDie, &VD);
1467 // Add variable type.
1468 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1469 // addresses instead.
1470 if (VD.isBlockByrefVariable())
1471 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1473 addType(VariableDie, VD.getType());
1476 // Add variable address.
1477 if (!Scope->isAbstractScope()) {
1478 MachineLocation Location;
1480 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1481 Location.set(FrameReg, Offset);
1483 if (VD.hasComplexAddress())
1484 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1485 else if (VD.isBlockByrefVariable())
1486 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1488 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1490 DV->setDIE(VariableDie);
1495 void DwarfDebug::addPubTypes(DISubprogram SP) {
1496 DICompositeType SPTy = SP.getType();
1497 unsigned SPTag = SPTy.getTag();
1498 if (SPTag != dwarf::DW_TAG_subroutine_type)
1501 DIArray Args = SPTy.getTypeArray();
1505 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1506 DIType ATy(Args.getElement(i).getNode());
1509 DICompositeType CATy = getDICompositeType(ATy);
1510 if (!CATy.isNull() && !CATy.getName().empty()) {
1511 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1512 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1517 /// constructScopeDIE - Construct a DIE for this scope.
1518 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1521 DIScope DS(Scope->getScopeNode());
1525 DIE *ScopeDIE = NULL;
1526 if (Scope->getInlinedAt())
1527 ScopeDIE = constructInlinedScopeDIE(Scope);
1528 else if (DS.isSubprogram()) {
1529 if (Scope->isAbstractScope())
1530 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1532 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1535 ScopeDIE = constructLexicalScopeDIE(Scope);
1536 if (!ScopeDIE) return NULL;
1539 // Add variables to scope.
1540 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1541 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1542 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1544 ScopeDIE->addChild(VariableDIE);
1547 // Add nested scopes.
1548 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1549 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1550 // Define the Scope debug information entry.
1551 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1553 ScopeDIE->addChild(NestedDIE);
1556 if (DS.isSubprogram())
1557 addPubTypes(DISubprogram(DS.getNode()));
1562 /// GetOrCreateSourceID - Look up the source id with the given directory and
1563 /// source file names. If none currently exists, create a new id and insert it
1564 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1566 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) {
1568 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1569 if (DI != DirectoryIdMap.end()) {
1570 DId = DI->getValue();
1572 DId = DirectoryNames.size() + 1;
1573 DirectoryIdMap[DirName] = DId;
1574 DirectoryNames.push_back(DirName);
1578 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1579 if (FI != SourceFileIdMap.end()) {
1580 FId = FI->getValue();
1582 FId = SourceFileNames.size() + 1;
1583 SourceFileIdMap[FileName] = FId;
1584 SourceFileNames.push_back(FileName);
1587 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1588 SourceIdMap.find(std::make_pair(DId, FId));
1589 if (SI != SourceIdMap.end())
1592 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1593 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1594 SourceIds.push_back(std::make_pair(DId, FId));
1599 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1600 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace &NS) {
1601 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1605 NDie = new DIE(dwarf::DW_TAG_namespace);
1606 ModuleCU->insertDIE(NS.getNode(), NDie);
1607 if (!NS.getName().empty())
1608 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1609 addSourceLine(NDie, &NS);
1610 DIDescriptor NSContext = NS.getContext();
1611 DIE *Context = NULL;
1612 if (NSContext.isNameSpace()) {
1613 DINameSpace NS2(NSContext.getNode());
1614 Context = getOrCreateNameSpace(NS2);
1617 Context = ModuleCU->getCUDie();
1618 Context->addChild(NDie);
1622 void DwarfDebug::constructCompileUnit(MDNode *N) {
1623 DICompileUnit DIUnit(N);
1624 StringRef FN = DIUnit.getFilename();
1625 StringRef Dir = DIUnit.getDirectory();
1626 unsigned ID = GetOrCreateSourceID(Dir, FN);
1628 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1629 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1630 DWLabel("section_line", 0), DWLabel("section_line", 0),
1632 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1633 DIUnit.getProducer());
1634 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1635 DIUnit.getLanguage());
1636 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1639 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1640 if (DIUnit.isOptimized())
1641 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1643 StringRef Flags = DIUnit.getFlags();
1645 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1647 unsigned RVer = DIUnit.getRunTimeVersion();
1649 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1650 dwarf::DW_FORM_data1, RVer);
1652 CompileUnit *Unit = new CompileUnit(ID, Die);
1653 if (!ModuleCU && DIUnit.isMain()) {
1654 // Use first compile unit marked as isMain as the compile unit
1659 CompileUnitMap[DIUnit.getNode()] = Unit;
1660 CompileUnits.push_back(Unit);
1663 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1664 DIGlobalVariable DI_GV(N);
1666 // If debug information is malformed then ignore it.
1667 if (DI_GV.Verify() == false)
1670 // Check for pre-existence.
1671 if (ModuleCU->getDIE(DI_GV.getNode()))
1674 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1677 ModuleCU->insertDIE(N, VariableDie);
1679 // Add to context owner.
1680 if (TopLevelDIEs.insert(VariableDie))
1681 TopLevelDIEsVector.push_back(VariableDie);
1683 // Expose as global. FIXME - need to check external flag.
1684 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1686 DIType GTy = DI_GV.getType();
1687 if (GTy.isCompositeType() && !GTy.getName().empty()) {
1688 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1689 assert (Entry && "Missing global type!");
1690 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1695 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1698 // Check for pre-existence.
1699 if (ModuleCU->getDIE(N))
1702 if (!SP.isDefinition())
1703 // This is a method declaration which will be handled while constructing
1707 DIE *SubprogramDie = createSubprogramDIE(SP);
1710 ModuleCU->insertDIE(N, SubprogramDie);
1712 // Add to context owner.
1713 DIDescriptor SPContext = SP.getContext();
1714 if (SPContext.isCompileUnit()
1715 && SPContext.getNode() == SP.getCompileUnit().getNode()) {
1716 if (TopLevelDIEs.insert(SubprogramDie))
1717 TopLevelDIEsVector.push_back(SubprogramDie);
1718 } else if (SPContext.isNameSpace()) {
1719 DINameSpace NS(SPContext.getNode());
1720 DIE *NDie = getOrCreateNameSpace(NS);
1721 NDie->addChild(SubprogramDie);
1724 // Expose as global.
1725 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1730 /// beginModule - Emit all Dwarf sections that should come prior to the
1731 /// content. Create global DIEs and emit initial debug info sections.
1732 /// This is inovked by the target AsmPrinter.
1733 void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1736 if (TimePassesIsEnabled)
1737 DebugTimer->startTimer();
1739 if (!MAI->doesSupportDebugInformation())
1742 DebugInfoFinder DbgFinder;
1743 DbgFinder.processModule(*M);
1745 // Create all the compile unit DIEs.
1746 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1747 E = DbgFinder.compile_unit_end(); I != E; ++I)
1748 constructCompileUnit(*I);
1750 if (CompileUnits.empty()) {
1751 if (TimePassesIsEnabled)
1752 DebugTimer->stopTimer();
1757 // If main compile unit for this module is not seen than randomly
1758 // select first compile unit.
1760 ModuleCU = CompileUnits[0];
1762 // Create DIEs for each of the externally visible global variables.
1763 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1764 E = DbgFinder.global_variable_end(); I != E; ++I) {
1765 DIGlobalVariable GV(*I);
1766 DIDescriptor GVContext = GV.getContext();
1767 if (GVContext.isCompileUnit()
1768 && GVContext.getNode() == GV.getCompileUnit().getNode())
1769 constructGlobalVariableDIE(*I);
1770 else if (GVContext.isNameSpace()) {
1771 DIE *GVDie = createGlobalVariableDIE(GV);
1773 DINameSpace NS(GVContext.getNode());
1774 DIE *NDie = getOrCreateNameSpace(NS);
1775 NDie->addChild(GVDie);
1779 ScopedGVs.push_back(*I);
1782 // Create DIEs for each subprogram.
1783 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1784 E = DbgFinder.subprogram_end(); I != E; ++I)
1785 constructSubprogramDIE(*I);
1789 MMI->setDebugInfoAvailability(true);
1791 // Prime section data.
1792 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1794 // Print out .file directives to specify files for .loc directives. These are
1795 // printed out early so that they precede any .loc directives.
1796 if (MAI->hasDotLocAndDotFile()) {
1797 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1798 // Remember source id starts at 1.
1799 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1800 sys::Path FullPath(getSourceDirectoryName(Id.first));
1802 FullPath.appendComponent(getSourceFileName(Id.second));
1803 assert(AppendOk && "Could not append filename to directory!");
1805 Asm->EmitFile(i, FullPath.str());
1810 // Emit initial sections
1813 if (TimePassesIsEnabled)
1814 DebugTimer->stopTimer();
1817 /// endModule - Emit all Dwarf sections that should come after the content.
1819 void DwarfDebug::endModule() {
1823 if (TimePassesIsEnabled)
1824 DebugTimer->startTimer();
1826 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1827 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1828 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1830 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1833 // Insert top level DIEs.
1834 for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(),
1835 TE = TopLevelDIEsVector.end(); TI != TE; ++TI)
1836 ModuleCU->getCUDie()->addChild(*TI);
1838 for (DenseMap<DIE *, WeakVH>::iterator CI = ContainingTypeMap.begin(),
1839 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1840 DIE *SPDie = CI->first;
1841 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1843 DIE *NDie = ModuleCU->getDIE(N);
1844 if (!NDie) continue;
1845 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1846 addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1849 // Standard sections final addresses.
1850 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1851 EmitLabel("text_end", 0);
1852 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1853 EmitLabel("data_end", 0);
1855 // End text sections.
1856 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1857 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1858 EmitLabel("section_end", i);
1861 // Emit common frame information.
1862 emitCommonDebugFrame();
1864 // Emit function debug frame information
1865 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1866 E = DebugFrames.end(); I != E; ++I)
1867 emitFunctionDebugFrame(*I);
1869 // Compute DIE offsets and sizes.
1870 computeSizeAndOffsets();
1872 // Emit all the DIEs into a debug info section
1875 // Corresponding abbreviations into a abbrev section.
1876 emitAbbreviations();
1878 // Emit source line correspondence into a debug line section.
1881 // Emit info into a debug pubnames section.
1882 emitDebugPubNames();
1884 // Emit info into a debug pubtypes section.
1885 emitDebugPubTypes();
1887 // Emit info into a debug str section.
1890 // Emit info into a debug loc section.
1893 // Emit info into a debug aranges section.
1896 // Emit info into a debug ranges section.
1899 // Emit info into a debug macinfo section.
1902 // Emit inline info.
1903 emitDebugInlineInfo();
1905 if (TimePassesIsEnabled)
1906 DebugTimer->stopTimer();
1909 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1910 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1912 DILocation &ScopeLoc) {
1914 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1916 return AbsDbgVariable;
1918 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1922 AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1923 Scope->addVariable(AbsDbgVariable);
1924 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1925 return AbsDbgVariable;
1928 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1929 void DwarfDebug::collectVariableInfo() {
1932 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1933 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1934 VE = VMap.end(); VI != VE; ++VI) {
1935 MetadataBase *MB = VI->first;
1936 MDNode *Var = dyn_cast_or_null<MDNode>(MB);
1938 DIVariable DV (Var);
1939 std::pair< unsigned, MDNode *> VP = VI->second;
1940 DILocation ScopeLoc(VP.second);
1943 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1945 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1946 // If variable scope is not found then skip this variable.
1950 DbgVariable *RegVar = new DbgVariable(DV, VP.first);
1951 Scope->addVariable(RegVar);
1952 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first,
1954 RegVar->setAbstractVariable(AbsDbgVariable);
1958 /// beginScope - Process beginning of a scope starting at Label.
1959 void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) {
1960 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1961 if (I == DbgScopeBeginMap.end())
1963 ScopeVector &SD = I->second;
1964 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1966 (*SDI)->setStartLabelID(Label);
1969 /// endScope - Process end of a scope.
1970 void DwarfDebug::endScope(const MachineInstr *MI) {
1971 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1972 if (I == DbgScopeEndMap.end())
1975 unsigned Label = MMI->NextLabelID();
1976 Asm->printLabel(Label);
1979 SmallVector<DbgScope *, 2> &SD = I->second;
1980 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1982 (*SDI)->setEndLabelID(Label);
1986 /// createDbgScope - Create DbgScope for the scope.
1987 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1990 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1993 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1994 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1995 if (DIDescriptor(Scope).isLexicalBlock())
1996 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2000 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2004 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2005 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2006 DILocation DL(InlinedAt);
2007 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2010 /// extractScopeInformation - Scan machine instructions in this function
2011 /// and collect DbgScopes. Return true, if atleast one scope was found.
2012 bool DwarfDebug::extractScopeInformation(MachineFunction *MF) {
2013 // If scope information was extracted using .dbg intrinsics then there is not
2014 // any need to extract these information by scanning each instruction.
2015 if (!DbgScopeMap.empty())
2018 // Scan each instruction and create scopes. First build working set of scopes.
2019 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2021 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2023 const MachineInstr *MInsn = II;
2024 DebugLoc DL = MInsn->getDebugLoc();
2025 if (DL.isUnknown()) continue;
2026 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
2027 if (!DLT.Scope) continue;
2028 // There is no need to create another DIE for compile unit. For all
2029 // other scopes, create one DbgScope now. This will be translated
2030 // into a scope DIE at the end.
2031 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
2032 createDbgScope(DLT.Scope, DLT.InlinedAtLoc);
2037 // Build scope hierarchy using working set of scopes.
2038 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2040 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2042 const MachineInstr *MInsn = II;
2043 DebugLoc DL = MInsn->getDebugLoc();
2044 if (DL.isUnknown()) continue;
2045 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
2046 if (!DLT.Scope) continue;
2047 // There is no need to create another DIE for compile unit. For all
2048 // other scopes, create one DbgScope now. This will be translated
2049 // into a scope DIE at the end.
2050 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
2051 DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
2052 Scope->setLastInsn(MInsn);
2056 // If a scope's last instruction is not set then use its child scope's
2057 // last instruction as this scope's last instrunction.
2058 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2059 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2060 if (DI->second->isAbstractScope())
2062 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
2063 DI->second->fixInstructionMarkers();
2064 assert (DI->second->getLastInsn() && "Invalid last instruction!");
2067 // Each scope has first instruction and last instruction to mark beginning
2068 // and end of a scope respectively. Create an inverse map that list scopes
2069 // starts (and ends) with an instruction. One instruction may start (or end)
2071 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2072 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2073 DbgScope *S = DI->second;
2074 if (S->isAbstractScope())
2076 const MachineInstr *MI = S->getFirstInsn();
2077 assert (MI && "DbgScope does not have first instruction!");
2079 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
2080 if (IDI != DbgScopeBeginMap.end())
2081 IDI->second.push_back(S);
2083 DbgScopeBeginMap[MI].push_back(S);
2085 MI = S->getLastInsn();
2086 assert (MI && "DbgScope does not have last instruction!");
2087 IDI = DbgScopeEndMap.find(MI);
2088 if (IDI != DbgScopeEndMap.end())
2089 IDI->second.push_back(S);
2091 DbgScopeEndMap[MI].push_back(S);
2094 return !DbgScopeMap.empty();
2097 /// beginFunction - Gather pre-function debug information. Assumes being
2098 /// emitted immediately after the function entry point.
2099 void DwarfDebug::beginFunction(MachineFunction *MF) {
2102 if (!ShouldEmitDwarfDebug()) return;
2104 if (TimePassesIsEnabled)
2105 DebugTimer->startTimer();
2107 if (!extractScopeInformation(MF))
2110 collectVariableInfo();
2112 // Begin accumulating function debug information.
2113 MMI->BeginFunction(MF);
2115 // Assumes in correct section after the entry point.
2116 EmitLabel("func_begin", ++SubprogramCount);
2118 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2120 DebugLoc FDL = MF->getDefaultDebugLoc();
2121 if (!FDL.isUnknown()) {
2122 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2123 unsigned LabelID = 0;
2124 DISubprogram SP = getDISubprogram(DLT.Scope);
2126 LabelID = recordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
2128 LabelID = recordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
2129 Asm->printLabel(LabelID);
2132 if (TimePassesIsEnabled)
2133 DebugTimer->stopTimer();
2136 /// endFunction - Gather and emit post-function debug information.
2138 void DwarfDebug::endFunction(MachineFunction *MF) {
2139 if (!ShouldEmitDwarfDebug()) return;
2141 if (TimePassesIsEnabled)
2142 DebugTimer->startTimer();
2144 if (DbgScopeMap.empty())
2147 // Define end label for subprogram.
2148 EmitLabel("func_end", SubprogramCount);
2150 // Get function line info.
2151 if (!Lines.empty()) {
2152 // Get section line info.
2153 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2154 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2155 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2156 // Append the function info to section info.
2157 SectionLineInfos.insert(SectionLineInfos.end(),
2158 Lines.begin(), Lines.end());
2161 // Construct abstract scopes.
2162 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2163 AE = AbstractScopesList.end(); AI != AE; ++AI)
2164 constructScopeDIE(*AI);
2166 constructScopeDIE(CurrentFnDbgScope);
2168 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2169 MMI->getFrameMoves()));
2172 CurrentFnDbgScope = NULL;
2173 DbgScopeMap.clear();
2174 DbgScopeBeginMap.clear();
2175 DbgScopeEndMap.clear();
2176 ConcreteScopes.clear();
2177 AbstractScopesList.clear();
2181 if (TimePassesIsEnabled)
2182 DebugTimer->stopTimer();
2185 /// recordSourceLine - Records location information and associates it with a
2186 /// label. Returns a unique label ID used to generate a label and provide
2187 /// correspondence to the source line list.
2188 unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2193 if (TimePassesIsEnabled)
2194 DebugTimer->startTimer();
2199 DIDescriptor Scope(S);
2200 if (Scope.isCompileUnit()) {
2201 DICompileUnit CU(S);
2202 Dir = CU.getDirectory();
2203 Fn = CU.getFilename();
2204 } else if (Scope.isSubprogram()) {
2206 Dir = SP.getDirectory();
2207 Fn = SP.getFilename();
2208 } else if (Scope.isLexicalBlock()) {
2209 DILexicalBlock DB(S);
2210 Dir = DB.getDirectory();
2211 Fn = DB.getFilename();
2213 assert (0 && "Unexpected scope info");
2215 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2216 unsigned ID = MMI->NextLabelID();
2217 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2219 if (TimePassesIsEnabled)
2220 DebugTimer->stopTimer();
2225 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2226 /// timed. Look up the source id with the given directory and source file
2227 /// names. If none currently exists, create a new id and insert it in the
2228 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2230 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2231 const std::string &FileName) {
2232 if (TimePassesIsEnabled)
2233 DebugTimer->startTimer();
2235 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2237 if (TimePassesIsEnabled)
2238 DebugTimer->stopTimer();
2243 //===----------------------------------------------------------------------===//
2245 //===----------------------------------------------------------------------===//
2247 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2250 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2251 // Get the children.
2252 const std::vector<DIE *> &Children = Die->getChildren();
2254 // If not last sibling and has children then add sibling offset attribute.
2255 if (!Last && !Children.empty()) Die->addSiblingOffset();
2257 // Record the abbreviation.
2258 assignAbbrevNumber(Die->getAbbrev());
2260 // Get the abbreviation for this DIE.
2261 unsigned AbbrevNumber = Die->getAbbrevNumber();
2262 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2265 Die->setOffset(Offset);
2267 // Start the size with the size of abbreviation code.
2268 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2270 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2271 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2273 // Size the DIE attribute values.
2274 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2275 // Size attribute value.
2276 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2278 // Size the DIE children if any.
2279 if (!Children.empty()) {
2280 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2281 "Children flag not set");
2283 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2284 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2286 // End of children marker.
2287 Offset += sizeof(int8_t);
2290 Die->setSize(Offset - Die->getOffset());
2294 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2296 void DwarfDebug::computeSizeAndOffsets() {
2297 // Compute size of compile unit header.
2298 static unsigned Offset =
2299 sizeof(int32_t) + // Length of Compilation Unit Info
2300 sizeof(int16_t) + // DWARF version number
2301 sizeof(int32_t) + // Offset Into Abbrev. Section
2302 sizeof(int8_t); // Pointer Size (in bytes)
2304 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2305 CompileUnitOffsets[ModuleCU] = 0;
2308 /// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
2309 /// tools to recognize the object file contains Dwarf information.
2310 void DwarfDebug::emitInitial() {
2311 // Check to see if we already emitted intial headers.
2312 if (didInitial) return;
2315 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2317 // Dwarf sections base addresses.
2318 if (MAI->doesDwarfRequireFrameSection()) {
2319 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2320 EmitLabel("section_debug_frame", 0);
2323 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2324 EmitLabel("section_info", 0);
2325 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2326 EmitLabel("section_abbrev", 0);
2327 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2328 EmitLabel("section_aranges", 0);
2330 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2331 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2332 EmitLabel("section_macinfo", 0);
2335 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2336 EmitLabel("section_line", 0);
2337 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2338 EmitLabel("section_loc", 0);
2339 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2340 EmitLabel("section_pubnames", 0);
2341 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection());
2342 EmitLabel("section_pubtypes", 0);
2343 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2344 EmitLabel("section_str", 0);
2345 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2346 EmitLabel("section_ranges", 0);
2348 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2349 EmitLabel("text_begin", 0);
2350 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2351 EmitLabel("data_begin", 0);
2354 /// emitDIE - Recusively Emits a debug information entry.
2356 void DwarfDebug::emitDIE(DIE *Die) {
2357 // Get the abbreviation for this DIE.
2358 unsigned AbbrevNumber = Die->getAbbrevNumber();
2359 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2363 // Emit the code (index) for the abbreviation.
2364 Asm->EmitULEB128Bytes(AbbrevNumber);
2366 if (Asm->isVerbose())
2367 Asm->EOL(std::string("Abbrev [" +
2368 utostr(AbbrevNumber) +
2369 "] 0x" + utohexstr(Die->getOffset()) +
2370 ":0x" + utohexstr(Die->getSize()) + " " +
2371 dwarf::TagString(Abbrev->getTag())));
2375 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2376 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2378 // Emit the DIE attribute values.
2379 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2380 unsigned Attr = AbbrevData[i].getAttribute();
2381 unsigned Form = AbbrevData[i].getForm();
2382 assert(Form && "Too many attributes for DIE (check abbreviation)");
2385 case dwarf::DW_AT_sibling:
2386 Asm->EmitInt32(Die->getSiblingOffset());
2388 case dwarf::DW_AT_abstract_origin: {
2389 DIEEntry *E = cast<DIEEntry>(Values[i]);
2390 DIE *Origin = E->getEntry();
2391 unsigned Addr = Origin->getOffset();
2392 Asm->EmitInt32(Addr);
2396 // Emit an attribute using the defined form.
2397 Values[i]->EmitValue(this, Form);
2401 Asm->EOL(dwarf::AttributeString(Attr));
2404 // Emit the DIE children if any.
2405 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2406 const std::vector<DIE *> &Children = Die->getChildren();
2408 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2409 emitDIE(Children[j]);
2411 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2415 /// emitDebugInfo - Emit the debug info section.
2417 void DwarfDebug::emitDebugInfo() {
2418 // Start debug info section.
2419 Asm->OutStreamer.SwitchSection(
2420 Asm->getObjFileLowering().getDwarfInfoSection());
2421 DIE *Die = ModuleCU->getCUDie();
2423 // Emit the compile units header.
2424 EmitLabel("info_begin", ModuleCU->getID());
2426 // Emit size of content not including length itself
2427 unsigned ContentSize = Die->getSize() +
2428 sizeof(int16_t) + // DWARF version number
2429 sizeof(int32_t) + // Offset Into Abbrev. Section
2430 sizeof(int8_t) + // Pointer Size (in bytes)
2431 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2433 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2434 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2435 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2436 Asm->EOL("Offset Into Abbrev. Section");
2437 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2440 // FIXME - extra padding for gdb bug.
2441 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2442 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2443 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2444 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2445 EmitLabel("info_end", ModuleCU->getID());
2451 /// emitAbbreviations - Emit the abbreviation section.
2453 void DwarfDebug::emitAbbreviations() const {
2454 // Check to see if it is worth the effort.
2455 if (!Abbreviations.empty()) {
2456 // Start the debug abbrev section.
2457 Asm->OutStreamer.SwitchSection(
2458 Asm->getObjFileLowering().getDwarfAbbrevSection());
2460 EmitLabel("abbrev_begin", 0);
2462 // For each abbrevation.
2463 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2464 // Get abbreviation data
2465 const DIEAbbrev *Abbrev = Abbreviations[i];
2467 // Emit the abbrevations code (base 1 index.)
2468 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2469 Asm->EOL("Abbreviation Code");
2471 // Emit the abbreviations data.
2477 // Mark end of abbreviations.
2478 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2480 EmitLabel("abbrev_end", 0);
2485 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2486 /// the line matrix.
2488 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2489 // Define last address of section.
2490 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2491 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2492 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2493 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2495 // Mark end of matrix.
2496 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2497 Asm->EmitULEB128Bytes(1); Asm->EOL();
2498 Asm->EmitInt8(1); Asm->EOL();
2501 /// emitDebugLines - Emit source line information.
2503 void DwarfDebug::emitDebugLines() {
2504 // If the target is using .loc/.file, the assembler will be emitting the
2505 // .debug_line table automatically.
2506 if (MAI->hasDotLocAndDotFile())
2509 // Minimum line delta, thus ranging from -10..(255-10).
2510 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2511 // Maximum line delta, thus ranging from -10..(255-10).
2512 const int MaxLineDelta = 255 + MinLineDelta;
2514 // Start the dwarf line section.
2515 Asm->OutStreamer.SwitchSection(
2516 Asm->getObjFileLowering().getDwarfLineSection());
2518 // Construct the section header.
2519 EmitDifference("line_end", 0, "line_begin", 0, true);
2520 Asm->EOL("Length of Source Line Info");
2521 EmitLabel("line_begin", 0);
2523 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2525 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2526 Asm->EOL("Prolog Length");
2527 EmitLabel("line_prolog_begin", 0);
2529 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2531 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2533 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2535 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2537 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2539 // Line number standard opcode encodings argument count
2540 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2541 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2542 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2543 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2544 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2545 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2546 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2547 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2548 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2550 // Emit directories.
2551 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2552 Asm->EmitString(getSourceDirectoryName(DI));
2553 Asm->EOL("Directory");
2556 Asm->EmitInt8(0); Asm->EOL("End of directories");
2559 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2560 // Remember source id starts at 1.
2561 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2562 Asm->EmitString(getSourceFileName(Id.second));
2564 Asm->EmitULEB128Bytes(Id.first);
2565 Asm->EOL("Directory #");
2566 Asm->EmitULEB128Bytes(0);
2567 Asm->EOL("Mod date");
2568 Asm->EmitULEB128Bytes(0);
2569 Asm->EOL("File size");
2572 Asm->EmitInt8(0); Asm->EOL("End of files");
2574 EmitLabel("line_prolog_end", 0);
2576 // A sequence for each text section.
2577 unsigned SecSrcLinesSize = SectionSourceLines.size();
2579 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2580 // Isolate current sections line info.
2581 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2583 /*if (Asm->isVerbose()) {
2584 const MCSection *S = SectionMap[j + 1];
2585 O << '\t' << MAI->getCommentString() << " Section"
2586 << S->getName() << '\n';
2590 // Dwarf assumes we start with first line of first source file.
2591 unsigned Source = 1;
2594 // Construct rows of the address, source, line, column matrix.
2595 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2596 const SrcLineInfo &LineInfo = LineInfos[i];
2597 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2598 if (!LabelID) continue;
2600 if (LineInfo.getLine() == 0) continue;
2602 if (!Asm->isVerbose())
2605 std::pair<unsigned, unsigned> SourceID =
2606 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2607 O << '\t' << MAI->getCommentString() << ' '
2608 << getSourceDirectoryName(SourceID.first) << '/'
2609 << getSourceFileName(SourceID.second)
2610 << ':' << utostr_32(LineInfo.getLine()) << '\n';
2613 // Define the line address.
2614 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2615 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2616 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2617 EmitReference("label", LabelID); Asm->EOL("Location label");
2619 // If change of source, then switch to the new source.
2620 if (Source != LineInfo.getSourceID()) {
2621 Source = LineInfo.getSourceID();
2622 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2623 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2626 // If change of line.
2627 if (Line != LineInfo.getLine()) {
2628 // Determine offset.
2629 int Offset = LineInfo.getLine() - Line;
2630 int Delta = Offset - MinLineDelta;
2633 Line = LineInfo.getLine();
2635 // If delta is small enough and in range...
2636 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2637 // ... then use fast opcode.
2638 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2640 // ... otherwise use long hand.
2641 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2642 Asm->EOL("DW_LNS_advance_line");
2643 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2644 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2647 // Copy the previous row (different address or source)
2648 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2652 emitEndOfLineMatrix(j + 1);
2655 if (SecSrcLinesSize == 0)
2656 // Because we're emitting a debug_line section, we still need a line
2657 // table. The linker and friends expect it to exist. If there's nothing to
2658 // put into it, emit an empty table.
2659 emitEndOfLineMatrix(1);
2661 EmitLabel("line_end", 0);
2665 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2667 void DwarfDebug::emitCommonDebugFrame() {
2668 if (!MAI->doesDwarfRequireFrameSection())
2672 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2673 TargetFrameInfo::StackGrowsUp ?
2674 TD->getPointerSize() : -TD->getPointerSize();
2676 // Start the dwarf frame section.
2677 Asm->OutStreamer.SwitchSection(
2678 Asm->getObjFileLowering().getDwarfFrameSection());
2680 EmitLabel("debug_frame_common", 0);
2681 EmitDifference("debug_frame_common_end", 0,
2682 "debug_frame_common_begin", 0, true);
2683 Asm->EOL("Length of Common Information Entry");
2685 EmitLabel("debug_frame_common_begin", 0);
2686 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2687 Asm->EOL("CIE Identifier Tag");
2688 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2689 Asm->EOL("CIE Version");
2690 Asm->EmitString("");
2691 Asm->EOL("CIE Augmentation");
2692 Asm->EmitULEB128Bytes(1);
2693 Asm->EOL("CIE Code Alignment Factor");
2694 Asm->EmitSLEB128Bytes(stackGrowth);
2695 Asm->EOL("CIE Data Alignment Factor");
2696 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2697 Asm->EOL("CIE RA Column");
2699 std::vector<MachineMove> Moves;
2700 RI->getInitialFrameState(Moves);
2702 EmitFrameMoves(NULL, 0, Moves, false);
2704 Asm->EmitAlignment(2, 0, 0, false);
2705 EmitLabel("debug_frame_common_end", 0);
2710 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2713 DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2714 if (!MAI->doesDwarfRequireFrameSection())
2717 // Start the dwarf frame section.
2718 Asm->OutStreamer.SwitchSection(
2719 Asm->getObjFileLowering().getDwarfFrameSection());
2721 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2722 "debug_frame_begin", DebugFrameInfo.Number, true);
2723 Asm->EOL("Length of Frame Information Entry");
2725 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2727 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2729 Asm->EOL("FDE CIE offset");
2731 EmitReference("func_begin", DebugFrameInfo.Number);
2732 Asm->EOL("FDE initial location");
2733 EmitDifference("func_end", DebugFrameInfo.Number,
2734 "func_begin", DebugFrameInfo.Number);
2735 Asm->EOL("FDE address range");
2737 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2740 Asm->EmitAlignment(2, 0, 0, false);
2741 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2746 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2748 void DwarfDebug::emitDebugPubNames() {
2749 // Start the dwarf pubnames section.
2750 Asm->OutStreamer.SwitchSection(
2751 Asm->getObjFileLowering().getDwarfPubNamesSection());
2753 EmitDifference("pubnames_end", ModuleCU->getID(),
2754 "pubnames_begin", ModuleCU->getID(), true);
2755 Asm->EOL("Length of Public Names Info");
2757 EmitLabel("pubnames_begin", ModuleCU->getID());
2759 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2761 EmitSectionOffset("info_begin", "section_info",
2762 ModuleCU->getID(), 0, true, false);
2763 Asm->EOL("Offset of Compilation Unit Info");
2765 EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
2767 Asm->EOL("Compilation Unit Length");
2769 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
2770 for (StringMap<DIE*>::const_iterator
2771 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2772 const char *Name = GI->getKeyData();
2773 DIE * Entity = GI->second;
2775 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2776 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2779 Asm->EmitInt32(0); Asm->EOL("End Mark");
2780 EmitLabel("pubnames_end", ModuleCU->getID());
2785 void DwarfDebug::emitDebugPubTypes() {
2786 // Start the dwarf pubnames section.
2787 Asm->OutStreamer.SwitchSection(
2788 Asm->getObjFileLowering().getDwarfPubTypesSection());
2789 EmitDifference("pubtypes_end", ModuleCU->getID(),
2790 "pubtypes_begin", ModuleCU->getID(), true);
2791 Asm->EOL("Length of Public Types Info");
2793 EmitLabel("pubtypes_begin", ModuleCU->getID());
2795 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2797 EmitSectionOffset("info_begin", "section_info",
2798 ModuleCU->getID(), 0, true, false);
2799 Asm->EOL("Offset of Compilation ModuleCU Info");
2801 EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
2803 Asm->EOL("Compilation ModuleCU Length");
2805 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
2806 for (StringMap<DIE*>::const_iterator
2807 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2808 const char *Name = GI->getKeyData();
2809 DIE * Entity = GI->second;
2811 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2812 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2815 Asm->EmitInt32(0); Asm->EOL("End Mark");
2816 EmitLabel("pubtypes_end", ModuleCU->getID());
2821 /// emitDebugStr - Emit visible names into a debug str section.
2823 void DwarfDebug::emitDebugStr() {
2824 // Check to see if it is worth the effort.
2825 if (!StringPool.empty()) {
2826 // Start the dwarf str section.
2827 Asm->OutStreamer.SwitchSection(
2828 Asm->getObjFileLowering().getDwarfStrSection());
2830 // For each of strings in the string pool.
2831 for (unsigned StringID = 1, N = StringPool.size();
2832 StringID <= N; ++StringID) {
2833 // Emit a label for reference from debug information entries.
2834 EmitLabel("string", StringID);
2836 // Emit the string itself.
2837 const std::string &String = StringPool[StringID];
2838 Asm->EmitString(String); Asm->EOL();
2845 /// emitDebugLoc - Emit visible names into a debug loc section.
2847 void DwarfDebug::emitDebugLoc() {
2848 // Start the dwarf loc section.
2849 Asm->OutStreamer.SwitchSection(
2850 Asm->getObjFileLowering().getDwarfLocSection());
2854 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2856 void DwarfDebug::EmitDebugARanges() {
2857 // Start the dwarf aranges section.
2858 Asm->OutStreamer.SwitchSection(
2859 Asm->getObjFileLowering().getDwarfARangesSection());
2863 CompileUnit *Unit = GetBaseCompileUnit();
2865 // Don't include size of length
2866 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2868 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2870 EmitReference("info_begin", Unit->getID());
2871 Asm->EOL("Offset of Compilation Unit Info");
2873 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2875 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2877 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2878 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2881 EmitReference("text_begin", 0); Asm->EOL("Address");
2882 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2884 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2885 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2891 /// emitDebugRanges - Emit visible names into a debug ranges section.
2893 void DwarfDebug::emitDebugRanges() {
2894 // Start the dwarf ranges section.
2895 Asm->OutStreamer.SwitchSection(
2896 Asm->getObjFileLowering().getDwarfRangesSection());
2900 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2902 void DwarfDebug::emitDebugMacInfo() {
2903 if (const MCSection *LineInfo =
2904 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2905 // Start the dwarf macinfo section.
2906 Asm->OutStreamer.SwitchSection(LineInfo);
2911 /// emitDebugInlineInfo - Emit inline info using following format.
2913 /// 1. length of section
2914 /// 2. Dwarf version number
2915 /// 3. address size.
2917 /// Entries (one "entry" for each function that was inlined):
2919 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2920 /// otherwise offset into __debug_str for regular function name.
2921 /// 2. offset into __debug_str section for regular function name.
2922 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2923 /// instances for the function.
2925 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2926 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2927 /// __debug_info section, and the low_pc is the starting address for the
2928 /// inlining instance.
2929 void DwarfDebug::emitDebugInlineInfo() {
2930 if (!MAI->doesDwarfUsesInlineInfoSection())
2936 Asm->OutStreamer.SwitchSection(
2937 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2939 EmitDifference("debug_inlined_end", 1,
2940 "debug_inlined_begin", 1, true);
2941 Asm->EOL("Length of Debug Inlined Information Entry");
2943 EmitLabel("debug_inlined_begin", 1);
2945 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2946 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2948 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2949 E = InlinedSPNodes.end(); I != E; ++I) {
2951 // for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
2952 // I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2954 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2955 = InlineInfo.find(Node);
2956 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2957 DISubprogram SP(Node);
2958 StringRef LName = SP.getLinkageName();
2959 StringRef Name = SP.getName();
2962 Asm->EmitString(Name);
2964 // Skip special LLVM prefix that is used to inform the asm printer to not
2965 // emit usual symbol prefix before the symbol name. This happens for
2966 // Objective-C symbol names and symbol whose name is replaced using GCC's
2967 // __asm__ attribute.
2969 LName = LName.substr(1);
2970 // Asm->EmitString(LName);
2971 EmitSectionOffset("string", "section_str",
2972 StringPool.idFor(LName), false, true);
2975 Asm->EOL("MIPS linkage name");
2976 // Asm->EmitString(Name);
2977 EmitSectionOffset("string", "section_str",
2978 StringPool.idFor(Name), false, true);
2979 Asm->EOL("Function name");
2980 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2982 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2983 LE = Labels.end(); LI != LE; ++LI) {
2984 DIE *SP = LI->second;
2985 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2987 if (TD->getPointerSize() == sizeof(int32_t))
2988 O << MAI->getData32bitsDirective();
2990 O << MAI->getData64bitsDirective();
2992 PrintLabelName("label", LI->first); Asm->EOL("low_pc");
2996 EmitLabel("debug_inlined_end", 1);