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 /* Byref variables, in Blocks, are declared by the programmer as
450 "SomeType VarName;", but the compiler creates a
451 __Block_byref_x_VarName struct, and gives the variable VarName
452 either the struct, or a pointer to the struct, as its type. This
453 is necessary for various behind-the-scenes things the compiler
454 needs to do with by-reference variables in blocks.
456 However, as far as the original *programmer* is concerned, the
457 variable should still have type 'SomeType', as originally declared.
459 The following function dives into the __Block_byref_x_VarName
460 struct to find the original type of the variable. This will be
461 passed back to the code generating the type for the Debug
462 Information Entry for the variable 'VarName'. 'VarName' will then
463 have the original type 'SomeType' in its debug information.
465 The original type 'SomeType' will be the type of the field named
466 'VarName' inside the __Block_byref_x_VarName struct.
468 NOTE: In order for this to not completely fail on the debugger
469 side, the Debug Information Entry for the variable VarName needs to
470 have a DW_AT_location that tells the debugger how to unwind through
471 the pointers and __Block_byref_x_VarName struct to find the actual
472 value of the variable. The function addBlockByrefType does this. */
474 /// Find the type the programmer originally declared the variable to be
475 /// and return that type.
477 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
480 unsigned tag = Ty.getTag();
482 if (tag == dwarf::DW_TAG_pointer_type) {
483 DIDerivedType DTy = DIDerivedType(Ty.getNode());
484 subType = DTy.getTypeDerivedFrom();
487 DICompositeType blockStruct = DICompositeType(subType.getNode());
489 DIArray Elements = blockStruct.getTypeArray();
491 if (Elements.isNull())
494 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
495 DIDescriptor Element = Elements.getElement(i);
496 DIDerivedType DT = DIDerivedType(Element.getNode());
497 if (Name == DT.getName())
498 return (DT.getTypeDerivedFrom());
504 /// addComplexAddress - Start with the address based on the location provided,
505 /// and generate the DWARF information necessary to find the actual variable
506 /// given the extra address information encoded in the DIVariable, starting from
507 /// the starting location. Add the DWARF information to the die.
509 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
511 const MachineLocation &Location) {
512 const DIVariable &VD = DV->getVariable();
513 DIType Ty = VD.getType();
515 // Decode the original location, and use that as the start of the byref
516 // variable's location.
517 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
518 DIEBlock *Block = new DIEBlock();
520 if (Location.isReg()) {
522 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
524 Reg = Reg - dwarf::DW_OP_reg0;
525 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
526 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
530 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
532 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
533 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
536 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
539 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
540 uint64_t Element = VD.getAddrElement(i);
542 if (Element == DIFactory::OpPlus) {
543 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
544 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
545 } else if (Element == DIFactory::OpDeref) {
546 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
547 } else llvm_unreachable("unknown DIFactory Opcode");
550 // Now attach the location information to the DIE.
551 addBlock(Die, Attribute, 0, Block);
554 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
555 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
556 gives the variable VarName either the struct, or a pointer to the struct, as
557 its type. This is necessary for various behind-the-scenes things the
558 compiler needs to do with by-reference variables in Blocks.
560 However, as far as the original *programmer* is concerned, the variable
561 should still have type 'SomeType', as originally declared.
563 The function getBlockByrefType dives into the __Block_byref_x_VarName
564 struct to find the original type of the variable, which is then assigned to
565 the variable's Debug Information Entry as its real type. So far, so good.
566 However now the debugger will expect the variable VarName to have the type
567 SomeType. So we need the location attribute for the variable to be an
568 expression that explains to the debugger how to navigate through the
569 pointers and struct to find the actual variable of type SomeType.
571 The following function does just that. We start by getting
572 the "normal" location for the variable. This will be the location
573 of either the struct __Block_byref_x_VarName or the pointer to the
574 struct __Block_byref_x_VarName.
576 The struct will look something like:
578 struct __Block_byref_x_VarName {
580 struct __Block_byref_x_VarName *forwarding;
581 ... <various other fields>
583 ... <maybe more fields>
586 If we are given the struct directly (as our starting point) we
587 need to tell the debugger to:
589 1). Add the offset of the forwarding field.
591 2). Follow that pointer to get the the real __Block_byref_x_VarName
592 struct to use (the real one may have been copied onto the heap).
594 3). Add the offset for the field VarName, to find the actual variable.
596 If we started with a pointer to the struct, then we need to
597 dereference that pointer first, before the other steps.
598 Translating this into DWARF ops, we will need to append the following
599 to the current location description for the variable:
601 DW_OP_deref -- optional, if we start with a pointer
602 DW_OP_plus_uconst <forward_fld_offset>
604 DW_OP_plus_uconst <varName_fld_offset>
606 That is what this function does. */
608 /// addBlockByrefAddress - Start with the address based on the location
609 /// provided, and generate the DWARF information necessary to find the
610 /// actual Block variable (navigating the Block struct) based on the
611 /// starting location. Add the DWARF information to the die. For
612 /// more information, read large comment just above here.
614 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
616 const MachineLocation &Location) {
617 const DIVariable &VD = DV->getVariable();
618 DIType Ty = VD.getType();
620 unsigned Tag = Ty.getTag();
621 bool isPointer = false;
623 StringRef varName = VD.getName();
625 if (Tag == dwarf::DW_TAG_pointer_type) {
626 DIDerivedType DTy = DIDerivedType(Ty.getNode());
627 TmpTy = DTy.getTypeDerivedFrom();
631 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
633 // Find the __forwarding field and the variable field in the __Block_byref
635 DIArray Fields = blockStruct.getTypeArray();
636 DIDescriptor varField = DIDescriptor();
637 DIDescriptor forwardingField = DIDescriptor();
640 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
641 DIDescriptor Element = Fields.getElement(i);
642 DIDerivedType DT = DIDerivedType(Element.getNode());
643 StringRef fieldName = DT.getName();
644 if (fieldName == "__forwarding")
645 forwardingField = Element;
646 else if (fieldName == varName)
650 assert(!varField.isNull() && "Can't find byref variable in Block struct");
651 assert(!forwardingField.isNull()
652 && "Can't find forwarding field in Block struct");
654 // Get the offsets for the forwarding field and the variable field.
655 unsigned int forwardingFieldOffset =
656 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
657 unsigned int varFieldOffset =
658 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
660 // Decode the original location, and use that as the start of the byref
661 // variable's location.
662 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
663 DIEBlock *Block = new DIEBlock();
665 if (Location.isReg()) {
667 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
669 Reg = Reg - dwarf::DW_OP_reg0;
670 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
671 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
675 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
677 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
678 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
681 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
684 // If we started with a pointer to the __Block_byref... struct, then
685 // the first thing we need to do is dereference the pointer (DW_OP_deref).
687 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
689 // Next add the offset for the '__forwarding' field:
690 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
691 // adding the offset if it's 0.
692 if (forwardingFieldOffset > 0) {
693 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
694 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
697 // Now dereference the __forwarding field to get to the real __Block_byref
698 // struct: DW_OP_deref.
699 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
701 // Now that we've got the real __Block_byref... struct, add the offset
702 // for the variable's field to get to the location of the actual variable:
703 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
704 if (varFieldOffset > 0) {
705 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
706 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
709 // Now attach the location information to the DIE.
710 addBlock(Die, Attribute, 0, Block);
713 /// addAddress - Add an address attribute to a die based on the location
715 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
716 const MachineLocation &Location) {
717 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
718 DIEBlock *Block = new DIEBlock();
720 if (Location.isReg()) {
722 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
724 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
725 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
729 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
731 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
732 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
735 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
738 addBlock(Die, Attribute, 0, Block);
741 /// addToContextOwner - Add Die into the list of its context owner's children.
742 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
743 if (Context.isNull())
744 ModuleCU->addDie(Die);
745 else if (Context.isType()) {
746 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
747 ContextDIE->addChild(Die);
748 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
749 ContextDIE->addChild(Die);
751 ModuleCU->addDie(Die);
754 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
756 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
757 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
762 TyDIE = new DIE(dwarf::DW_TAG_base_type);
763 ModuleCU->insertDIE(Ty.getNode(), TyDIE);
764 if (Ty.isBasicType())
765 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
766 else if (Ty.isCompositeType())
767 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
769 assert(Ty.isDerivedType() && "Unknown kind of DIType");
770 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
773 addToContextOwner(TyDIE, Ty.getContext());
777 /// addType - Add a new type attribute to the specified entity.
778 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
782 // Check for pre-existence.
783 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
785 // If it exists then use the existing value.
787 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
792 Entry = createDIEEntry();
793 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
796 DIE *Buffer = getOrCreateTypeDIE(Ty);
798 Entry->setEntry(Buffer);
799 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
802 /// constructTypeDIE - Construct basic type die from DIBasicType.
803 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
804 // Get core information.
805 StringRef Name = BTy.getName();
806 Buffer.setTag(dwarf::DW_TAG_base_type);
807 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
810 // Add name if not anonymous or intermediate type.
812 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
813 uint64_t Size = BTy.getSizeInBits() >> 3;
814 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
817 /// constructTypeDIE - Construct derived type die from DIDerivedType.
818 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
819 // Get core information.
820 StringRef Name = DTy.getName();
821 uint64_t Size = DTy.getSizeInBits() >> 3;
822 unsigned Tag = DTy.getTag();
824 // FIXME - Workaround for templates.
825 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
829 // Map to main type, void will not have a type.
830 DIType FromTy = DTy.getTypeDerivedFrom();
831 addType(&Buffer, FromTy);
833 // Add name if not anonymous or intermediate type.
835 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
837 // Add size if non-zero (derived types might be zero-sized.)
839 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
841 // Add source line info if available and TyDesc is not a forward declaration.
842 if (!DTy.isForwardDecl())
843 addSourceLine(&Buffer, &DTy);
846 /// constructTypeDIE - Construct type DIE from DICompositeType.
847 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
848 // Get core information.
849 StringRef Name = CTy.getName();
851 uint64_t Size = CTy.getSizeInBits() >> 3;
852 unsigned Tag = CTy.getTag();
856 case dwarf::DW_TAG_vector_type:
857 case dwarf::DW_TAG_array_type:
858 constructArrayTypeDIE(Buffer, &CTy);
860 case dwarf::DW_TAG_enumeration_type: {
861 DIArray Elements = CTy.getTypeArray();
863 // Add enumerators to enumeration type.
864 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
866 DIEnumerator Enum(Elements.getElement(i).getNode());
867 if (!Enum.isNull()) {
868 ElemDie = constructEnumTypeDIE(&Enum);
869 Buffer.addChild(ElemDie);
874 case dwarf::DW_TAG_subroutine_type: {
876 DIArray Elements = CTy.getTypeArray();
877 DIDescriptor RTy = Elements.getElement(0);
878 addType(&Buffer, DIType(RTy.getNode()));
880 // Add prototype flag.
881 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
884 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
885 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
886 DIDescriptor Ty = Elements.getElement(i);
887 addType(Arg, DIType(Ty.getNode()));
888 Buffer.addChild(Arg);
892 case dwarf::DW_TAG_structure_type:
893 case dwarf::DW_TAG_union_type:
894 case dwarf::DW_TAG_class_type: {
895 // Add elements to structure type.
896 DIArray Elements = CTy.getTypeArray();
898 // A forward struct declared type may not have elements available.
899 if (Elements.isNull())
902 // Add elements to structure type.
903 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
904 DIDescriptor Element = Elements.getElement(i);
905 if (Element.isNull())
908 if (Element.getTag() == dwarf::DW_TAG_subprogram)
909 ElemDie = createMemberSubprogramDIE(DISubprogram(Element.getNode()));
911 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
912 Buffer.addChild(ElemDie);
915 if (CTy.isAppleBlockExtension())
916 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
918 unsigned RLang = CTy.getRunTimeLang();
920 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
921 dwarf::DW_FORM_data1, RLang);
928 // Add name if not anonymous or intermediate type.
930 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
932 if (Tag == dwarf::DW_TAG_enumeration_type ||
933 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
934 // Add size if non-zero (derived types might be zero-sized.)
936 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
938 // Add zero size if it is not a forward declaration.
939 if (CTy.isForwardDecl())
940 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
942 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
945 // Add source line info if available.
946 if (!CTy.isForwardDecl())
947 addSourceLine(&Buffer, &CTy);
951 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
952 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
953 int64_t L = SR.getLo();
954 int64_t H = SR.getHi();
955 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
957 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
959 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
960 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
962 Buffer.addChild(DW_Subrange);
965 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
966 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
967 DICompositeType *CTy) {
968 Buffer.setTag(dwarf::DW_TAG_array_type);
969 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
970 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
972 // Emit derived type.
973 addType(&Buffer, CTy->getTypeDerivedFrom());
974 DIArray Elements = CTy->getTypeArray();
976 // Get an anonymous type for index type.
977 DIE *IdxTy = ModuleCU->getIndexTyDie();
979 // Construct an anonymous type for index type.
980 IdxTy = new DIE(dwarf::DW_TAG_base_type);
981 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
982 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
983 dwarf::DW_ATE_signed);
984 ModuleCU->addDie(IdxTy);
985 ModuleCU->setIndexTyDie(IdxTy);
988 // Add subranges to array type.
989 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
990 DIDescriptor Element = Elements.getElement(i);
991 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
992 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
996 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
997 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator *ETy) {
998 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
999 StringRef Name = ETy->getName();
1000 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1001 int64_t Value = ETy->getEnumValue();
1002 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1006 /// createGlobalVariableDIE - Create new DIE using GV.
1007 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1008 // If the global variable was optmized out then no need to create debug info
1010 if (!GV.getGlobal()) return NULL;
1011 if (GV.getDisplayName().empty()) return NULL;
1013 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1014 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1015 GV.getDisplayName());
1017 StringRef LinkageName = GV.getLinkageName();
1018 if (!LinkageName.empty()) {
1019 // Skip special LLVM prefix that is used to inform the asm printer to not
1020 // emit usual symbol prefix before the symbol name. This happens for
1021 // Objective-C symbol names and symbol whose name is replaced using GCC's
1022 // __asm__ attribute.
1023 if (LinkageName[0] == 1)
1024 LinkageName = LinkageName.substr(1);
1025 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1028 addType(GVDie, GV.getType());
1029 if (!GV.isLocalToUnit())
1030 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1031 addSourceLine(GVDie, &GV);
1034 DIEBlock *Block = new DIEBlock();
1035 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1036 addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1037 Asm->Mang->getMangledName(GV.getGlobal()));
1038 addBlock(GVDie, dwarf::DW_AT_location, 0, Block);
1043 /// createMemberDIE - Create new member DIE.
1044 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1045 DIE *MemberDie = new DIE(DT.getTag());
1046 StringRef Name = DT.getName();
1048 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1050 addType(MemberDie, DT.getTypeDerivedFrom());
1052 addSourceLine(MemberDie, &DT);
1054 DIEBlock *MemLocationDie = new DIEBlock();
1055 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1057 uint64_t Size = DT.getSizeInBits();
1058 uint64_t FieldSize = DT.getOriginalTypeSize();
1060 if (Size != FieldSize) {
1062 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1063 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1065 uint64_t Offset = DT.getOffsetInBits();
1066 uint64_t FieldOffset = Offset;
1067 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1068 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1069 FieldOffset = (HiMark - FieldSize);
1070 Offset -= FieldOffset;
1072 // Maybe we need to work from the other end.
1073 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1074 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1076 // Here WD_AT_data_member_location points to the anonymous
1077 // field that includes this bit field.
1078 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1081 // This is not a bitfield.
1082 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1084 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1086 if (DT.isProtected())
1087 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1088 dwarf::DW_ACCESS_protected);
1089 else if (DT.isPrivate())
1090 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1091 dwarf::DW_ACCESS_private);
1092 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1093 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1094 dwarf::DW_ACCESS_public);
1096 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1097 dwarf::DW_VIRTUALITY_virtual);
1101 /// createRawSubprogramDIE - Create new partially incomplete DIE. This is
1102 /// a helper routine used by createMemberSubprogramDIE and
1103 /// createSubprogramDIE.
1104 DIE *DwarfDebug::createRawSubprogramDIE(const DISubprogram &SP) {
1105 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1106 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1108 StringRef LinkageName = SP.getLinkageName();
1109 if (!LinkageName.empty()) {
1110 // Skip special LLVM prefix that is used to inform the asm printer to not
1111 // emit usual symbol prefix before the symbol name. This happens for
1112 // Objective-C symbol names and symbol whose name is replaced using GCC's
1113 // __asm__ attribute.
1114 if (LinkageName[0] == 1)
1115 LinkageName = LinkageName.substr(1);
1116 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1119 addSourceLine(SPDie, &SP);
1121 // Add prototyped tag, if C or ObjC.
1122 unsigned Lang = SP.getCompileUnit().getLanguage();
1123 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1124 Lang == dwarf::DW_LANG_ObjC)
1125 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1128 DICompositeType SPTy = SP.getType();
1129 DIArray Args = SPTy.getTypeArray();
1130 unsigned SPTag = SPTy.getTag();
1132 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1133 addType(SPDie, SPTy);
1135 addType(SPDie, DIType(Args.getElement(0).getNode()));
1137 unsigned VK = SP.getVirtuality();
1139 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1140 DIEBlock *Block = new DIEBlock();
1141 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1142 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1143 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1144 ContainingTypeMap.insert(std::make_pair(SPDie, WeakVH(SP.getContainingType().getNode())));
1150 /// createMemberSubprogramDIE - Create new member DIE using SP. This routine
1151 /// always returns a die with DW_AT_declaration attribute.
1152 DIE *DwarfDebug::createMemberSubprogramDIE(const DISubprogram &SP) {
1153 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1155 SPDie = createSubprogramDIE(SP);
1157 // If SPDie has DW_AT_declaration then reuse it.
1158 if (!SP.isDefinition())
1161 // Otherwise create new DIE for the declaration. First push definition
1162 // DIE at the top level.
1163 if (TopLevelDIEs.insert(SPDie))
1164 TopLevelDIEsVector.push_back(SPDie);
1166 SPDie = createRawSubprogramDIE(SP);
1169 DICompositeType SPTy = SP.getType();
1170 DIArray Args = SPTy.getTypeArray();
1171 unsigned SPTag = SPTy.getTag();
1172 if (SPTag == dwarf::DW_TAG_subroutine_type)
1173 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1174 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1175 addType(Arg, DIType(Args.getElement(i).getNode()));
1176 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1177 SPDie->addChild(Arg);
1180 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1184 /// createSubprogramDIE - Create new DIE using SP.
1185 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP) {
1186 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1190 SPDie = createRawSubprogramDIE(SP);
1192 if (!SP.isDefinition()) {
1193 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1195 // Add arguments. Do not add arguments for subprogram definition. They will
1196 // be handled while processing variables.
1197 DICompositeType SPTy = SP.getType();
1198 DIArray Args = SPTy.getTypeArray();
1199 unsigned SPTag = SPTy.getTag();
1201 if (SPTag == dwarf::DW_TAG_subroutine_type)
1202 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1203 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1204 addType(Arg, DIType(Args.getElement(i).getNode()));
1205 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1206 SPDie->addChild(Arg);
1210 // DW_TAG_inlined_subroutine may refer to this DIE.
1211 ModuleCU->insertDIE(SP.getNode(), SPDie);
1215 /// findCompileUnit - Get the compile unit for the given descriptor.
1217 CompileUnit &DwarfDebug::findCompileUnit(DICompileUnit Unit) const {
1218 DenseMap<Value *, CompileUnit *>::const_iterator I =
1219 CompileUnitMap.find(Unit.getNode());
1220 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1224 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1225 /// Initialize scope and update scope hierarchy.
1226 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1227 MDNode *InlinedAt) {
1228 assert (N && "Invalid Scope encoding!");
1229 assert (MI && "Missing machine instruction!");
1230 bool GetConcreteScope = (MI && InlinedAt);
1232 DbgScope *NScope = NULL;
1235 NScope = DbgScopeMap.lookup(InlinedAt);
1237 NScope = DbgScopeMap.lookup(N);
1238 assert (NScope && "Unable to find working scope!");
1240 if (NScope->getFirstInsn())
1243 DbgScope *Parent = NULL;
1244 if (GetConcreteScope) {
1245 DILocation IL(InlinedAt);
1246 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1247 IL.getOrigLocation().getNode());
1248 assert (Parent && "Unable to find Parent scope!");
1249 NScope->setParent(Parent);
1250 Parent->addScope(NScope);
1251 } else if (DIDescriptor(N).isLexicalBlock()) {
1252 DILexicalBlock DB(N);
1253 if (!DB.getContext().isNull()) {
1254 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1255 NScope->setParent(Parent);
1256 Parent->addScope(NScope);
1260 NScope->setFirstInsn(MI);
1262 if (!Parent && !InlinedAt) {
1263 StringRef SPName = DISubprogram(N).getLinkageName();
1264 if (SPName == MF->getFunction()->getName())
1265 CurrentFnDbgScope = NScope;
1268 if (GetConcreteScope) {
1269 ConcreteScopes[InlinedAt] = NScope;
1270 getOrCreateAbstractScope(N);
1276 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1277 assert (N && "Invalid Scope encoding!");
1279 DbgScope *AScope = AbstractScopes.lookup(N);
1283 DbgScope *Parent = NULL;
1285 DIDescriptor Scope(N);
1286 if (Scope.isLexicalBlock()) {
1287 DILexicalBlock DB(N);
1288 DIDescriptor ParentDesc = DB.getContext();
1289 if (!ParentDesc.isNull())
1290 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1293 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1296 Parent->addScope(AScope);
1297 AScope->setAbstractScope();
1298 AbstractScopes[N] = AScope;
1299 if (DIDescriptor(N).isSubprogram())
1300 AbstractScopesList.push_back(AScope);
1304 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1305 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1306 /// If there are global variables in this scope then create and insert
1307 /// DIEs for these variables.
1308 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1310 DIE *SPDie = ModuleCU->getDIE(SPNode);
1311 assert (SPDie && "Unable to find subprogram DIE!");
1312 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1313 DWLabel("func_begin", SubprogramCount));
1314 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1315 DWLabel("func_end", SubprogramCount));
1316 MachineLocation Location(RI->getFrameRegister(*MF));
1317 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1319 if (!DISubprogram(SPNode).isLocalToUnit())
1320 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1325 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1326 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1327 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1328 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1329 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1331 // Ignore empty scopes.
1332 if (StartID == EndID && StartID != 0)
1335 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1336 if (Scope->isAbstractScope())
1339 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1341 DWLabel("label", StartID)
1342 : DWLabel("func_begin", SubprogramCount));
1343 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1345 DWLabel("label", EndID)
1346 : DWLabel("func_end", SubprogramCount));
1353 /// constructInlinedScopeDIE - This scope represents inlined body of
1354 /// a function. Construct DIE to represent this concrete inlined copy
1355 /// of the function.
1356 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1357 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1358 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1359 assert (StartID && "Invalid starting label for an inlined scope!");
1360 assert (EndID && "Invalid end label for an inlined scope!");
1361 // Ignore empty scopes.
1362 if (StartID == EndID && StartID != 0)
1365 DIScope DS(Scope->getScopeNode());
1368 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1370 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1371 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1372 assert (OriginDIE && "Unable to find Origin DIE!");
1373 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1374 dwarf::DW_FORM_ref4, OriginDIE);
1376 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1377 DWLabel("label", StartID));
1378 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1379 DWLabel("label", EndID));
1381 InlinedSubprogramDIEs.insert(OriginDIE);
1383 // Track the start label for this inlined function.
1384 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1385 I = InlineInfo.find(InlinedSP.getNode());
1387 if (I == InlineInfo.end()) {
1388 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID,
1390 InlinedSPNodes.push_back(InlinedSP.getNode());
1392 I->second.push_back(std::make_pair(StartID, ScopeDIE));
1394 StringPool.insert(InlinedSP.getName());
1395 StringPool.insert(InlinedSP.getLinkageName());
1396 DILocation DL(Scope->getInlinedAt());
1397 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1398 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1404 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1405 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1406 // Get the descriptor.
1407 const DIVariable &VD = DV->getVariable();
1408 StringRef Name = VD.getName();
1412 // Translate tag to proper Dwarf tag. The result variable is dropped for
1415 switch (VD.getTag()) {
1416 case dwarf::DW_TAG_return_variable:
1418 case dwarf::DW_TAG_arg_variable:
1419 Tag = dwarf::DW_TAG_formal_parameter;
1421 case dwarf::DW_TAG_auto_variable: // fall thru
1423 Tag = dwarf::DW_TAG_variable;
1427 // Define variable debug information entry.
1428 DIE *VariableDie = new DIE(Tag);
1432 if (DbgVariable *AV = DV->getAbstractVariable())
1433 AbsDIE = AV->getDIE();
1436 DIScope DS(Scope->getScopeNode());
1437 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1438 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1440 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1441 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1442 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1443 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1444 dwarf::DW_FORM_ref4, AbsDIE);
1447 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1448 addSourceLine(VariableDie, &VD);
1450 // Add variable type.
1451 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1452 // addresses instead.
1453 if (VD.isBlockByrefVariable())
1454 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1456 addType(VariableDie, VD.getType());
1459 // Add variable address.
1460 if (!Scope->isAbstractScope()) {
1461 MachineLocation Location;
1463 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1464 Location.set(FrameReg, Offset);
1466 if (VD.hasComplexAddress())
1467 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1468 else if (VD.isBlockByrefVariable())
1469 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1471 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1473 DV->setDIE(VariableDie);
1478 void DwarfDebug::addPubTypes(DISubprogram SP) {
1479 DICompositeType SPTy = SP.getType();
1480 unsigned SPTag = SPTy.getTag();
1481 if (SPTag != dwarf::DW_TAG_subroutine_type)
1484 DIArray Args = SPTy.getTypeArray();
1488 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1489 DIType ATy(Args.getElement(i).getNode());
1492 DICompositeType CATy = getDICompositeType(ATy);
1493 if (!CATy.isNull() && !CATy.getName().empty()) {
1494 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1495 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1500 /// constructScopeDIE - Construct a DIE for this scope.
1501 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1504 DIScope DS(Scope->getScopeNode());
1508 DIE *ScopeDIE = NULL;
1509 if (Scope->getInlinedAt())
1510 ScopeDIE = constructInlinedScopeDIE(Scope);
1511 else if (DS.isSubprogram()) {
1512 if (Scope->isAbstractScope())
1513 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1515 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1518 ScopeDIE = constructLexicalScopeDIE(Scope);
1519 if (!ScopeDIE) return NULL;
1522 // Add variables to scope.
1523 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1524 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1525 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1527 ScopeDIE->addChild(VariableDIE);
1530 // Add nested scopes.
1531 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1532 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1533 // Define the Scope debug information entry.
1534 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1536 ScopeDIE->addChild(NestedDIE);
1539 if (DS.isSubprogram())
1540 addPubTypes(DISubprogram(DS.getNode()));
1545 /// GetOrCreateSourceID - Look up the source id with the given directory and
1546 /// source file names. If none currently exists, create a new id and insert it
1547 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1549 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) {
1551 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1552 if (DI != DirectoryIdMap.end()) {
1553 DId = DI->getValue();
1555 DId = DirectoryNames.size() + 1;
1556 DirectoryIdMap[DirName] = DId;
1557 DirectoryNames.push_back(DirName);
1561 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1562 if (FI != SourceFileIdMap.end()) {
1563 FId = FI->getValue();
1565 FId = SourceFileNames.size() + 1;
1566 SourceFileIdMap[FileName] = FId;
1567 SourceFileNames.push_back(FileName);
1570 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1571 SourceIdMap.find(std::make_pair(DId, FId));
1572 if (SI != SourceIdMap.end())
1575 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1576 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1577 SourceIds.push_back(std::make_pair(DId, FId));
1582 void DwarfDebug::constructCompileUnit(MDNode *N) {
1583 DICompileUnit DIUnit(N);
1584 StringRef FN = DIUnit.getFilename();
1585 StringRef Dir = DIUnit.getDirectory();
1586 unsigned ID = GetOrCreateSourceID(Dir, FN);
1588 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1589 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1590 DWLabel("section_line", 0), DWLabel("section_line", 0),
1592 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1593 DIUnit.getProducer());
1594 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1595 DIUnit.getLanguage());
1596 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1599 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1600 if (DIUnit.isOptimized())
1601 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1603 StringRef Flags = DIUnit.getFlags();
1605 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1607 unsigned RVer = DIUnit.getRunTimeVersion();
1609 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1610 dwarf::DW_FORM_data1, RVer);
1612 CompileUnit *Unit = new CompileUnit(ID, Die);
1613 if (!ModuleCU && DIUnit.isMain()) {
1614 // Use first compile unit marked as isMain as the compile unit
1619 CompileUnitMap[DIUnit.getNode()] = Unit;
1620 CompileUnits.push_back(Unit);
1623 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1624 DIGlobalVariable DI_GV(N);
1626 // If debug information is malformed then ignore it.
1627 if (DI_GV.Verify() == false)
1630 // Check for pre-existence.
1631 if (ModuleCU->getDIE(DI_GV.getNode()))
1634 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1637 ModuleCU->insertDIE(N, VariableDie);
1639 // Add to context owner.
1640 addToContextOwner(VariableDie, DI_GV.getContext());
1642 // Expose as global. FIXME - need to check external flag.
1643 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1645 DIType GTy = DI_GV.getType();
1646 if (GTy.isCompositeType() && !GTy.getName().empty()) {
1647 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1648 assert (Entry && "Missing global type!");
1649 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1654 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1657 // Check for pre-existence.
1658 if (ModuleCU->getDIE(N))
1661 if (!SP.isDefinition())
1662 // This is a method declaration which will be handled while constructing
1666 DIE *SubprogramDie = createSubprogramDIE(SP);
1669 ModuleCU->insertDIE(N, SubprogramDie);
1671 // Add to context owner.
1672 if (SP.getContext().getNode() == SP.getCompileUnit().getNode())
1673 if (TopLevelDIEs.insert(SubprogramDie))
1674 TopLevelDIEsVector.push_back(SubprogramDie);
1676 // Expose as global.
1677 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1682 /// beginModule - Emit all Dwarf sections that should come prior to the
1683 /// content. Create global DIEs and emit initial debug info sections.
1684 /// This is inovked by the target AsmPrinter.
1685 void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1688 if (TimePassesIsEnabled)
1689 DebugTimer->startTimer();
1691 if (!MAI->doesSupportDebugInformation())
1694 DebugInfoFinder DbgFinder;
1695 DbgFinder.processModule(*M);
1697 // Create all the compile unit DIEs.
1698 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1699 E = DbgFinder.compile_unit_end(); I != E; ++I)
1700 constructCompileUnit(*I);
1702 if (CompileUnits.empty()) {
1703 if (TimePassesIsEnabled)
1704 DebugTimer->stopTimer();
1709 // If main compile unit for this module is not seen than randomly
1710 // select first compile unit.
1712 ModuleCU = CompileUnits[0];
1714 // Create DIEs for each subprogram.
1715 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1716 E = DbgFinder.subprogram_end(); I != E; ++I)
1717 constructSubprogramDIE(*I);
1719 // Create DIEs for each global variable.
1720 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1721 E = DbgFinder.global_variable_end(); I != E; ++I)
1722 constructGlobalVariableDIE(*I);
1726 MMI->setDebugInfoAvailability(true);
1728 // Prime section data.
1729 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1731 // Print out .file directives to specify files for .loc directives. These are
1732 // printed out early so that they precede any .loc directives.
1733 if (MAI->hasDotLocAndDotFile()) {
1734 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1735 // Remember source id starts at 1.
1736 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1737 sys::Path FullPath(getSourceDirectoryName(Id.first));
1739 FullPath.appendComponent(getSourceFileName(Id.second));
1740 assert(AppendOk && "Could not append filename to directory!");
1742 Asm->EmitFile(i, FullPath.str());
1747 // Emit initial sections
1750 if (TimePassesIsEnabled)
1751 DebugTimer->stopTimer();
1754 /// endModule - Emit all Dwarf sections that should come after the content.
1756 void DwarfDebug::endModule() {
1760 if (TimePassesIsEnabled)
1761 DebugTimer->startTimer();
1763 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1764 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1765 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1767 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1770 // Insert top level DIEs.
1771 for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(),
1772 TE = TopLevelDIEsVector.end(); TI != TE; ++TI)
1773 ModuleCU->getCUDie()->addChild(*TI);
1775 for (DenseMap<DIE *, WeakVH>::iterator CI = ContainingTypeMap.begin(),
1776 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1777 DIE *SPDie = CI->first;
1778 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1780 DIE *NDie = ModuleCU->getDIE(N);
1781 if (!NDie) continue;
1782 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1783 addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1786 // Standard sections final addresses.
1787 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1788 EmitLabel("text_end", 0);
1789 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1790 EmitLabel("data_end", 0);
1792 // End text sections.
1793 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1794 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1795 EmitLabel("section_end", i);
1798 // Emit common frame information.
1799 emitCommonDebugFrame();
1801 // Emit function debug frame information
1802 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1803 E = DebugFrames.end(); I != E; ++I)
1804 emitFunctionDebugFrame(*I);
1806 // Compute DIE offsets and sizes.
1807 computeSizeAndOffsets();
1809 // Emit all the DIEs into a debug info section
1812 // Corresponding abbreviations into a abbrev section.
1813 emitAbbreviations();
1815 // Emit source line correspondence into a debug line section.
1818 // Emit info into a debug pubnames section.
1819 emitDebugPubNames();
1821 // Emit info into a debug pubtypes section.
1822 emitDebugPubTypes();
1824 // Emit info into a debug str section.
1827 // Emit info into a debug loc section.
1830 // Emit info into a debug aranges section.
1833 // Emit info into a debug ranges section.
1836 // Emit info into a debug macinfo section.
1839 // Emit inline info.
1840 emitDebugInlineInfo();
1842 if (TimePassesIsEnabled)
1843 DebugTimer->stopTimer();
1846 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1847 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1849 DILocation &ScopeLoc) {
1851 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1853 return AbsDbgVariable;
1855 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1859 AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1860 Scope->addVariable(AbsDbgVariable);
1861 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1862 return AbsDbgVariable;
1865 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1866 void DwarfDebug::collectVariableInfo() {
1869 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1870 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1871 VE = VMap.end(); VI != VE; ++VI) {
1872 MetadataBase *MB = VI->first;
1873 MDNode *Var = dyn_cast_or_null<MDNode>(MB);
1875 DIVariable DV (Var);
1876 std::pair< unsigned, MDNode *> VP = VI->second;
1877 DILocation ScopeLoc(VP.second);
1880 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1882 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1883 // If variable scope is not found then skip this variable.
1887 DbgVariable *RegVar = new DbgVariable(DV, VP.first);
1888 Scope->addVariable(RegVar);
1889 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first,
1891 RegVar->setAbstractVariable(AbsDbgVariable);
1895 /// beginScope - Process beginning of a scope starting at Label.
1896 void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) {
1897 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1898 if (I == DbgScopeBeginMap.end())
1900 ScopeVector &SD = I->second;
1901 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1903 (*SDI)->setStartLabelID(Label);
1906 /// endScope - Process end of a scope.
1907 void DwarfDebug::endScope(const MachineInstr *MI) {
1908 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1909 if (I == DbgScopeEndMap.end())
1912 unsigned Label = MMI->NextLabelID();
1913 Asm->printLabel(Label);
1916 SmallVector<DbgScope *, 2> &SD = I->second;
1917 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1919 (*SDI)->setEndLabelID(Label);
1923 /// createDbgScope - Create DbgScope for the scope.
1924 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1927 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1930 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1931 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1932 if (DIDescriptor(Scope).isLexicalBlock())
1933 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
1937 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1941 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1942 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1943 DILocation DL(InlinedAt);
1944 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
1947 /// extractScopeInformation - Scan machine instructions in this function
1948 /// and collect DbgScopes. Return true, if atleast one scope was found.
1949 bool DwarfDebug::extractScopeInformation(MachineFunction *MF) {
1950 // If scope information was extracted using .dbg intrinsics then there is not
1951 // any need to extract these information by scanning each instruction.
1952 if (!DbgScopeMap.empty())
1955 // Scan each instruction and create scopes. First build working set of scopes.
1956 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1958 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1960 const MachineInstr *MInsn = II;
1961 DebugLoc DL = MInsn->getDebugLoc();
1962 if (DL.isUnknown()) continue;
1963 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1964 if (!DLT.Scope) continue;
1965 // There is no need to create another DIE for compile unit. For all
1966 // other scopes, create one DbgScope now. This will be translated
1967 // into a scope DIE at the end.
1968 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
1969 createDbgScope(DLT.Scope, DLT.InlinedAtLoc);
1974 // Build scope hierarchy using working set of scopes.
1975 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1977 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1979 const MachineInstr *MInsn = II;
1980 DebugLoc DL = MInsn->getDebugLoc();
1981 if (DL.isUnknown()) continue;
1982 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
1983 if (!DLT.Scope) continue;
1984 // There is no need to create another DIE for compile unit. For all
1985 // other scopes, create one DbgScope now. This will be translated
1986 // into a scope DIE at the end.
1987 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
1988 DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
1989 Scope->setLastInsn(MInsn);
1993 // If a scope's last instruction is not set then use its child scope's
1994 // last instruction as this scope's last instrunction.
1995 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
1996 DE = DbgScopeMap.end(); DI != DE; ++DI) {
1997 if (DI->second->isAbstractScope())
1999 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
2000 DI->second->fixInstructionMarkers();
2001 assert (DI->second->getLastInsn() && "Invalid last instruction!");
2004 // Each scope has first instruction and last instruction to mark beginning
2005 // and end of a scope respectively. Create an inverse map that list scopes
2006 // starts (and ends) with an instruction. One instruction may start (or end)
2008 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2009 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2010 DbgScope *S = DI->second;
2011 if (S->isAbstractScope())
2013 const MachineInstr *MI = S->getFirstInsn();
2014 assert (MI && "DbgScope does not have first instruction!");
2016 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
2017 if (IDI != DbgScopeBeginMap.end())
2018 IDI->second.push_back(S);
2020 DbgScopeBeginMap[MI].push_back(S);
2022 MI = S->getLastInsn();
2023 assert (MI && "DbgScope does not have last instruction!");
2024 IDI = DbgScopeEndMap.find(MI);
2025 if (IDI != DbgScopeEndMap.end())
2026 IDI->second.push_back(S);
2028 DbgScopeEndMap[MI].push_back(S);
2031 return !DbgScopeMap.empty();
2034 /// beginFunction - Gather pre-function debug information. Assumes being
2035 /// emitted immediately after the function entry point.
2036 void DwarfDebug::beginFunction(MachineFunction *MF) {
2039 if (!ShouldEmitDwarfDebug()) return;
2041 if (TimePassesIsEnabled)
2042 DebugTimer->startTimer();
2044 if (!extractScopeInformation(MF))
2047 collectVariableInfo();
2049 // Begin accumulating function debug information.
2050 MMI->BeginFunction(MF);
2052 // Assumes in correct section after the entry point.
2053 EmitLabel("func_begin", ++SubprogramCount);
2055 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2057 DebugLoc FDL = MF->getDefaultDebugLoc();
2058 if (!FDL.isUnknown()) {
2059 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2060 unsigned LabelID = 0;
2061 DISubprogram SP = getDISubprogram(DLT.Scope);
2063 LabelID = recordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
2065 LabelID = recordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
2066 Asm->printLabel(LabelID);
2069 if (TimePassesIsEnabled)
2070 DebugTimer->stopTimer();
2073 /// endFunction - Gather and emit post-function debug information.
2075 void DwarfDebug::endFunction(MachineFunction *MF) {
2076 if (!ShouldEmitDwarfDebug()) return;
2078 if (TimePassesIsEnabled)
2079 DebugTimer->startTimer();
2081 if (DbgScopeMap.empty())
2084 // Define end label for subprogram.
2085 EmitLabel("func_end", SubprogramCount);
2087 // Get function line info.
2088 if (!Lines.empty()) {
2089 // Get section line info.
2090 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2091 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2092 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2093 // Append the function info to section info.
2094 SectionLineInfos.insert(SectionLineInfos.end(),
2095 Lines.begin(), Lines.end());
2098 // Construct abstract scopes.
2099 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2100 AE = AbstractScopesList.end(); AI != AE; ++AI)
2101 constructScopeDIE(*AI);
2103 constructScopeDIE(CurrentFnDbgScope);
2105 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2106 MMI->getFrameMoves()));
2109 CurrentFnDbgScope = NULL;
2110 DbgScopeMap.clear();
2111 DbgScopeBeginMap.clear();
2112 DbgScopeEndMap.clear();
2113 ConcreteScopes.clear();
2114 AbstractScopesList.clear();
2118 if (TimePassesIsEnabled)
2119 DebugTimer->stopTimer();
2122 /// recordSourceLine - Records location information and associates it with a
2123 /// label. Returns a unique label ID used to generate a label and provide
2124 /// correspondence to the source line list.
2125 unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2130 if (TimePassesIsEnabled)
2131 DebugTimer->startTimer();
2136 DIDescriptor Scope(S);
2137 if (Scope.isCompileUnit()) {
2138 DICompileUnit CU(S);
2139 Dir = CU.getDirectory();
2140 Fn = CU.getFilename();
2141 } else if (Scope.isSubprogram()) {
2143 Dir = SP.getDirectory();
2144 Fn = SP.getFilename();
2145 } else if (Scope.isLexicalBlock()) {
2146 DILexicalBlock DB(S);
2147 Dir = DB.getDirectory();
2148 Fn = DB.getFilename();
2150 assert (0 && "Unexpected scope info");
2152 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2153 unsigned ID = MMI->NextLabelID();
2154 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2156 if (TimePassesIsEnabled)
2157 DebugTimer->stopTimer();
2162 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2163 /// timed. Look up the source id with the given directory and source file
2164 /// names. If none currently exists, create a new id and insert it in the
2165 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2167 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2168 const std::string &FileName) {
2169 if (TimePassesIsEnabled)
2170 DebugTimer->startTimer();
2172 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2174 if (TimePassesIsEnabled)
2175 DebugTimer->stopTimer();
2180 //===----------------------------------------------------------------------===//
2182 //===----------------------------------------------------------------------===//
2184 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2187 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2188 // Get the children.
2189 const std::vector<DIE *> &Children = Die->getChildren();
2191 // If not last sibling and has children then add sibling offset attribute.
2192 if (!Last && !Children.empty()) Die->addSiblingOffset();
2194 // Record the abbreviation.
2195 assignAbbrevNumber(Die->getAbbrev());
2197 // Get the abbreviation for this DIE.
2198 unsigned AbbrevNumber = Die->getAbbrevNumber();
2199 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2202 Die->setOffset(Offset);
2204 // Start the size with the size of abbreviation code.
2205 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2207 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2208 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2210 // Size the DIE attribute values.
2211 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2212 // Size attribute value.
2213 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2215 // Size the DIE children if any.
2216 if (!Children.empty()) {
2217 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2218 "Children flag not set");
2220 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2221 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2223 // End of children marker.
2224 Offset += sizeof(int8_t);
2227 Die->setSize(Offset - Die->getOffset());
2231 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2233 void DwarfDebug::computeSizeAndOffsets() {
2234 // Compute size of compile unit header.
2235 static unsigned Offset =
2236 sizeof(int32_t) + // Length of Compilation Unit Info
2237 sizeof(int16_t) + // DWARF version number
2238 sizeof(int32_t) + // Offset Into Abbrev. Section
2239 sizeof(int8_t); // Pointer Size (in bytes)
2241 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2242 CompileUnitOffsets[ModuleCU] = 0;
2245 /// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
2246 /// tools to recognize the object file contains Dwarf information.
2247 void DwarfDebug::emitInitial() {
2248 // Check to see if we already emitted intial headers.
2249 if (didInitial) return;
2252 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2254 // Dwarf sections base addresses.
2255 if (MAI->doesDwarfRequireFrameSection()) {
2256 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2257 EmitLabel("section_debug_frame", 0);
2260 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2261 EmitLabel("section_info", 0);
2262 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2263 EmitLabel("section_abbrev", 0);
2264 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2265 EmitLabel("section_aranges", 0);
2267 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2268 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2269 EmitLabel("section_macinfo", 0);
2272 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2273 EmitLabel("section_line", 0);
2274 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2275 EmitLabel("section_loc", 0);
2276 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2277 EmitLabel("section_pubnames", 0);
2278 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection());
2279 EmitLabel("section_pubtypes", 0);
2280 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2281 EmitLabel("section_str", 0);
2282 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2283 EmitLabel("section_ranges", 0);
2285 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2286 EmitLabel("text_begin", 0);
2287 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2288 EmitLabel("data_begin", 0);
2291 /// emitDIE - Recusively Emits a debug information entry.
2293 void DwarfDebug::emitDIE(DIE *Die) {
2294 // Get the abbreviation for this DIE.
2295 unsigned AbbrevNumber = Die->getAbbrevNumber();
2296 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2300 // Emit the code (index) for the abbreviation.
2301 Asm->EmitULEB128Bytes(AbbrevNumber);
2303 if (Asm->isVerbose())
2304 Asm->EOL(std::string("Abbrev [" +
2305 utostr(AbbrevNumber) +
2306 "] 0x" + utohexstr(Die->getOffset()) +
2307 ":0x" + utohexstr(Die->getSize()) + " " +
2308 dwarf::TagString(Abbrev->getTag())));
2312 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2313 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2315 // Emit the DIE attribute values.
2316 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2317 unsigned Attr = AbbrevData[i].getAttribute();
2318 unsigned Form = AbbrevData[i].getForm();
2319 assert(Form && "Too many attributes for DIE (check abbreviation)");
2322 case dwarf::DW_AT_sibling:
2323 Asm->EmitInt32(Die->getSiblingOffset());
2325 case dwarf::DW_AT_abstract_origin: {
2326 DIEEntry *E = cast<DIEEntry>(Values[i]);
2327 DIE *Origin = E->getEntry();
2328 unsigned Addr = Origin->getOffset();
2329 Asm->EmitInt32(Addr);
2333 // Emit an attribute using the defined form.
2334 Values[i]->EmitValue(this, Form);
2338 Asm->EOL(dwarf::AttributeString(Attr));
2341 // Emit the DIE children if any.
2342 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2343 const std::vector<DIE *> &Children = Die->getChildren();
2345 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2346 emitDIE(Children[j]);
2348 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2352 /// emitDebugInfo - Emit the debug info section.
2354 void DwarfDebug::emitDebugInfo() {
2355 // Start debug info section.
2356 Asm->OutStreamer.SwitchSection(
2357 Asm->getObjFileLowering().getDwarfInfoSection());
2358 DIE *Die = ModuleCU->getCUDie();
2360 // Emit the compile units header.
2361 EmitLabel("info_begin", ModuleCU->getID());
2363 // Emit size of content not including length itself
2364 unsigned ContentSize = Die->getSize() +
2365 sizeof(int16_t) + // DWARF version number
2366 sizeof(int32_t) + // Offset Into Abbrev. Section
2367 sizeof(int8_t) + // Pointer Size (in bytes)
2368 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2370 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2371 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2372 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2373 Asm->EOL("Offset Into Abbrev. Section");
2374 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2377 // FIXME - extra padding for gdb bug.
2378 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2379 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2380 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2381 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2382 EmitLabel("info_end", ModuleCU->getID());
2388 /// emitAbbreviations - Emit the abbreviation section.
2390 void DwarfDebug::emitAbbreviations() const {
2391 // Check to see if it is worth the effort.
2392 if (!Abbreviations.empty()) {
2393 // Start the debug abbrev section.
2394 Asm->OutStreamer.SwitchSection(
2395 Asm->getObjFileLowering().getDwarfAbbrevSection());
2397 EmitLabel("abbrev_begin", 0);
2399 // For each abbrevation.
2400 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2401 // Get abbreviation data
2402 const DIEAbbrev *Abbrev = Abbreviations[i];
2404 // Emit the abbrevations code (base 1 index.)
2405 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2406 Asm->EOL("Abbreviation Code");
2408 // Emit the abbreviations data.
2414 // Mark end of abbreviations.
2415 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2417 EmitLabel("abbrev_end", 0);
2422 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2423 /// the line matrix.
2425 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2426 // Define last address of section.
2427 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2428 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2429 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2430 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2432 // Mark end of matrix.
2433 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2434 Asm->EmitULEB128Bytes(1); Asm->EOL();
2435 Asm->EmitInt8(1); Asm->EOL();
2438 /// emitDebugLines - Emit source line information.
2440 void DwarfDebug::emitDebugLines() {
2441 // If the target is using .loc/.file, the assembler will be emitting the
2442 // .debug_line table automatically.
2443 if (MAI->hasDotLocAndDotFile())
2446 // Minimum line delta, thus ranging from -10..(255-10).
2447 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2448 // Maximum line delta, thus ranging from -10..(255-10).
2449 const int MaxLineDelta = 255 + MinLineDelta;
2451 // Start the dwarf line section.
2452 Asm->OutStreamer.SwitchSection(
2453 Asm->getObjFileLowering().getDwarfLineSection());
2455 // Construct the section header.
2456 EmitDifference("line_end", 0, "line_begin", 0, true);
2457 Asm->EOL("Length of Source Line Info");
2458 EmitLabel("line_begin", 0);
2460 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2462 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2463 Asm->EOL("Prolog Length");
2464 EmitLabel("line_prolog_begin", 0);
2466 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2468 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2470 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2472 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2474 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2476 // Line number standard opcode encodings argument count
2477 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2478 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2479 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2480 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2481 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2482 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2483 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2484 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2485 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2487 // Emit directories.
2488 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2489 Asm->EmitString(getSourceDirectoryName(DI));
2490 Asm->EOL("Directory");
2493 Asm->EmitInt8(0); Asm->EOL("End of directories");
2496 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2497 // Remember source id starts at 1.
2498 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2499 Asm->EmitString(getSourceFileName(Id.second));
2501 Asm->EmitULEB128Bytes(Id.first);
2502 Asm->EOL("Directory #");
2503 Asm->EmitULEB128Bytes(0);
2504 Asm->EOL("Mod date");
2505 Asm->EmitULEB128Bytes(0);
2506 Asm->EOL("File size");
2509 Asm->EmitInt8(0); Asm->EOL("End of files");
2511 EmitLabel("line_prolog_end", 0);
2513 // A sequence for each text section.
2514 unsigned SecSrcLinesSize = SectionSourceLines.size();
2516 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2517 // Isolate current sections line info.
2518 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2520 /*if (Asm->isVerbose()) {
2521 const MCSection *S = SectionMap[j + 1];
2522 O << '\t' << MAI->getCommentString() << " Section"
2523 << S->getName() << '\n';
2527 // Dwarf assumes we start with first line of first source file.
2528 unsigned Source = 1;
2531 // Construct rows of the address, source, line, column matrix.
2532 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2533 const SrcLineInfo &LineInfo = LineInfos[i];
2534 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2535 if (!LabelID) continue;
2537 if (LineInfo.getLine() == 0) continue;
2539 if (!Asm->isVerbose())
2542 std::pair<unsigned, unsigned> SourceID =
2543 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2544 O << '\t' << MAI->getCommentString() << ' '
2545 << getSourceDirectoryName(SourceID.first) << '/'
2546 << getSourceFileName(SourceID.second)
2547 << ':' << utostr_32(LineInfo.getLine()) << '\n';
2550 // Define the line address.
2551 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2552 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2553 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2554 EmitReference("label", LabelID); Asm->EOL("Location label");
2556 // If change of source, then switch to the new source.
2557 if (Source != LineInfo.getSourceID()) {
2558 Source = LineInfo.getSourceID();
2559 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2560 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2563 // If change of line.
2564 if (Line != LineInfo.getLine()) {
2565 // Determine offset.
2566 int Offset = LineInfo.getLine() - Line;
2567 int Delta = Offset - MinLineDelta;
2570 Line = LineInfo.getLine();
2572 // If delta is small enough and in range...
2573 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2574 // ... then use fast opcode.
2575 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2577 // ... otherwise use long hand.
2578 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2579 Asm->EOL("DW_LNS_advance_line");
2580 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2581 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2584 // Copy the previous row (different address or source)
2585 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2589 emitEndOfLineMatrix(j + 1);
2592 if (SecSrcLinesSize == 0)
2593 // Because we're emitting a debug_line section, we still need a line
2594 // table. The linker and friends expect it to exist. If there's nothing to
2595 // put into it, emit an empty table.
2596 emitEndOfLineMatrix(1);
2598 EmitLabel("line_end", 0);
2602 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2604 void DwarfDebug::emitCommonDebugFrame() {
2605 if (!MAI->doesDwarfRequireFrameSection())
2609 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2610 TargetFrameInfo::StackGrowsUp ?
2611 TD->getPointerSize() : -TD->getPointerSize();
2613 // Start the dwarf frame section.
2614 Asm->OutStreamer.SwitchSection(
2615 Asm->getObjFileLowering().getDwarfFrameSection());
2617 EmitLabel("debug_frame_common", 0);
2618 EmitDifference("debug_frame_common_end", 0,
2619 "debug_frame_common_begin", 0, true);
2620 Asm->EOL("Length of Common Information Entry");
2622 EmitLabel("debug_frame_common_begin", 0);
2623 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2624 Asm->EOL("CIE Identifier Tag");
2625 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2626 Asm->EOL("CIE Version");
2627 Asm->EmitString("");
2628 Asm->EOL("CIE Augmentation");
2629 Asm->EmitULEB128Bytes(1);
2630 Asm->EOL("CIE Code Alignment Factor");
2631 Asm->EmitSLEB128Bytes(stackGrowth);
2632 Asm->EOL("CIE Data Alignment Factor");
2633 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2634 Asm->EOL("CIE RA Column");
2636 std::vector<MachineMove> Moves;
2637 RI->getInitialFrameState(Moves);
2639 EmitFrameMoves(NULL, 0, Moves, false);
2641 Asm->EmitAlignment(2, 0, 0, false);
2642 EmitLabel("debug_frame_common_end", 0);
2647 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2650 DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2651 if (!MAI->doesDwarfRequireFrameSection())
2654 // Start the dwarf frame section.
2655 Asm->OutStreamer.SwitchSection(
2656 Asm->getObjFileLowering().getDwarfFrameSection());
2658 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2659 "debug_frame_begin", DebugFrameInfo.Number, true);
2660 Asm->EOL("Length of Frame Information Entry");
2662 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2664 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2666 Asm->EOL("FDE CIE offset");
2668 EmitReference("func_begin", DebugFrameInfo.Number);
2669 Asm->EOL("FDE initial location");
2670 EmitDifference("func_end", DebugFrameInfo.Number,
2671 "func_begin", DebugFrameInfo.Number);
2672 Asm->EOL("FDE address range");
2674 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2677 Asm->EmitAlignment(2, 0, 0, false);
2678 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2683 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2685 void DwarfDebug::emitDebugPubNames() {
2686 // Start the dwarf pubnames section.
2687 Asm->OutStreamer.SwitchSection(
2688 Asm->getObjFileLowering().getDwarfPubNamesSection());
2690 EmitDifference("pubnames_end", ModuleCU->getID(),
2691 "pubnames_begin", ModuleCU->getID(), true);
2692 Asm->EOL("Length of Public Names Info");
2694 EmitLabel("pubnames_begin", ModuleCU->getID());
2696 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2698 EmitSectionOffset("info_begin", "section_info",
2699 ModuleCU->getID(), 0, true, false);
2700 Asm->EOL("Offset of Compilation Unit Info");
2702 EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
2704 Asm->EOL("Compilation Unit Length");
2706 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
2707 for (StringMap<DIE*>::const_iterator
2708 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2709 const char *Name = GI->getKeyData();
2710 DIE * Entity = GI->second;
2712 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2713 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2716 Asm->EmitInt32(0); Asm->EOL("End Mark");
2717 EmitLabel("pubnames_end", ModuleCU->getID());
2722 void DwarfDebug::emitDebugPubTypes() {
2723 // Start the dwarf pubnames section.
2724 Asm->OutStreamer.SwitchSection(
2725 Asm->getObjFileLowering().getDwarfPubTypesSection());
2726 EmitDifference("pubtypes_end", ModuleCU->getID(),
2727 "pubtypes_begin", ModuleCU->getID(), true);
2728 Asm->EOL("Length of Public Types Info");
2730 EmitLabel("pubtypes_begin", ModuleCU->getID());
2732 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2734 EmitSectionOffset("info_begin", "section_info",
2735 ModuleCU->getID(), 0, true, false);
2736 Asm->EOL("Offset of Compilation ModuleCU Info");
2738 EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
2740 Asm->EOL("Compilation ModuleCU Length");
2742 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
2743 for (StringMap<DIE*>::const_iterator
2744 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2745 const char *Name = GI->getKeyData();
2746 DIE * Entity = GI->second;
2748 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2749 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2752 Asm->EmitInt32(0); Asm->EOL("End Mark");
2753 EmitLabel("pubtypes_end", ModuleCU->getID());
2758 /// emitDebugStr - Emit visible names into a debug str section.
2760 void DwarfDebug::emitDebugStr() {
2761 // Check to see if it is worth the effort.
2762 if (!StringPool.empty()) {
2763 // Start the dwarf str section.
2764 Asm->OutStreamer.SwitchSection(
2765 Asm->getObjFileLowering().getDwarfStrSection());
2767 // For each of strings in the string pool.
2768 for (unsigned StringID = 1, N = StringPool.size();
2769 StringID <= N; ++StringID) {
2770 // Emit a label for reference from debug information entries.
2771 EmitLabel("string", StringID);
2773 // Emit the string itself.
2774 const std::string &String = StringPool[StringID];
2775 Asm->EmitString(String); Asm->EOL();
2782 /// emitDebugLoc - Emit visible names into a debug loc section.
2784 void DwarfDebug::emitDebugLoc() {
2785 // Start the dwarf loc section.
2786 Asm->OutStreamer.SwitchSection(
2787 Asm->getObjFileLowering().getDwarfLocSection());
2791 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2793 void DwarfDebug::EmitDebugARanges() {
2794 // Start the dwarf aranges section.
2795 Asm->OutStreamer.SwitchSection(
2796 Asm->getObjFileLowering().getDwarfARangesSection());
2800 CompileUnit *Unit = GetBaseCompileUnit();
2802 // Don't include size of length
2803 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2805 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2807 EmitReference("info_begin", Unit->getID());
2808 Asm->EOL("Offset of Compilation Unit Info");
2810 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2812 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2814 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2815 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2818 EmitReference("text_begin", 0); Asm->EOL("Address");
2819 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2821 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2822 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2828 /// emitDebugRanges - Emit visible names into a debug ranges section.
2830 void DwarfDebug::emitDebugRanges() {
2831 // Start the dwarf ranges section.
2832 Asm->OutStreamer.SwitchSection(
2833 Asm->getObjFileLowering().getDwarfRangesSection());
2837 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2839 void DwarfDebug::emitDebugMacInfo() {
2840 if (const MCSection *LineInfo =
2841 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2842 // Start the dwarf macinfo section.
2843 Asm->OutStreamer.SwitchSection(LineInfo);
2848 /// emitDebugInlineInfo - Emit inline info using following format.
2850 /// 1. length of section
2851 /// 2. Dwarf version number
2852 /// 3. address size.
2854 /// Entries (one "entry" for each function that was inlined):
2856 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2857 /// otherwise offset into __debug_str for regular function name.
2858 /// 2. offset into __debug_str section for regular function name.
2859 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2860 /// instances for the function.
2862 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2863 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2864 /// __debug_info section, and the low_pc is the starting address for the
2865 /// inlining instance.
2866 void DwarfDebug::emitDebugInlineInfo() {
2867 if (!MAI->doesDwarfUsesInlineInfoSection())
2873 Asm->OutStreamer.SwitchSection(
2874 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2876 EmitDifference("debug_inlined_end", 1,
2877 "debug_inlined_begin", 1, true);
2878 Asm->EOL("Length of Debug Inlined Information Entry");
2880 EmitLabel("debug_inlined_begin", 1);
2882 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2883 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2885 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2886 E = InlinedSPNodes.end(); I != E; ++I) {
2888 // for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
2889 // I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2891 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2892 = InlineInfo.find(Node);
2893 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2894 DISubprogram SP(Node);
2895 StringRef LName = SP.getLinkageName();
2896 StringRef Name = SP.getName();
2899 Asm->EmitString(Name);
2901 // Skip special LLVM prefix that is used to inform the asm printer to not
2902 // emit usual symbol prefix before the symbol name. This happens for
2903 // Objective-C symbol names and symbol whose name is replaced using GCC's
2904 // __asm__ attribute.
2906 LName = LName.substr(1);
2907 // Asm->EmitString(LName);
2908 EmitSectionOffset("string", "section_str",
2909 StringPool.idFor(LName), false, true);
2912 Asm->EOL("MIPS linkage name");
2913 // Asm->EmitString(Name);
2914 EmitSectionOffset("string", "section_str",
2915 StringPool.idFor(Name), false, true);
2916 Asm->EOL("Function name");
2917 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2919 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2920 LE = Labels.end(); LI != LE; ++LI) {
2921 DIE *SP = LI->second;
2922 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2924 if (TD->getPointerSize() == sizeof(int32_t))
2925 O << MAI->getData32bitsDirective();
2927 O << MAI->getData64bitsDirective();
2929 PrintLabelName("label", LI->first); Asm->EOL("low_pc");
2933 EmitLabel("debug_inlined_end", 1);