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 /// addType - Add a new type attribute to the specified entity.
742 void DwarfDebug::addType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
746 // Check for pre-existence.
747 DIEEntry *Entry = DW_Unit->getDIEEntry(Ty.getNode());
749 // If it exists then use the existing value.
751 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
756 Entry = createDIEEntry();
757 DW_Unit->insertDIEEntry(Ty.getNode(), Entry);
760 DIE *Buffer = new DIE(dwarf::DW_TAG_base_type);
761 ModuleCU->insertDIE(Ty.getNode(), Buffer);
762 if (Ty.isBasicType())
763 constructTypeDIE(DW_Unit, *Buffer, DIBasicType(Ty.getNode()));
764 else if (Ty.isCompositeType())
765 constructTypeDIE(DW_Unit, *Buffer, DICompositeType(Ty.getNode()));
767 assert(Ty.isDerivedType() && "Unknown kind of DIType");
768 constructTypeDIE(DW_Unit, *Buffer, DIDerivedType(Ty.getNode()));
771 // Add debug information entry to entity and appropriate context.
773 DIDescriptor Context = Ty.getContext();
774 if (!Context.isNull())
775 Die = DW_Unit->getDIE(Context.getNode());
778 Die->addChild(Buffer);
780 DW_Unit->addDie(Buffer);
781 Entry->setEntry(Buffer);
782 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
785 /// constructTypeDIE - Construct basic type die from DIBasicType.
786 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
788 // Get core information.
789 StringRef Name = BTy.getName();
790 Buffer.setTag(dwarf::DW_TAG_base_type);
791 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
794 // Add name if not anonymous or intermediate type.
796 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
797 uint64_t Size = BTy.getSizeInBits() >> 3;
798 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
801 /// constructTypeDIE - Construct derived type die from DIDerivedType.
802 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
804 // Get core information.
805 StringRef Name = DTy.getName();
806 uint64_t Size = DTy.getSizeInBits() >> 3;
807 unsigned Tag = DTy.getTag();
809 // FIXME - Workaround for templates.
810 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
814 // Map to main type, void will not have a type.
815 DIType FromTy = DTy.getTypeDerivedFrom();
816 addType(DW_Unit, &Buffer, FromTy);
818 // Add name if not anonymous or intermediate type.
820 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
822 // Add size if non-zero (derived types might be zero-sized.)
824 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
826 // Add source line info if available and TyDesc is not a forward declaration.
827 if (!DTy.isForwardDecl())
828 addSourceLine(&Buffer, &DTy);
831 /// constructTypeDIE - Construct type DIE from DICompositeType.
832 void DwarfDebug::constructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
833 DICompositeType CTy) {
834 // Get core information.
835 StringRef Name = CTy.getName();
837 uint64_t Size = CTy.getSizeInBits() >> 3;
838 unsigned Tag = CTy.getTag();
842 case dwarf::DW_TAG_vector_type:
843 case dwarf::DW_TAG_array_type:
844 constructArrayTypeDIE(DW_Unit, Buffer, &CTy);
846 case dwarf::DW_TAG_enumeration_type: {
847 DIArray Elements = CTy.getTypeArray();
849 // Add enumerators to enumeration type.
850 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
852 DIEnumerator Enum(Elements.getElement(i).getNode());
853 if (!Enum.isNull()) {
854 ElemDie = constructEnumTypeDIE(DW_Unit, &Enum);
855 Buffer.addChild(ElemDie);
860 case dwarf::DW_TAG_subroutine_type: {
862 DIArray Elements = CTy.getTypeArray();
863 DIDescriptor RTy = Elements.getElement(0);
864 addType(DW_Unit, &Buffer, DIType(RTy.getNode()));
866 // Add prototype flag.
867 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
870 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
871 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
872 DIDescriptor Ty = Elements.getElement(i);
873 addType(DW_Unit, Arg, DIType(Ty.getNode()));
874 Buffer.addChild(Arg);
878 case dwarf::DW_TAG_structure_type:
879 case dwarf::DW_TAG_union_type:
880 case dwarf::DW_TAG_class_type: {
881 // Add elements to structure type.
882 DIArray Elements = CTy.getTypeArray();
884 // A forward struct declared type may not have elements available.
885 if (Elements.isNull())
888 // Add elements to structure type.
889 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
890 DIDescriptor Element = Elements.getElement(i);
891 if (Element.isNull())
894 if (Element.getTag() == dwarf::DW_TAG_subprogram)
895 ElemDie = createMemberSubprogramDIE(DW_Unit,
896 DISubprogram(Element.getNode()));
898 ElemDie = createMemberDIE(DW_Unit,
899 DIDerivedType(Element.getNode()));
900 Buffer.addChild(ElemDie);
903 if (CTy.isAppleBlockExtension())
904 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
906 unsigned RLang = CTy.getRunTimeLang();
908 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
909 dwarf::DW_FORM_data1, RLang);
916 // Add name if not anonymous or intermediate type.
918 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
920 if (Tag == dwarf::DW_TAG_enumeration_type ||
921 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
922 // Add size if non-zero (derived types might be zero-sized.)
924 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
926 // Add zero size if it is not a forward declaration.
927 if (CTy.isForwardDecl())
928 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
930 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
933 // Add source line info if available.
934 if (!CTy.isForwardDecl())
935 addSourceLine(&Buffer, &CTy);
939 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
940 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
941 int64_t L = SR.getLo();
942 int64_t H = SR.getHi();
943 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
945 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
947 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
948 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
950 Buffer.addChild(DW_Subrange);
953 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
954 void DwarfDebug::constructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
955 DICompositeType *CTy) {
956 Buffer.setTag(dwarf::DW_TAG_array_type);
957 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
958 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
960 // Emit derived type.
961 addType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
962 DIArray Elements = CTy->getTypeArray();
964 // Get an anonymous type for index type.
965 DIE *IdxTy = DW_Unit->getIndexTyDie();
967 // Construct an anonymous type for index type.
968 IdxTy = new DIE(dwarf::DW_TAG_base_type);
969 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
970 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
971 dwarf::DW_ATE_signed);
972 DW_Unit->addDie(IdxTy);
973 DW_Unit->setIndexTyDie(IdxTy);
976 // Add subranges to array type.
977 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
978 DIDescriptor Element = Elements.getElement(i);
979 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
980 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
984 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
985 DIE *DwarfDebug::constructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
986 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
987 StringRef Name = ETy->getName();
988 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
989 int64_t Value = ETy->getEnumValue();
990 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
994 /// createGlobalVariableDIE - Create new DIE using GV.
995 DIE *DwarfDebug::createGlobalVariableDIE(CompileUnit *DW_Unit,
996 const DIGlobalVariable &GV) {
997 // If the global variable was optmized out then no need to create debug info
999 if (!GV.getGlobal()) return NULL;
1000 if (GV.getDisplayName().empty()) return NULL;
1002 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1003 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1004 GV.getDisplayName());
1006 StringRef LinkageName = GV.getLinkageName();
1007 if (!LinkageName.empty()) {
1008 // Skip special LLVM prefix that is used to inform the asm printer to not
1009 // emit usual symbol prefix before the symbol name. This happens for
1010 // Objective-C symbol names and symbol whose name is replaced using GCC's
1011 // __asm__ attribute.
1012 if (LinkageName[0] == 1)
1013 LinkageName = LinkageName.substr(1);
1014 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1017 addType(DW_Unit, GVDie, GV.getType());
1018 if (!GV.isLocalToUnit())
1019 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1020 addSourceLine(GVDie, &GV);
1023 DIEBlock *Block = new DIEBlock();
1024 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1025 addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1026 Asm->Mang->getMangledName(GV.getGlobal()));
1027 addBlock(GVDie, dwarf::DW_AT_location, 0, Block);
1032 /// createMemberDIE - Create new member DIE.
1033 DIE *DwarfDebug::createMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
1034 DIE *MemberDie = new DIE(DT.getTag());
1035 StringRef Name = DT.getName();
1037 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1039 addType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1041 addSourceLine(MemberDie, &DT);
1043 DIEBlock *MemLocationDie = new DIEBlock();
1044 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1046 uint64_t Size = DT.getSizeInBits();
1047 uint64_t FieldSize = DT.getOriginalTypeSize();
1049 if (Size != FieldSize) {
1051 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1052 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1054 uint64_t Offset = DT.getOffsetInBits();
1055 uint64_t FieldOffset = Offset;
1056 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1057 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1058 FieldOffset = (HiMark - FieldSize);
1059 Offset -= FieldOffset;
1061 // Maybe we need to work from the other end.
1062 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1063 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1065 // Here WD_AT_data_member_location points to the anonymous
1066 // field that includes this bit field.
1067 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1070 // This is not a bitfield.
1071 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1073 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1075 if (DT.isProtected())
1076 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1077 dwarf::DW_ACCESS_protected);
1078 else if (DT.isPrivate())
1079 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1080 dwarf::DW_ACCESS_private);
1081 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1082 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1083 dwarf::DW_ACCESS_public);
1085 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1086 dwarf::DW_VIRTUALITY_virtual);
1090 /// createRawSubprogramDIE - Create new partially incomplete DIE. This is
1091 /// a helper routine used by createMemberSubprogramDIE and
1092 /// createSubprogramDIE.
1093 DIE *DwarfDebug::createRawSubprogramDIE(CompileUnit *DW_Unit,
1094 const DISubprogram &SP) {
1095 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
1096 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1098 StringRef LinkageName = SP.getLinkageName();
1099 if (!LinkageName.empty()) {
1100 // Skip special LLVM prefix that is used to inform the asm printer to not
1101 // emit usual symbol prefix before the symbol name. This happens for
1102 // Objective-C symbol names and symbol whose name is replaced using GCC's
1103 // __asm__ attribute.
1104 if (LinkageName[0] == 1)
1105 LinkageName = LinkageName.substr(1);
1106 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1109 addSourceLine(SPDie, &SP);
1111 // Add prototyped tag, if C or ObjC.
1112 unsigned Lang = SP.getCompileUnit().getLanguage();
1113 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1114 Lang == dwarf::DW_LANG_ObjC)
1115 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1118 DICompositeType SPTy = SP.getType();
1119 DIArray Args = SPTy.getTypeArray();
1120 unsigned SPTag = SPTy.getTag();
1122 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
1123 addType(DW_Unit, SPDie, SPTy);
1125 addType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
1127 unsigned VK = SP.getVirtuality();
1129 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1130 DIEBlock *Block = new DIEBlock();
1131 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1132 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1133 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1134 ContainingTypeMap.insert(std::make_pair(SPDie, WeakVH(SP.getContainingType().getNode())));
1140 /// createMemberSubprogramDIE - Create new member DIE using SP. This routine
1141 /// always returns a die with DW_AT_declaration attribute.
1142 DIE *DwarfDebug::createMemberSubprogramDIE(CompileUnit *DW_Unit,
1143 const DISubprogram &SP) {
1144 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1146 SPDie = createSubprogramDIE(DW_Unit, SP);
1148 // If SPDie has DW_AT_declaration then reuse it.
1149 if (!SP.isDefinition())
1152 // Otherwise create new DIE for the declaration. First push definition
1153 // DIE at the top level.
1154 if (TopLevelDIEs.insert(SPDie))
1155 TopLevelDIEsVector.push_back(SPDie);
1157 SPDie = createRawSubprogramDIE(DW_Unit, SP);
1160 DICompositeType SPTy = SP.getType();
1161 DIArray Args = SPTy.getTypeArray();
1162 unsigned SPTag = SPTy.getTag();
1163 if (SPTag == dwarf::DW_TAG_subroutine_type)
1164 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1165 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1166 addType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1167 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1168 SPDie->addChild(Arg);
1171 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1175 /// createSubprogramDIE - Create new DIE using SP.
1176 DIE *DwarfDebug::createSubprogramDIE(CompileUnit *DW_Unit,
1177 const DISubprogram &SP) {
1178 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1182 SPDie = createRawSubprogramDIE(DW_Unit, SP);
1184 if (!SP.isDefinition()) {
1185 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1187 // Add arguments. Do not add arguments for subprogram definition. They will
1188 // be handled while processing variables.
1189 DICompositeType SPTy = SP.getType();
1190 DIArray Args = SPTy.getTypeArray();
1191 unsigned SPTag = SPTy.getTag();
1193 if (SPTag == dwarf::DW_TAG_subroutine_type)
1194 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1195 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1196 addType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
1197 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
1198 SPDie->addChild(Arg);
1202 // DW_TAG_inlined_subroutine may refer to this DIE.
1203 DW_Unit->insertDIE(SP.getNode(), SPDie);
1207 /// findCompileUnit - Get the compile unit for the given descriptor.
1209 CompileUnit &DwarfDebug::findCompileUnit(DICompileUnit Unit) const {
1210 DenseMap<Value *, CompileUnit *>::const_iterator I =
1211 CompileUnitMap.find(Unit.getNode());
1212 assert(I != CompileUnitMap.end() && "Missing compile unit.");
1216 /// createDbgScopeVariable - Create a new scope variable.
1218 DIE *DwarfDebug::createDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1219 // Get the descriptor.
1220 const DIVariable &VD = DV->getVariable();
1221 StringRef Name = VD.getName();
1225 // Translate tag to proper Dwarf tag. The result variable is dropped for
1228 switch (VD.getTag()) {
1229 case dwarf::DW_TAG_return_variable:
1231 case dwarf::DW_TAG_arg_variable:
1232 Tag = dwarf::DW_TAG_formal_parameter;
1234 case dwarf::DW_TAG_auto_variable: // fall thru
1236 Tag = dwarf::DW_TAG_variable;
1240 // Define variable debug information entry.
1241 DIE *VariableDie = new DIE(Tag);
1242 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1244 // Add source line info if available.
1245 addSourceLine(VariableDie, &VD);
1247 // Add variable type.
1248 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1249 // addresses instead.
1250 if (VD.isBlockByrefVariable())
1251 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name));
1253 addType(Unit, VariableDie, VD.getType());
1255 // Add variable address.
1256 // Variables for abstract instances of inlined functions don't get a
1258 MachineLocation Location;
1260 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1261 Location.set(FrameReg, Offset);
1264 if (VD.hasComplexAddress())
1265 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1266 else if (VD.isBlockByrefVariable())
1267 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1269 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1274 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1275 /// Initialize scope and update scope hierarchy.
1276 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1277 MDNode *InlinedAt) {
1278 assert (N && "Invalid Scope encoding!");
1279 assert (MI && "Missing machine instruction!");
1280 bool GetConcreteScope = (MI && InlinedAt);
1282 DbgScope *NScope = NULL;
1285 NScope = DbgScopeMap.lookup(InlinedAt);
1287 NScope = DbgScopeMap.lookup(N);
1288 assert (NScope && "Unable to find working scope!");
1290 if (NScope->getFirstInsn())
1293 DbgScope *Parent = NULL;
1294 if (GetConcreteScope) {
1295 DILocation IL(InlinedAt);
1296 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1297 IL.getOrigLocation().getNode());
1298 assert (Parent && "Unable to find Parent scope!");
1299 NScope->setParent(Parent);
1300 Parent->addScope(NScope);
1301 } else if (DIDescriptor(N).isLexicalBlock()) {
1302 DILexicalBlock DB(N);
1303 if (!DB.getContext().isNull()) {
1304 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1305 NScope->setParent(Parent);
1306 Parent->addScope(NScope);
1310 NScope->setFirstInsn(MI);
1312 if (!Parent && !InlinedAt) {
1313 StringRef SPName = DISubprogram(N).getLinkageName();
1314 if (SPName == MF->getFunction()->getName())
1315 CurrentFnDbgScope = NScope;
1318 if (GetConcreteScope) {
1319 ConcreteScopes[InlinedAt] = NScope;
1320 getOrCreateAbstractScope(N);
1326 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1327 assert (N && "Invalid Scope encoding!");
1329 DbgScope *AScope = AbstractScopes.lookup(N);
1333 DbgScope *Parent = NULL;
1335 DIDescriptor Scope(N);
1336 if (Scope.isLexicalBlock()) {
1337 DILexicalBlock DB(N);
1338 DIDescriptor ParentDesc = DB.getContext();
1339 if (!ParentDesc.isNull())
1340 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1343 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1346 Parent->addScope(AScope);
1347 AScope->setAbstractScope();
1348 AbstractScopes[N] = AScope;
1349 if (DIDescriptor(N).isSubprogram())
1350 AbstractScopesList.push_back(AScope);
1354 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1355 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1356 /// If there are global variables in this scope then create and insert
1357 /// DIEs for these variables.
1358 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1360 DIE *SPDie = ModuleCU->getDIE(SPNode);
1361 assert (SPDie && "Unable to find subprogram DIE!");
1362 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1363 DWLabel("func_begin", SubprogramCount));
1364 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1365 DWLabel("func_end", SubprogramCount));
1366 MachineLocation Location(RI->getFrameRegister(*MF));
1367 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1369 if (!DISubprogram(SPNode).isLocalToUnit())
1370 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1372 // If there are global variables at this scope then add their dies.
1373 for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(),
1374 SGE = ScopedGVs.end(); SGI != SGE; ++SGI) {
1375 MDNode *N = dyn_cast_or_null<MDNode>(*SGI);
1377 DIGlobalVariable GV(N);
1378 if (GV.getContext().getNode() == SPNode) {
1379 DIE *ScopedGVDie = createGlobalVariableDIE(ModuleCU, GV);
1381 SPDie->addChild(ScopedGVDie);
1388 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1389 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1390 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1391 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1392 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1394 // Ignore empty scopes.
1395 if (StartID == EndID && StartID != 0)
1398 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1399 if (Scope->isAbstractScope())
1402 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1404 DWLabel("label", StartID)
1405 : DWLabel("func_begin", SubprogramCount));
1406 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1408 DWLabel("label", EndID)
1409 : DWLabel("func_end", SubprogramCount));
1416 /// constructInlinedScopeDIE - This scope represents inlined body of
1417 /// a function. Construct DIE to represent this concrete inlined copy
1418 /// of the function.
1419 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1420 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1421 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1422 assert (StartID && "Invalid starting label for an inlined scope!");
1423 assert (EndID && "Invalid end label for an inlined scope!");
1424 // Ignore empty scopes.
1425 if (StartID == EndID && StartID != 0)
1428 DIScope DS(Scope->getScopeNode());
1431 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1433 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1434 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1435 assert (OriginDIE && "Unable to find Origin DIE!");
1436 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1437 dwarf::DW_FORM_ref4, OriginDIE);
1439 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1440 DWLabel("label", StartID));
1441 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1442 DWLabel("label", EndID));
1444 InlinedSubprogramDIEs.insert(OriginDIE);
1446 // Track the start label for this inlined function.
1447 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1448 I = InlineInfo.find(InlinedSP.getNode());
1450 if (I == InlineInfo.end()) {
1451 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID,
1453 InlinedSPNodes.push_back(InlinedSP.getNode());
1455 I->second.push_back(std::make_pair(StartID, ScopeDIE));
1457 StringPool.insert(InlinedSP.getName());
1458 StringPool.insert(InlinedSP.getLinkageName());
1459 DILocation DL(Scope->getInlinedAt());
1460 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1461 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1467 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1468 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV,
1469 DbgScope *Scope, CompileUnit *Unit) {
1470 // Get the descriptor.
1471 const DIVariable &VD = DV->getVariable();
1472 StringRef Name = VD.getName();
1476 // Translate tag to proper Dwarf tag. The result variable is dropped for
1479 switch (VD.getTag()) {
1480 case dwarf::DW_TAG_return_variable:
1482 case dwarf::DW_TAG_arg_variable:
1483 Tag = dwarf::DW_TAG_formal_parameter;
1485 case dwarf::DW_TAG_auto_variable: // fall thru
1487 Tag = dwarf::DW_TAG_variable;
1491 // Define variable debug information entry.
1492 DIE *VariableDie = new DIE(Tag);
1496 if (DbgVariable *AV = DV->getAbstractVariable())
1497 AbsDIE = AV->getDIE();
1500 DIScope DS(Scope->getScopeNode());
1501 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1502 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1504 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1505 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1506 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1507 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1508 dwarf::DW_FORM_ref4, AbsDIE);
1511 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1512 addSourceLine(VariableDie, &VD);
1514 // Add variable type.
1515 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1516 // addresses instead.
1517 if (VD.isBlockByrefVariable())
1518 addType(Unit, VariableDie, getBlockByrefType(VD.getType(), Name));
1520 addType(Unit, VariableDie, VD.getType());
1523 // Add variable address.
1524 if (!Scope->isAbstractScope()) {
1525 MachineLocation Location;
1527 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1528 Location.set(FrameReg, Offset);
1530 if (VD.hasComplexAddress())
1531 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1532 else if (VD.isBlockByrefVariable())
1533 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1535 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1537 DV->setDIE(VariableDie);
1542 void DwarfDebug::addPubTypes(DISubprogram SP) {
1543 DICompositeType SPTy = SP.getType();
1544 unsigned SPTag = SPTy.getTag();
1545 if (SPTag != dwarf::DW_TAG_subroutine_type)
1548 DIArray Args = SPTy.getTypeArray();
1552 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1553 DIType ATy(Args.getElement(i).getNode());
1556 DICompositeType CATy = getDICompositeType(ATy);
1557 if (!CATy.isNull() && !CATy.getName().empty()) {
1558 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1559 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1564 /// constructScopeDIE - Construct a DIE for this scope.
1565 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1568 DIScope DS(Scope->getScopeNode());
1572 DIE *ScopeDIE = NULL;
1573 if (Scope->getInlinedAt())
1574 ScopeDIE = constructInlinedScopeDIE(Scope);
1575 else if (DS.isSubprogram()) {
1576 if (Scope->isAbstractScope())
1577 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1579 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1582 ScopeDIE = constructLexicalScopeDIE(Scope);
1583 if (!ScopeDIE) return NULL;
1586 // Add variables to scope.
1587 SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1588 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1589 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope, ModuleCU);
1591 ScopeDIE->addChild(VariableDIE);
1594 // Add nested scopes.
1595 SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1596 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1597 // Define the Scope debug information entry.
1598 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1600 ScopeDIE->addChild(NestedDIE);
1603 if (DS.isSubprogram())
1604 addPubTypes(DISubprogram(DS.getNode()));
1609 /// GetOrCreateSourceID - Look up the source id with the given directory and
1610 /// source file names. If none currently exists, create a new id and insert it
1611 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1613 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) {
1615 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1616 if (DI != DirectoryIdMap.end()) {
1617 DId = DI->getValue();
1619 DId = DirectoryNames.size() + 1;
1620 DirectoryIdMap[DirName] = DId;
1621 DirectoryNames.push_back(DirName);
1625 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1626 if (FI != SourceFileIdMap.end()) {
1627 FId = FI->getValue();
1629 FId = SourceFileNames.size() + 1;
1630 SourceFileIdMap[FileName] = FId;
1631 SourceFileNames.push_back(FileName);
1634 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1635 SourceIdMap.find(std::make_pair(DId, FId));
1636 if (SI != SourceIdMap.end())
1639 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1640 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1641 SourceIds.push_back(std::make_pair(DId, FId));
1646 void DwarfDebug::constructCompileUnit(MDNode *N) {
1647 DICompileUnit DIUnit(N);
1648 StringRef FN = DIUnit.getFilename();
1649 StringRef Dir = DIUnit.getDirectory();
1650 unsigned ID = GetOrCreateSourceID(Dir, FN);
1652 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1653 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1654 DWLabel("section_line", 0), DWLabel("section_line", 0),
1656 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1657 DIUnit.getProducer());
1658 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1659 DIUnit.getLanguage());
1660 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1663 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1664 if (DIUnit.isOptimized())
1665 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1667 StringRef Flags = DIUnit.getFlags();
1669 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1671 unsigned RVer = DIUnit.getRunTimeVersion();
1673 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1674 dwarf::DW_FORM_data1, RVer);
1676 CompileUnit *Unit = new CompileUnit(ID, Die);
1677 if (!ModuleCU && DIUnit.isMain()) {
1678 // Use first compile unit marked as isMain as the compile unit
1683 CompileUnitMap[DIUnit.getNode()] = Unit;
1684 CompileUnits.push_back(Unit);
1687 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1688 DIGlobalVariable DI_GV(N);
1690 // If debug information is malformed then ignore it.
1691 if (DI_GV.Verify() == false)
1694 // Check for pre-existence.
1695 if (ModuleCU->getDIE(DI_GV.getNode()))
1698 DIE *VariableDie = createGlobalVariableDIE(ModuleCU, DI_GV);
1701 ModuleCU->insertDIE(N, VariableDie);
1703 // Add to context owner.
1704 if (TopLevelDIEs.insert(VariableDie))
1705 TopLevelDIEsVector.push_back(VariableDie);
1707 // Expose as global. FIXME - need to check external flag.
1708 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1710 DIType GTy = DI_GV.getType();
1711 if (GTy.isCompositeType() && !GTy.getName().empty()) {
1712 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1713 assert (Entry && "Missing global type!");
1714 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1719 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1722 // Check for pre-existence.
1723 if (ModuleCU->getDIE(N))
1726 if (!SP.isDefinition())
1727 // This is a method declaration which will be handled while constructing
1731 DIE *SubprogramDie = createSubprogramDIE(ModuleCU, SP);
1734 ModuleCU->insertDIE(N, SubprogramDie);
1736 // Add to context owner.
1737 if (SP.getContext().getNode() == SP.getCompileUnit().getNode())
1738 if (TopLevelDIEs.insert(SubprogramDie))
1739 TopLevelDIEsVector.push_back(SubprogramDie);
1741 // Expose as global.
1742 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1747 /// beginModule - Emit all Dwarf sections that should come prior to the
1748 /// content. Create global DIEs and emit initial debug info sections.
1749 /// This is inovked by the target AsmPrinter.
1750 void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1753 if (TimePassesIsEnabled)
1754 DebugTimer->startTimer();
1756 if (!MAI->doesSupportDebugInformation())
1759 DebugInfoFinder DbgFinder;
1760 DbgFinder.processModule(*M);
1762 // Create all the compile unit DIEs.
1763 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1764 E = DbgFinder.compile_unit_end(); I != E; ++I)
1765 constructCompileUnit(*I);
1767 if (CompileUnits.empty()) {
1768 if (TimePassesIsEnabled)
1769 DebugTimer->stopTimer();
1774 // If main compile unit for this module is not seen than randomly
1775 // select first compile unit.
1777 ModuleCU = CompileUnits[0];
1779 // Create DIEs for each of the externally visible global variables.
1780 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1781 E = DbgFinder.global_variable_end(); I != E; ++I) {
1782 DIGlobalVariable GV(*I);
1783 if (GV.getContext().getNode() != GV.getCompileUnit().getNode())
1784 ScopedGVs.push_back(*I);
1786 constructGlobalVariableDIE(*I);
1789 // Create DIEs for each subprogram.
1790 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1791 E = DbgFinder.subprogram_end(); I != E; ++I)
1792 constructSubprogramDIE(*I);
1796 MMI->setDebugInfoAvailability(true);
1798 // Prime section data.
1799 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1801 // Print out .file directives to specify files for .loc directives. These are
1802 // printed out early so that they precede any .loc directives.
1803 if (MAI->hasDotLocAndDotFile()) {
1804 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1805 // Remember source id starts at 1.
1806 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1807 sys::Path FullPath(getSourceDirectoryName(Id.first));
1809 FullPath.appendComponent(getSourceFileName(Id.second));
1810 assert(AppendOk && "Could not append filename to directory!");
1812 Asm->EmitFile(i, FullPath.str());
1817 // Emit initial sections
1820 if (TimePassesIsEnabled)
1821 DebugTimer->stopTimer();
1824 /// endModule - Emit all Dwarf sections that should come after the content.
1826 void DwarfDebug::endModule() {
1830 if (TimePassesIsEnabled)
1831 DebugTimer->startTimer();
1833 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1834 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1835 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1837 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1840 // Insert top level DIEs.
1841 for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(),
1842 TE = TopLevelDIEsVector.end(); TI != TE; ++TI)
1843 ModuleCU->getCUDie()->addChild(*TI);
1845 for (DenseMap<DIE *, WeakVH>::iterator CI = ContainingTypeMap.begin(),
1846 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1847 DIE *SPDie = CI->first;
1848 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1850 DIE *NDie = ModuleCU->getDIE(N);
1851 if (!NDie) continue;
1852 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1853 addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1856 // Standard sections final addresses.
1857 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1858 EmitLabel("text_end", 0);
1859 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1860 EmitLabel("data_end", 0);
1862 // End text sections.
1863 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1864 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1865 EmitLabel("section_end", i);
1868 // Emit common frame information.
1869 emitCommonDebugFrame();
1871 // Emit function debug frame information
1872 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1873 E = DebugFrames.end(); I != E; ++I)
1874 emitFunctionDebugFrame(*I);
1876 // Compute DIE offsets and sizes.
1877 computeSizeAndOffsets();
1879 // Emit all the DIEs into a debug info section
1882 // Corresponding abbreviations into a abbrev section.
1883 emitAbbreviations();
1885 // Emit source line correspondence into a debug line section.
1888 // Emit info into a debug pubnames section.
1889 emitDebugPubNames();
1891 // Emit info into a debug pubtypes section.
1892 emitDebugPubTypes();
1894 // Emit info into a debug str section.
1897 // Emit info into a debug loc section.
1900 // Emit info into a debug aranges section.
1903 // Emit info into a debug ranges section.
1906 // Emit info into a debug macinfo section.
1909 // Emit inline info.
1910 emitDebugInlineInfo();
1912 if (TimePassesIsEnabled)
1913 DebugTimer->stopTimer();
1916 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1917 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1919 DILocation &ScopeLoc) {
1921 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1923 return AbsDbgVariable;
1925 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1929 AbsDbgVariable = new DbgVariable(Var, FrameIdx);
1930 Scope->addVariable(AbsDbgVariable);
1931 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1932 return AbsDbgVariable;
1935 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1936 void DwarfDebug::collectVariableInfo() {
1939 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1940 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1941 VE = VMap.end(); VI != VE; ++VI) {
1942 MetadataBase *MB = VI->first;
1943 MDNode *Var = dyn_cast_or_null<MDNode>(MB);
1945 DIVariable DV (Var);
1946 std::pair< unsigned, MDNode *> VP = VI->second;
1947 DILocation ScopeLoc(VP.second);
1950 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1952 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1953 // If variable scope is not found then skip this variable.
1957 DbgVariable *RegVar = new DbgVariable(DV, VP.first);
1958 Scope->addVariable(RegVar);
1959 if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first,
1961 RegVar->setAbstractVariable(AbsDbgVariable);
1965 /// beginScope - Process beginning of a scope starting at Label.
1966 void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) {
1967 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1968 if (I == DbgScopeBeginMap.end())
1970 ScopeVector &SD = I->second;
1971 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1973 (*SDI)->setStartLabelID(Label);
1976 /// endScope - Process end of a scope.
1977 void DwarfDebug::endScope(const MachineInstr *MI) {
1978 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1979 if (I == DbgScopeEndMap.end())
1982 unsigned Label = MMI->NextLabelID();
1983 Asm->printLabel(Label);
1986 SmallVector<DbgScope *, 2> &SD = I->second;
1987 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1989 (*SDI)->setEndLabelID(Label);
1993 /// createDbgScope - Create DbgScope for the scope.
1994 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1997 DbgScope *WScope = DbgScopeMap.lookup(Scope);
2000 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2001 DbgScopeMap.insert(std::make_pair(Scope, WScope));
2002 if (DIDescriptor(Scope).isLexicalBlock())
2003 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
2007 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2011 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2012 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2013 DILocation DL(InlinedAt);
2014 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2017 /// extractScopeInformation - Scan machine instructions in this function
2018 /// and collect DbgScopes. Return true, if atleast one scope was found.
2019 bool DwarfDebug::extractScopeInformation(MachineFunction *MF) {
2020 // If scope information was extracted using .dbg intrinsics then there is not
2021 // any need to extract these information by scanning each instruction.
2022 if (!DbgScopeMap.empty())
2025 // Scan each instruction and create scopes. First build working set of scopes.
2026 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2028 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2030 const MachineInstr *MInsn = II;
2031 DebugLoc DL = MInsn->getDebugLoc();
2032 if (DL.isUnknown()) continue;
2033 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
2034 if (!DLT.Scope) continue;
2035 // There is no need to create another DIE for compile unit. For all
2036 // other scopes, create one DbgScope now. This will be translated
2037 // into a scope DIE at the end.
2038 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
2039 createDbgScope(DLT.Scope, DLT.InlinedAtLoc);
2044 // Build scope hierarchy using working set of scopes.
2045 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2047 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2049 const MachineInstr *MInsn = II;
2050 DebugLoc DL = MInsn->getDebugLoc();
2051 if (DL.isUnknown()) continue;
2052 DebugLocTuple DLT = MF->getDebugLocTuple(DL);
2053 if (!DLT.Scope) continue;
2054 // There is no need to create another DIE for compile unit. For all
2055 // other scopes, create one DbgScope now. This will be translated
2056 // into a scope DIE at the end.
2057 if (DIDescriptor(DLT.Scope).isCompileUnit()) continue;
2058 DbgScope *Scope = getUpdatedDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
2059 Scope->setLastInsn(MInsn);
2063 // If a scope's last instruction is not set then use its child scope's
2064 // last instruction as this scope's last instrunction.
2065 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2066 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2067 if (DI->second->isAbstractScope())
2069 assert (DI->second->getFirstInsn() && "Invalid first instruction!");
2070 DI->second->fixInstructionMarkers();
2071 assert (DI->second->getLastInsn() && "Invalid last instruction!");
2074 // Each scope has first instruction and last instruction to mark beginning
2075 // and end of a scope respectively. Create an inverse map that list scopes
2076 // starts (and ends) with an instruction. One instruction may start (or end)
2078 for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
2079 DE = DbgScopeMap.end(); DI != DE; ++DI) {
2080 DbgScope *S = DI->second;
2081 if (S->isAbstractScope())
2083 const MachineInstr *MI = S->getFirstInsn();
2084 assert (MI && "DbgScope does not have first instruction!");
2086 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
2087 if (IDI != DbgScopeBeginMap.end())
2088 IDI->second.push_back(S);
2090 DbgScopeBeginMap[MI].push_back(S);
2092 MI = S->getLastInsn();
2093 assert (MI && "DbgScope does not have last instruction!");
2094 IDI = DbgScopeEndMap.find(MI);
2095 if (IDI != DbgScopeEndMap.end())
2096 IDI->second.push_back(S);
2098 DbgScopeEndMap[MI].push_back(S);
2101 return !DbgScopeMap.empty();
2104 /// beginFunction - Gather pre-function debug information. Assumes being
2105 /// emitted immediately after the function entry point.
2106 void DwarfDebug::beginFunction(MachineFunction *MF) {
2109 if (!ShouldEmitDwarfDebug()) return;
2111 if (TimePassesIsEnabled)
2112 DebugTimer->startTimer();
2114 if (!extractScopeInformation(MF))
2117 collectVariableInfo();
2119 // Begin accumulating function debug information.
2120 MMI->BeginFunction(MF);
2122 // Assumes in correct section after the entry point.
2123 EmitLabel("func_begin", ++SubprogramCount);
2125 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2127 DebugLoc FDL = MF->getDefaultDebugLoc();
2128 if (!FDL.isUnknown()) {
2129 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2130 unsigned LabelID = 0;
2131 DISubprogram SP = getDISubprogram(DLT.Scope);
2133 LabelID = recordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
2135 LabelID = recordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
2136 Asm->printLabel(LabelID);
2139 if (TimePassesIsEnabled)
2140 DebugTimer->stopTimer();
2143 /// endFunction - Gather and emit post-function debug information.
2145 void DwarfDebug::endFunction(MachineFunction *MF) {
2146 if (!ShouldEmitDwarfDebug()) return;
2148 if (TimePassesIsEnabled)
2149 DebugTimer->startTimer();
2151 if (DbgScopeMap.empty())
2154 // Define end label for subprogram.
2155 EmitLabel("func_end", SubprogramCount);
2157 // Get function line info.
2158 if (!Lines.empty()) {
2159 // Get section line info.
2160 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2161 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2162 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2163 // Append the function info to section info.
2164 SectionLineInfos.insert(SectionLineInfos.end(),
2165 Lines.begin(), Lines.end());
2168 // Construct abstract scopes.
2169 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2170 AE = AbstractScopesList.end(); AI != AE; ++AI)
2171 constructScopeDIE(*AI);
2173 constructScopeDIE(CurrentFnDbgScope);
2175 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2176 MMI->getFrameMoves()));
2179 CurrentFnDbgScope = NULL;
2180 DbgScopeMap.clear();
2181 DbgScopeBeginMap.clear();
2182 DbgScopeEndMap.clear();
2183 ConcreteScopes.clear();
2184 AbstractScopesList.clear();
2188 if (TimePassesIsEnabled)
2189 DebugTimer->stopTimer();
2192 /// recordSourceLine - Records location information and associates it with a
2193 /// label. Returns a unique label ID used to generate a label and provide
2194 /// correspondence to the source line list.
2195 unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
2200 if (TimePassesIsEnabled)
2201 DebugTimer->startTimer();
2206 DIDescriptor Scope(S);
2207 if (Scope.isCompileUnit()) {
2208 DICompileUnit CU(S);
2209 Dir = CU.getDirectory();
2210 Fn = CU.getFilename();
2211 } else if (Scope.isSubprogram()) {
2213 Dir = SP.getDirectory();
2214 Fn = SP.getFilename();
2215 } else if (Scope.isLexicalBlock()) {
2216 DILexicalBlock DB(S);
2217 Dir = DB.getDirectory();
2218 Fn = DB.getFilename();
2220 assert (0 && "Unexpected scope info");
2222 unsigned Src = GetOrCreateSourceID(Dir, Fn);
2223 unsigned ID = MMI->NextLabelID();
2224 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2226 if (TimePassesIsEnabled)
2227 DebugTimer->stopTimer();
2232 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2233 /// timed. Look up the source id with the given directory and source file
2234 /// names. If none currently exists, create a new id and insert it in the
2235 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2237 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2238 const std::string &FileName) {
2239 if (TimePassesIsEnabled)
2240 DebugTimer->startTimer();
2242 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2244 if (TimePassesIsEnabled)
2245 DebugTimer->stopTimer();
2250 //===----------------------------------------------------------------------===//
2252 //===----------------------------------------------------------------------===//
2254 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2257 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2258 // Get the children.
2259 const std::vector<DIE *> &Children = Die->getChildren();
2261 // If not last sibling and has children then add sibling offset attribute.
2262 if (!Last && !Children.empty()) Die->addSiblingOffset();
2264 // Record the abbreviation.
2265 assignAbbrevNumber(Die->getAbbrev());
2267 // Get the abbreviation for this DIE.
2268 unsigned AbbrevNumber = Die->getAbbrevNumber();
2269 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2272 Die->setOffset(Offset);
2274 // Start the size with the size of abbreviation code.
2275 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2277 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2278 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2280 // Size the DIE attribute values.
2281 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2282 // Size attribute value.
2283 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2285 // Size the DIE children if any.
2286 if (!Children.empty()) {
2287 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2288 "Children flag not set");
2290 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2291 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2293 // End of children marker.
2294 Offset += sizeof(int8_t);
2297 Die->setSize(Offset - Die->getOffset());
2301 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2303 void DwarfDebug::computeSizeAndOffsets() {
2304 // Compute size of compile unit header.
2305 static unsigned Offset =
2306 sizeof(int32_t) + // Length of Compilation Unit Info
2307 sizeof(int16_t) + // DWARF version number
2308 sizeof(int32_t) + // Offset Into Abbrev. Section
2309 sizeof(int8_t); // Pointer Size (in bytes)
2311 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2312 CompileUnitOffsets[ModuleCU] = 0;
2315 /// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
2316 /// tools to recognize the object file contains Dwarf information.
2317 void DwarfDebug::emitInitial() {
2318 // Check to see if we already emitted intial headers.
2319 if (didInitial) return;
2322 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2324 // Dwarf sections base addresses.
2325 if (MAI->doesDwarfRequireFrameSection()) {
2326 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2327 EmitLabel("section_debug_frame", 0);
2330 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2331 EmitLabel("section_info", 0);
2332 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2333 EmitLabel("section_abbrev", 0);
2334 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2335 EmitLabel("section_aranges", 0);
2337 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2338 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2339 EmitLabel("section_macinfo", 0);
2342 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2343 EmitLabel("section_line", 0);
2344 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2345 EmitLabel("section_loc", 0);
2346 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2347 EmitLabel("section_pubnames", 0);
2348 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection());
2349 EmitLabel("section_pubtypes", 0);
2350 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2351 EmitLabel("section_str", 0);
2352 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2353 EmitLabel("section_ranges", 0);
2355 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2356 EmitLabel("text_begin", 0);
2357 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2358 EmitLabel("data_begin", 0);
2361 /// emitDIE - Recusively Emits a debug information entry.
2363 void DwarfDebug::emitDIE(DIE *Die) {
2364 // Get the abbreviation for this DIE.
2365 unsigned AbbrevNumber = Die->getAbbrevNumber();
2366 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2370 // Emit the code (index) for the abbreviation.
2371 Asm->EmitULEB128Bytes(AbbrevNumber);
2373 if (Asm->isVerbose())
2374 Asm->EOL(std::string("Abbrev [" +
2375 utostr(AbbrevNumber) +
2376 "] 0x" + utohexstr(Die->getOffset()) +
2377 ":0x" + utohexstr(Die->getSize()) + " " +
2378 dwarf::TagString(Abbrev->getTag())));
2382 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2383 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2385 // Emit the DIE attribute values.
2386 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2387 unsigned Attr = AbbrevData[i].getAttribute();
2388 unsigned Form = AbbrevData[i].getForm();
2389 assert(Form && "Too many attributes for DIE (check abbreviation)");
2392 case dwarf::DW_AT_sibling:
2393 Asm->EmitInt32(Die->getSiblingOffset());
2395 case dwarf::DW_AT_abstract_origin: {
2396 DIEEntry *E = cast<DIEEntry>(Values[i]);
2397 DIE *Origin = E->getEntry();
2398 unsigned Addr = Origin->getOffset();
2399 Asm->EmitInt32(Addr);
2403 // Emit an attribute using the defined form.
2404 Values[i]->EmitValue(this, Form);
2408 Asm->EOL(dwarf::AttributeString(Attr));
2411 // Emit the DIE children if any.
2412 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2413 const std::vector<DIE *> &Children = Die->getChildren();
2415 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2416 emitDIE(Children[j]);
2418 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2422 /// emitDebugInfo / emitDebugInfoPerCU - Emit the debug info section.
2424 void DwarfDebug::emitDebugInfoPerCU(CompileUnit *Unit) {
2425 DIE *Die = Unit->getCUDie();
2427 // Emit the compile units header.
2428 EmitLabel("info_begin", Unit->getID());
2430 // Emit size of content not including length itself
2431 unsigned ContentSize = Die->getSize() +
2432 sizeof(int16_t) + // DWARF version number
2433 sizeof(int32_t) + // Offset Into Abbrev. Section
2434 sizeof(int8_t) + // Pointer Size (in bytes)
2435 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2437 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2438 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2439 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2440 Asm->EOL("Offset Into Abbrev. Section");
2441 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2444 // FIXME - extra padding for gdb bug.
2445 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2446 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2447 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2448 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2449 EmitLabel("info_end", Unit->getID());
2454 void DwarfDebug::emitDebugInfo() {
2455 // Start debug info section.
2456 Asm->OutStreamer.SwitchSection(
2457 Asm->getObjFileLowering().getDwarfInfoSection());
2459 emitDebugInfoPerCU(ModuleCU);
2462 /// emitAbbreviations - Emit the abbreviation section.
2464 void DwarfDebug::emitAbbreviations() const {
2465 // Check to see if it is worth the effort.
2466 if (!Abbreviations.empty()) {
2467 // Start the debug abbrev section.
2468 Asm->OutStreamer.SwitchSection(
2469 Asm->getObjFileLowering().getDwarfAbbrevSection());
2471 EmitLabel("abbrev_begin", 0);
2473 // For each abbrevation.
2474 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2475 // Get abbreviation data
2476 const DIEAbbrev *Abbrev = Abbreviations[i];
2478 // Emit the abbrevations code (base 1 index.)
2479 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2480 Asm->EOL("Abbreviation Code");
2482 // Emit the abbreviations data.
2488 // Mark end of abbreviations.
2489 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2491 EmitLabel("abbrev_end", 0);
2496 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2497 /// the line matrix.
2499 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2500 // Define last address of section.
2501 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2502 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2503 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2504 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2506 // Mark end of matrix.
2507 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2508 Asm->EmitULEB128Bytes(1); Asm->EOL();
2509 Asm->EmitInt8(1); Asm->EOL();
2512 /// emitDebugLines - Emit source line information.
2514 void DwarfDebug::emitDebugLines() {
2515 // If the target is using .loc/.file, the assembler will be emitting the
2516 // .debug_line table automatically.
2517 if (MAI->hasDotLocAndDotFile())
2520 // Minimum line delta, thus ranging from -10..(255-10).
2521 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2522 // Maximum line delta, thus ranging from -10..(255-10).
2523 const int MaxLineDelta = 255 + MinLineDelta;
2525 // Start the dwarf line section.
2526 Asm->OutStreamer.SwitchSection(
2527 Asm->getObjFileLowering().getDwarfLineSection());
2529 // Construct the section header.
2530 EmitDifference("line_end", 0, "line_begin", 0, true);
2531 Asm->EOL("Length of Source Line Info");
2532 EmitLabel("line_begin", 0);
2534 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2536 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2537 Asm->EOL("Prolog Length");
2538 EmitLabel("line_prolog_begin", 0);
2540 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2542 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2544 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2546 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2548 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2550 // Line number standard opcode encodings argument count
2551 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2552 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2553 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2554 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2555 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2556 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2557 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2558 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2559 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2561 // Emit directories.
2562 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2563 Asm->EmitString(getSourceDirectoryName(DI));
2564 Asm->EOL("Directory");
2567 Asm->EmitInt8(0); Asm->EOL("End of directories");
2570 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2571 // Remember source id starts at 1.
2572 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2573 Asm->EmitString(getSourceFileName(Id.second));
2575 Asm->EmitULEB128Bytes(Id.first);
2576 Asm->EOL("Directory #");
2577 Asm->EmitULEB128Bytes(0);
2578 Asm->EOL("Mod date");
2579 Asm->EmitULEB128Bytes(0);
2580 Asm->EOL("File size");
2583 Asm->EmitInt8(0); Asm->EOL("End of files");
2585 EmitLabel("line_prolog_end", 0);
2587 // A sequence for each text section.
2588 unsigned SecSrcLinesSize = SectionSourceLines.size();
2590 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2591 // Isolate current sections line info.
2592 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2594 /*if (Asm->isVerbose()) {
2595 const MCSection *S = SectionMap[j + 1];
2596 O << '\t' << MAI->getCommentString() << " Section"
2597 << S->getName() << '\n';
2601 // Dwarf assumes we start with first line of first source file.
2602 unsigned Source = 1;
2605 // Construct rows of the address, source, line, column matrix.
2606 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2607 const SrcLineInfo &LineInfo = LineInfos[i];
2608 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2609 if (!LabelID) continue;
2611 if (LineInfo.getLine() == 0) continue;
2613 if (!Asm->isVerbose())
2616 std::pair<unsigned, unsigned> SourceID =
2617 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2618 O << '\t' << MAI->getCommentString() << ' '
2619 << getSourceDirectoryName(SourceID.first) << '/'
2620 << getSourceFileName(SourceID.second)
2621 << ':' << utostr_32(LineInfo.getLine()) << '\n';
2624 // Define the line address.
2625 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2626 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2627 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2628 EmitReference("label", LabelID); Asm->EOL("Location label");
2630 // If change of source, then switch to the new source.
2631 if (Source != LineInfo.getSourceID()) {
2632 Source = LineInfo.getSourceID();
2633 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2634 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2637 // If change of line.
2638 if (Line != LineInfo.getLine()) {
2639 // Determine offset.
2640 int Offset = LineInfo.getLine() - Line;
2641 int Delta = Offset - MinLineDelta;
2644 Line = LineInfo.getLine();
2646 // If delta is small enough and in range...
2647 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2648 // ... then use fast opcode.
2649 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2651 // ... otherwise use long hand.
2652 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2653 Asm->EOL("DW_LNS_advance_line");
2654 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2655 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2658 // Copy the previous row (different address or source)
2659 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2663 emitEndOfLineMatrix(j + 1);
2666 if (SecSrcLinesSize == 0)
2667 // Because we're emitting a debug_line section, we still need a line
2668 // table. The linker and friends expect it to exist. If there's nothing to
2669 // put into it, emit an empty table.
2670 emitEndOfLineMatrix(1);
2672 EmitLabel("line_end", 0);
2676 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2678 void DwarfDebug::emitCommonDebugFrame() {
2679 if (!MAI->doesDwarfRequireFrameSection())
2683 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2684 TargetFrameInfo::StackGrowsUp ?
2685 TD->getPointerSize() : -TD->getPointerSize();
2687 // Start the dwarf frame section.
2688 Asm->OutStreamer.SwitchSection(
2689 Asm->getObjFileLowering().getDwarfFrameSection());
2691 EmitLabel("debug_frame_common", 0);
2692 EmitDifference("debug_frame_common_end", 0,
2693 "debug_frame_common_begin", 0, true);
2694 Asm->EOL("Length of Common Information Entry");
2696 EmitLabel("debug_frame_common_begin", 0);
2697 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2698 Asm->EOL("CIE Identifier Tag");
2699 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2700 Asm->EOL("CIE Version");
2701 Asm->EmitString("");
2702 Asm->EOL("CIE Augmentation");
2703 Asm->EmitULEB128Bytes(1);
2704 Asm->EOL("CIE Code Alignment Factor");
2705 Asm->EmitSLEB128Bytes(stackGrowth);
2706 Asm->EOL("CIE Data Alignment Factor");
2707 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2708 Asm->EOL("CIE RA Column");
2710 std::vector<MachineMove> Moves;
2711 RI->getInitialFrameState(Moves);
2713 EmitFrameMoves(NULL, 0, Moves, false);
2715 Asm->EmitAlignment(2, 0, 0, false);
2716 EmitLabel("debug_frame_common_end", 0);
2721 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2724 DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2725 if (!MAI->doesDwarfRequireFrameSection())
2728 // Start the dwarf frame section.
2729 Asm->OutStreamer.SwitchSection(
2730 Asm->getObjFileLowering().getDwarfFrameSection());
2732 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2733 "debug_frame_begin", DebugFrameInfo.Number, true);
2734 Asm->EOL("Length of Frame Information Entry");
2736 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2738 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2740 Asm->EOL("FDE CIE offset");
2742 EmitReference("func_begin", DebugFrameInfo.Number);
2743 Asm->EOL("FDE initial location");
2744 EmitDifference("func_end", DebugFrameInfo.Number,
2745 "func_begin", DebugFrameInfo.Number);
2746 Asm->EOL("FDE address range");
2748 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2751 Asm->EmitAlignment(2, 0, 0, false);
2752 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2757 void DwarfDebug::emitDebugPubNamesPerCU(CompileUnit *Unit) {
2758 EmitDifference("pubnames_end", Unit->getID(),
2759 "pubnames_begin", Unit->getID(), true);
2760 Asm->EOL("Length of Public Names Info");
2762 EmitLabel("pubnames_begin", Unit->getID());
2764 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2766 EmitSectionOffset("info_begin", "section_info",
2767 Unit->getID(), 0, true, false);
2768 Asm->EOL("Offset of Compilation Unit Info");
2770 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2772 Asm->EOL("Compilation Unit Length");
2774 const StringMap<DIE*> &Globals = Unit->getGlobals();
2775 for (StringMap<DIE*>::const_iterator
2776 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2777 const char *Name = GI->getKeyData();
2778 DIE * Entity = GI->second;
2780 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2781 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2784 Asm->EmitInt32(0); Asm->EOL("End Mark");
2785 EmitLabel("pubnames_end", Unit->getID());
2790 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2792 void DwarfDebug::emitDebugPubNames() {
2793 // Start the dwarf pubnames section.
2794 Asm->OutStreamer.SwitchSection(
2795 Asm->getObjFileLowering().getDwarfPubNamesSection());
2797 emitDebugPubNamesPerCU(ModuleCU);
2800 void DwarfDebug::emitDebugPubTypes() {
2801 // Start the dwarf pubnames section.
2802 Asm->OutStreamer.SwitchSection(
2803 Asm->getObjFileLowering().getDwarfPubTypesSection());
2804 EmitDifference("pubtypes_end", ModuleCU->getID(),
2805 "pubtypes_begin", ModuleCU->getID(), true);
2806 Asm->EOL("Length of Public Types Info");
2808 EmitLabel("pubtypes_begin", ModuleCU->getID());
2810 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2812 EmitSectionOffset("info_begin", "section_info",
2813 ModuleCU->getID(), 0, true, false);
2814 Asm->EOL("Offset of Compilation ModuleCU Info");
2816 EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
2818 Asm->EOL("Compilation ModuleCU Length");
2820 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
2821 for (StringMap<DIE*>::const_iterator
2822 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2823 const char *Name = GI->getKeyData();
2824 DIE * Entity = GI->second;
2826 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2827 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2830 Asm->EmitInt32(0); Asm->EOL("End Mark");
2831 EmitLabel("pubtypes_end", ModuleCU->getID());
2836 /// emitDebugStr - Emit visible names into a debug str section.
2838 void DwarfDebug::emitDebugStr() {
2839 // Check to see if it is worth the effort.
2840 if (!StringPool.empty()) {
2841 // Start the dwarf str section.
2842 Asm->OutStreamer.SwitchSection(
2843 Asm->getObjFileLowering().getDwarfStrSection());
2845 // For each of strings in the string pool.
2846 for (unsigned StringID = 1, N = StringPool.size();
2847 StringID <= N; ++StringID) {
2848 // Emit a label for reference from debug information entries.
2849 EmitLabel("string", StringID);
2851 // Emit the string itself.
2852 const std::string &String = StringPool[StringID];
2853 Asm->EmitString(String); Asm->EOL();
2860 /// emitDebugLoc - Emit visible names into a debug loc section.
2862 void DwarfDebug::emitDebugLoc() {
2863 // Start the dwarf loc section.
2864 Asm->OutStreamer.SwitchSection(
2865 Asm->getObjFileLowering().getDwarfLocSection());
2869 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2871 void DwarfDebug::EmitDebugARanges() {
2872 // Start the dwarf aranges section.
2873 Asm->OutStreamer.SwitchSection(
2874 Asm->getObjFileLowering().getDwarfARangesSection());
2878 CompileUnit *Unit = GetBaseCompileUnit();
2880 // Don't include size of length
2881 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2883 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2885 EmitReference("info_begin", Unit->getID());
2886 Asm->EOL("Offset of Compilation Unit Info");
2888 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2890 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2892 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2893 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2896 EmitReference("text_begin", 0); Asm->EOL("Address");
2897 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2899 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2900 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2906 /// emitDebugRanges - Emit visible names into a debug ranges section.
2908 void DwarfDebug::emitDebugRanges() {
2909 // Start the dwarf ranges section.
2910 Asm->OutStreamer.SwitchSection(
2911 Asm->getObjFileLowering().getDwarfRangesSection());
2915 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2917 void DwarfDebug::emitDebugMacInfo() {
2918 if (const MCSection *LineInfo =
2919 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2920 // Start the dwarf macinfo section.
2921 Asm->OutStreamer.SwitchSection(LineInfo);
2926 /// emitDebugInlineInfo - Emit inline info using following format.
2928 /// 1. length of section
2929 /// 2. Dwarf version number
2930 /// 3. address size.
2932 /// Entries (one "entry" for each function that was inlined):
2934 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2935 /// otherwise offset into __debug_str for regular function name.
2936 /// 2. offset into __debug_str section for regular function name.
2937 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2938 /// instances for the function.
2940 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2941 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2942 /// __debug_info section, and the low_pc is the starting address for the
2943 /// inlining instance.
2944 void DwarfDebug::emitDebugInlineInfo() {
2945 if (!MAI->doesDwarfUsesInlineInfoSection())
2951 Asm->OutStreamer.SwitchSection(
2952 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2954 EmitDifference("debug_inlined_end", 1,
2955 "debug_inlined_begin", 1, true);
2956 Asm->EOL("Length of Debug Inlined Information Entry");
2958 EmitLabel("debug_inlined_begin", 1);
2960 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2961 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2963 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2964 E = InlinedSPNodes.end(); I != E; ++I) {
2966 // for (ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
2967 // I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2969 ValueMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2970 = InlineInfo.find(Node);
2971 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2972 DISubprogram SP(Node);
2973 StringRef LName = SP.getLinkageName();
2974 StringRef Name = SP.getName();
2977 Asm->EmitString(Name);
2979 // Skip special LLVM prefix that is used to inform the asm printer to not
2980 // emit usual symbol prefix before the symbol name. This happens for
2981 // Objective-C symbol names and symbol whose name is replaced using GCC's
2982 // __asm__ attribute.
2984 LName = LName.substr(1);
2985 // Asm->EmitString(LName);
2986 EmitSectionOffset("string", "section_str",
2987 StringPool.idFor(LName), false, true);
2990 Asm->EOL("MIPS linkage name");
2991 // Asm->EmitString(Name);
2992 EmitSectionOffset("string", "section_str",
2993 StringPool.idFor(Name), false, true);
2994 Asm->EOL("Function name");
2995 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2997 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2998 LE = Labels.end(); LI != LE; ++LI) {
2999 DIE *SP = LI->second;
3000 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
3002 if (TD->getPointerSize() == sizeof(int32_t))
3003 O << MAI->getData32bitsDirective();
3005 O << MAI->getData64bitsDirective();
3007 PrintLabelName("label", LI->first); Asm->EOL("low_pc");
3011 EmitLabel("debug_inlined_end", 1);