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 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
16 #include "llvm/Module.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCSection.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/Target/Mangler.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Target/TargetLoweringObjectFile.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ValueHandle.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Timer.h"
35 #include "llvm/System/Path.h"
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.
56 const OwningPtr<DIE> CUDie;
58 /// IndexTyDie - An anonymous type for index type. Owned by CUDie.
61 /// GVToDieMap - Tracks the mapping of unit level debug informaton
62 /// variables to debug information entries.
63 /// FIXME : Rename GVToDieMap -> NodeToDieMap
64 DenseMap<MDNode *, DIE *> GVToDieMap;
66 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
67 /// descriptors to debug information entries using a DIEEntry proxy.
69 DenseMap<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) {}
84 unsigned getID() const { return ID; }
85 DIE* getCUDie() const { return CUDie.get(); }
86 const StringMap<DIE*> &getGlobals() const { return Globals; }
87 const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
89 /// hasContent - Return true if this compile unit has something to write out.
91 bool hasContent() const { return !CUDie->getChildren().empty(); }
93 /// addGlobal - Add a new global entity to the compile unit.
95 void addGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
97 /// addGlobalType - Add a new global type to the compile unit.
99 void addGlobalType(const std::string &Name, DIE *Die) {
100 GlobalTypes[Name] = Die;
103 /// getDIE - Returns the debug information entry map slot for the
104 /// specified debug variable.
105 DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
107 /// insertDIE - Insert DIE into the map.
108 void insertDIE(MDNode *N, DIE *D) {
109 GVToDieMap.insert(std::make_pair(N, D));
112 /// getDIEEntry - Returns the debug information entry for the speciefied
114 DIEEntry *getDIEEntry(MDNode *N) {
115 DenseMap<MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
116 if (I == GVToDIEEntryMap.end())
121 /// insertDIEEntry - Insert debug information entry into the map.
122 void insertDIEEntry(MDNode *N, DIEEntry *E) {
123 GVToDIEEntryMap.insert(std::make_pair(N, E));
126 /// addDie - Adds or interns the DIE to the compile unit.
128 void addDie(DIE *Buffer) {
129 this->CUDie->addChild(Buffer);
132 // getIndexTyDie - Get an anonymous type for index type.
133 DIE *getIndexTyDie() {
137 // setIndexTyDie - Set D as anonymous type for index which can be reused
139 void setIndexTyDie(DIE *D) {
145 //===----------------------------------------------------------------------===//
146 /// DbgVariable - This class is used to track local variable information.
149 DIVariable Var; // Variable Descriptor.
150 unsigned FrameIndex; // Variable frame index.
151 DbgVariable *const AbstractVar; // Abstract variable for this variable.
154 // AbsVar may be NULL.
155 DbgVariable(DIVariable V, unsigned I, DbgVariable *AbsVar)
156 : Var(V), FrameIndex(I), AbstractVar(AbsVar), TheDIE(0) {}
159 DIVariable getVariable() const { return Var; }
160 unsigned getFrameIndex() const { return FrameIndex; }
161 DbgVariable *getAbstractVariable() const { return AbstractVar; }
162 void setDIE(DIE *D) { TheDIE = D; }
163 DIE *getDIE() const { return TheDIE; }
166 //===----------------------------------------------------------------------===//
167 /// DbgScope - This class is used to track scope information.
170 DbgScope *Parent; // Parent to this scope.
171 DIDescriptor Desc; // Debug info descriptor for scope.
172 // Location at which this scope is inlined.
173 AssertingVH<MDNode> InlinedAtLocation;
174 bool AbstractScope; // Abstract Scope
175 MCSymbol *StartLabel; // Label ID of the beginning of scope.
176 MCSymbol *EndLabel; // Label ID of the end of scope.
177 const MachineInstr *LastInsn; // Last instruction of this scope.
178 const MachineInstr *FirstInsn; // First instruction of this scope.
179 // Scopes defined in scope. Contents not owned.
180 SmallVector<DbgScope *, 4> Scopes;
181 // Variables declared in scope. Contents owned.
182 SmallVector<DbgVariable *, 8> Variables;
184 // Private state for dump()
185 mutable unsigned IndentLevel;
187 DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
188 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
189 StartLabel(0), EndLabel(0),
190 LastInsn(0), FirstInsn(0), IndentLevel(0) {}
194 DbgScope *getParent() const { return Parent; }
195 void setParent(DbgScope *P) { Parent = P; }
196 DIDescriptor getDesc() const { return Desc; }
197 MDNode *getInlinedAt() const { return InlinedAtLocation; }
198 MDNode *getScopeNode() const { return Desc.getNode(); }
199 MCSymbol *getStartLabel() const { return StartLabel; }
200 MCSymbol *getEndLabel() const { return EndLabel; }
201 const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
202 const SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
203 void setStartLabel(MCSymbol *S) { StartLabel = S; }
204 void setEndLabel(MCSymbol *E) { EndLabel = E; }
205 void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
206 const MachineInstr *getLastInsn() { return LastInsn; }
207 void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
208 void setAbstractScope() { AbstractScope = true; }
209 bool isAbstractScope() const { return AbstractScope; }
210 const MachineInstr *getFirstInsn() { return FirstInsn; }
212 /// addScope - Add a scope to the scope.
214 void addScope(DbgScope *S) { Scopes.push_back(S); }
216 /// addVariable - Add a variable to the scope.
218 void addVariable(DbgVariable *V) { Variables.push_back(V); }
220 void fixInstructionMarkers(DenseMap<const MachineInstr *,
221 unsigned> &MIIndexMap) {
222 assert (getFirstInsn() && "First instruction is missing!");
224 // Use the end of last child scope as end of this scope.
225 const SmallVector<DbgScope *, 4> &Scopes = getScopes();
226 const MachineInstr *LastInsn = getFirstInsn();
228 if (Scopes.empty()) {
229 assert (getLastInsn() && "Inner most scope does not have last insn!");
232 for (SmallVector<DbgScope *, 4>::const_iterator SI = Scopes.begin(),
233 SE = Scopes.end(); SI != SE; ++SI) {
235 DS->fixInstructionMarkers(MIIndexMap);
236 const MachineInstr *DSLastInsn = DS->getLastInsn();
237 unsigned DSI = MIIndexMap[DSLastInsn];
239 LastInsn = DSLastInsn;
244 unsigned CurrentLastInsnIndex = 0;
245 if (const MachineInstr *CL = getLastInsn())
246 CurrentLastInsnIndex = MIIndexMap[CL];
247 unsigned FIndex = MIIndexMap[getFirstInsn()];
249 // Set LastInsn as the last instruction for this scope only if
251 // 1) this scope's first instruction and
252 // 2) current last instruction for this scope, if any.
253 if (LIndex >= CurrentLastInsnIndex && LIndex >= FIndex)
254 setLastInsn(LastInsn);
263 void DbgScope::dump() const {
264 raw_ostream &err = dbgs();
265 err.indent(IndentLevel);
266 MDNode *N = Desc.getNode();
268 err << " [" << StartLabel << ", " << EndLabel << "]\n";
270 err << "Abstract Scope\n";
274 err << "Children ...\n";
275 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
276 if (Scopes[i] != this)
283 DbgScope::~DbgScope() {
284 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
288 } // end llvm namespace
290 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
291 : DwarfPrinter(OS, A, T), ModuleCU(0),
292 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
293 DIEValues(), SectionSourceLines(), didInitial(false), shouldEmit(false),
294 CurrentFnDbgScope(0), DebugTimer(0) {
295 NextStringPoolNumber = 0;
296 if (TimePassesIsEnabled)
297 DebugTimer = new Timer("Dwarf Debug Writer");
299 DwarfDebug::~DwarfDebug() {
300 for (unsigned j = 0, M = DIEValues.size(); j < M; ++j)
306 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
307 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
308 if (Entry.first) return Entry.first;
310 Entry.second = NextStringPoolNumber++;
311 return Entry.first = getDWLabel("string", Entry.second);
315 /// assignAbbrevNumber - Define a unique number for the abbreviation.
317 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
318 // Profile the node so that we can make it unique.
322 // Check the set for priors.
323 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
325 // If it's newly added.
326 if (InSet == &Abbrev) {
327 // Add to abbreviation list.
328 Abbreviations.push_back(&Abbrev);
330 // Assign the vector position + 1 as its number.
331 Abbrev.setNumber(Abbreviations.size());
333 // Assign existing abbreviation number.
334 Abbrev.setNumber(InSet->getNumber());
338 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
339 /// information entry.
340 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
341 DIEEntry *Value = new DIEEntry(Entry);
342 DIEValues.push_back(Value);
346 /// addUInt - Add an unsigned integer attribute data and value.
348 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
349 unsigned Form, uint64_t Integer) {
350 if (!Form) Form = DIEInteger::BestForm(false, Integer);
351 DIEValue *Value = new DIEInteger(Integer);
352 DIEValues.push_back(Value);
353 Die->addValue(Attribute, Form, Value);
356 /// addSInt - Add an signed integer attribute data and value.
358 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
359 unsigned Form, int64_t Integer) {
360 if (!Form) Form = DIEInteger::BestForm(true, Integer);
361 DIEValue *Value = new DIEInteger(Integer);
362 DIEValues.push_back(Value);
363 Die->addValue(Attribute, Form, Value);
366 /// addString - Add a string attribute data and value. DIEString only
367 /// keeps string reference.
368 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
370 DIEValue *Value = new DIEString(String);
371 DIEValues.push_back(Value);
372 Die->addValue(Attribute, Form, Value);
375 /// addLabel - Add a Dwarf label attribute data and value.
377 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
378 const MCSymbol *Label) {
379 DIEValue *Value = new DIELabel(Label);
380 DIEValues.push_back(Value);
381 Die->addValue(Attribute, Form, Value);
384 /// addSectionOffset - Add a section offset label attribute data and value.
386 void DwarfDebug::addSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
387 const MCSymbol *Label,const MCSymbol *Section,
389 DIEValue *Value = new DIESectionOffset(Label, Section, isEH);
390 DIEValues.push_back(Value);
391 Die->addValue(Attribute, Form, Value);
394 /// addDelta - Add a label delta attribute data and value.
396 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
397 const MCSymbol *Hi, const MCSymbol *Lo) {
398 DIEValue *Value = new DIEDelta(Hi, Lo);
399 DIEValues.push_back(Value);
400 Die->addValue(Attribute, Form, Value);
403 /// addBlock - Add block data.
405 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
407 Block->ComputeSize(TD);
408 DIEValues.push_back(Block);
409 Die->addValue(Attribute, Block->BestForm(), Block);
412 /// addSourceLine - Add location information to specified debug information
414 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
415 // If there is no compile unit specified, don't add a line #.
416 if (!V->getCompileUnit().Verify())
419 unsigned Line = V->getLineNumber();
420 unsigned FileID = GetOrCreateSourceID(V->getContext().getDirectory(),
421 V->getContext().getFilename());
422 assert(FileID && "Invalid file id");
423 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
424 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
427 /// addSourceLine - Add location information to specified debug information
429 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
430 // If there is no compile unit specified, don't add a line #.
431 if (!G->getCompileUnit().Verify())
434 unsigned Line = G->getLineNumber();
435 unsigned FileID = GetOrCreateSourceID(G->getContext().getDirectory(),
436 G->getContext().getFilename());
437 assert(FileID && "Invalid file id");
438 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
439 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
442 /// addSourceLine - Add location information to specified debug information
444 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
445 // If there is no compile unit specified, don't add a line #.
446 if (!SP->getCompileUnit().Verify())
448 // If the line number is 0, don't add it.
449 if (SP->getLineNumber() == 0)
452 unsigned Line = SP->getLineNumber();
453 if (!SP->getContext().Verify())
455 unsigned FileID = GetOrCreateSourceID(SP->getContext().getDirectory(),
456 SP->getContext().getFilename());
457 assert(FileID && "Invalid file id");
458 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
459 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
462 /// addSourceLine - Add location information to specified debug information
464 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
465 // If there is no compile unit specified, don't add a line #.
466 DICompileUnit CU = Ty->getCompileUnit();
470 unsigned Line = Ty->getLineNumber();
471 if (!Ty->getContext().Verify())
473 unsigned FileID = GetOrCreateSourceID(Ty->getContext().getDirectory(),
474 Ty->getContext().getFilename());
475 assert(FileID && "Invalid file id");
476 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
477 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
480 /// addSourceLine - Add location information to specified debug information
482 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
483 // If there is no compile unit specified, don't add a line #.
484 if (!NS->getCompileUnit().Verify())
487 unsigned Line = NS->getLineNumber();
488 StringRef FN = NS->getFilename();
489 StringRef Dir = NS->getDirectory();
491 unsigned FileID = GetOrCreateSourceID(Dir, FN);
492 assert(FileID && "Invalid file id");
493 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
494 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
497 /* Byref variables, in Blocks, are declared by the programmer as
498 "SomeType VarName;", but the compiler creates a
499 __Block_byref_x_VarName struct, and gives the variable VarName
500 either the struct, or a pointer to the struct, as its type. This
501 is necessary for various behind-the-scenes things the compiler
502 needs to do with by-reference variables in blocks.
504 However, as far as the original *programmer* is concerned, the
505 variable should still have type 'SomeType', as originally declared.
507 The following function dives into the __Block_byref_x_VarName
508 struct to find the original type of the variable. This will be
509 passed back to the code generating the type for the Debug
510 Information Entry for the variable 'VarName'. 'VarName' will then
511 have the original type 'SomeType' in its debug information.
513 The original type 'SomeType' will be the type of the field named
514 'VarName' inside the __Block_byref_x_VarName struct.
516 NOTE: In order for this to not completely fail on the debugger
517 side, the Debug Information Entry for the variable VarName needs to
518 have a DW_AT_location that tells the debugger how to unwind through
519 the pointers and __Block_byref_x_VarName struct to find the actual
520 value of the variable. The function addBlockByrefType does this. */
522 /// Find the type the programmer originally declared the variable to be
523 /// and return that type.
525 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
528 unsigned tag = Ty.getTag();
530 if (tag == dwarf::DW_TAG_pointer_type) {
531 DIDerivedType DTy = DIDerivedType(Ty.getNode());
532 subType = DTy.getTypeDerivedFrom();
535 DICompositeType blockStruct = DICompositeType(subType.getNode());
536 DIArray Elements = blockStruct.getTypeArray();
538 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
539 DIDescriptor Element = Elements.getElement(i);
540 DIDerivedType DT = DIDerivedType(Element.getNode());
541 if (Name == DT.getName())
542 return (DT.getTypeDerivedFrom());
548 /// addComplexAddress - Start with the address based on the location provided,
549 /// and generate the DWARF information necessary to find the actual variable
550 /// given the extra address information encoded in the DIVariable, starting from
551 /// the starting location. Add the DWARF information to the die.
553 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
555 const MachineLocation &Location) {
556 const DIVariable &VD = DV->getVariable();
557 DIType Ty = VD.getType();
559 // Decode the original location, and use that as the start of the byref
560 // variable's location.
561 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
562 DIEBlock *Block = new DIEBlock();
564 if (Location.isReg()) {
566 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
568 Reg = Reg - dwarf::DW_OP_reg0;
569 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
570 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
574 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
576 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
577 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
580 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
583 for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
584 uint64_t Element = VD.getAddrElement(i);
586 if (Element == DIFactory::OpPlus) {
587 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
588 addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
589 } else if (Element == DIFactory::OpDeref) {
590 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
591 } else llvm_unreachable("unknown DIFactory Opcode");
594 // Now attach the location information to the DIE.
595 addBlock(Die, Attribute, 0, Block);
598 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
599 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
600 gives the variable VarName either the struct, or a pointer to the struct, as
601 its type. This is necessary for various behind-the-scenes things the
602 compiler needs to do with by-reference variables in Blocks.
604 However, as far as the original *programmer* is concerned, the variable
605 should still have type 'SomeType', as originally declared.
607 The function getBlockByrefType dives into the __Block_byref_x_VarName
608 struct to find the original type of the variable, which is then assigned to
609 the variable's Debug Information Entry as its real type. So far, so good.
610 However now the debugger will expect the variable VarName to have the type
611 SomeType. So we need the location attribute for the variable to be an
612 expression that explains to the debugger how to navigate through the
613 pointers and struct to find the actual variable of type SomeType.
615 The following function does just that. We start by getting
616 the "normal" location for the variable. This will be the location
617 of either the struct __Block_byref_x_VarName or the pointer to the
618 struct __Block_byref_x_VarName.
620 The struct will look something like:
622 struct __Block_byref_x_VarName {
624 struct __Block_byref_x_VarName *forwarding;
625 ... <various other fields>
627 ... <maybe more fields>
630 If we are given the struct directly (as our starting point) we
631 need to tell the debugger to:
633 1). Add the offset of the forwarding field.
635 2). Follow that pointer to get the real __Block_byref_x_VarName
636 struct to use (the real one may have been copied onto the heap).
638 3). Add the offset for the field VarName, to find the actual variable.
640 If we started with a pointer to the struct, then we need to
641 dereference that pointer first, before the other steps.
642 Translating this into DWARF ops, we will need to append the following
643 to the current location description for the variable:
645 DW_OP_deref -- optional, if we start with a pointer
646 DW_OP_plus_uconst <forward_fld_offset>
648 DW_OP_plus_uconst <varName_fld_offset>
650 That is what this function does. */
652 /// addBlockByrefAddress - Start with the address based on the location
653 /// provided, and generate the DWARF information necessary to find the
654 /// actual Block variable (navigating the Block struct) based on the
655 /// starting location. Add the DWARF information to the die. For
656 /// more information, read large comment just above here.
658 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
660 const MachineLocation &Location) {
661 const DIVariable &VD = DV->getVariable();
662 DIType Ty = VD.getType();
664 unsigned Tag = Ty.getTag();
665 bool isPointer = false;
667 StringRef varName = VD.getName();
669 if (Tag == dwarf::DW_TAG_pointer_type) {
670 DIDerivedType DTy = DIDerivedType(Ty.getNode());
671 TmpTy = DTy.getTypeDerivedFrom();
675 DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
677 // Find the __forwarding field and the variable field in the __Block_byref
679 DIArray Fields = blockStruct.getTypeArray();
680 DIDescriptor varField = DIDescriptor();
681 DIDescriptor forwardingField = DIDescriptor();
683 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
684 DIDescriptor Element = Fields.getElement(i);
685 DIDerivedType DT = DIDerivedType(Element.getNode());
686 StringRef fieldName = DT.getName();
687 if (fieldName == "__forwarding")
688 forwardingField = Element;
689 else if (fieldName == varName)
693 // Get the offsets for the forwarding field and the variable field.
694 unsigned int forwardingFieldOffset =
695 DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
696 unsigned int varFieldOffset =
697 DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
699 // Decode the original location, and use that as the start of the byref
700 // variable's location.
701 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
702 DIEBlock *Block = new DIEBlock();
704 if (Location.isReg()) {
706 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
708 Reg = Reg - dwarf::DW_OP_reg0;
709 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
710 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
714 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
716 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
717 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
720 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
723 // If we started with a pointer to the __Block_byref... struct, then
724 // the first thing we need to do is dereference the pointer (DW_OP_deref).
726 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
728 // Next add the offset for the '__forwarding' field:
729 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
730 // adding the offset if it's 0.
731 if (forwardingFieldOffset > 0) {
732 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
733 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
736 // Now dereference the __forwarding field to get to the real __Block_byref
737 // struct: DW_OP_deref.
738 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
740 // Now that we've got the real __Block_byref... struct, add the offset
741 // for the variable's field to get to the location of the actual variable:
742 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
743 if (varFieldOffset > 0) {
744 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
745 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
748 // Now attach the location information to the DIE.
749 addBlock(Die, Attribute, 0, Block);
752 /// addAddress - Add an address attribute to a die based on the location
754 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
755 const MachineLocation &Location) {
756 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
757 DIEBlock *Block = new DIEBlock();
759 if (Location.isReg()) {
761 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
763 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
764 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
768 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
770 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
771 addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
774 addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
777 addBlock(Die, Attribute, 0, Block);
780 /// addToContextOwner - Add Die into the list of its context owner's children.
781 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
782 if (Context.isType()) {
783 DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
784 ContextDIE->addChild(Die);
785 } else if (Context.isNameSpace()) {
786 DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
787 ContextDIE->addChild(Die);
788 } else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
789 ContextDIE->addChild(Die);
791 ModuleCU->addDie(Die);
794 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
796 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
797 DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
802 TyDIE = new DIE(dwarf::DW_TAG_base_type);
803 ModuleCU->insertDIE(Ty.getNode(), TyDIE);
804 if (Ty.isBasicType())
805 constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
806 else if (Ty.isCompositeType())
807 constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
809 assert(Ty.isDerivedType() && "Unknown kind of DIType");
810 constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
813 addToContextOwner(TyDIE, Ty.getContext());
817 /// addType - Add a new type attribute to the specified entity.
818 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
822 // Check for pre-existence.
823 DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
824 // If it exists then use the existing value.
826 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
831 DIE *Buffer = getOrCreateTypeDIE(Ty);
834 Entry = createDIEEntry(Buffer);
835 ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
837 Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
840 /// constructTypeDIE - Construct basic type die from DIBasicType.
841 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
842 // Get core information.
843 StringRef Name = BTy.getName();
844 Buffer.setTag(dwarf::DW_TAG_base_type);
845 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
848 // Add name if not anonymous or intermediate type.
850 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
851 uint64_t Size = BTy.getSizeInBits() >> 3;
852 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
855 /// constructTypeDIE - Construct derived type die from DIDerivedType.
856 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
857 // Get core information.
858 StringRef Name = DTy.getName();
859 uint64_t Size = DTy.getSizeInBits() >> 3;
860 unsigned Tag = DTy.getTag();
862 // FIXME - Workaround for templates.
863 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
867 // Map to main type, void will not have a type.
868 DIType FromTy = DTy.getTypeDerivedFrom();
869 addType(&Buffer, FromTy);
871 // Add name if not anonymous or intermediate type.
873 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
875 // Add size if non-zero (derived types might be zero-sized.)
877 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
879 // Add source line info if available and TyDesc is not a forward declaration.
880 if (!DTy.isForwardDecl())
881 addSourceLine(&Buffer, &DTy);
884 /// constructTypeDIE - Construct type DIE from DICompositeType.
885 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
886 // Get core information.
887 StringRef Name = CTy.getName();
889 uint64_t Size = CTy.getSizeInBits() >> 3;
890 unsigned Tag = CTy.getTag();
894 case dwarf::DW_TAG_vector_type:
895 case dwarf::DW_TAG_array_type:
896 constructArrayTypeDIE(Buffer, &CTy);
898 case dwarf::DW_TAG_enumeration_type: {
899 DIArray Elements = CTy.getTypeArray();
901 // Add enumerators to enumeration type.
902 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
904 DIDescriptor Enum(Elements.getElement(i).getNode());
905 if (Enum.isEnumerator()) {
906 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum.getNode()));
907 Buffer.addChild(ElemDie);
912 case dwarf::DW_TAG_subroutine_type: {
914 DIArray Elements = CTy.getTypeArray();
915 DIDescriptor RTy = Elements.getElement(0);
916 addType(&Buffer, DIType(RTy.getNode()));
918 // Add prototype flag.
919 addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
922 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
923 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
924 DIDescriptor Ty = Elements.getElement(i);
925 addType(Arg, DIType(Ty.getNode()));
926 Buffer.addChild(Arg);
930 case dwarf::DW_TAG_structure_type:
931 case dwarf::DW_TAG_union_type:
932 case dwarf::DW_TAG_class_type: {
933 // Add elements to structure type.
934 DIArray Elements = CTy.getTypeArray();
936 // A forward struct declared type may not have elements available.
937 unsigned N = Elements.getNumElements();
941 // Add elements to structure type.
942 for (unsigned i = 0; i < N; ++i) {
943 DIDescriptor Element = Elements.getElement(i);
945 if (Element.isSubprogram())
946 ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
947 else if (Element.isVariable()) {
948 DIVariable DV(Element.getNode());
949 ElemDie = new DIE(dwarf::DW_TAG_variable);
950 addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
952 addType(ElemDie, DV.getType());
953 addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
954 addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
955 addSourceLine(ElemDie, &DV);
956 } else if (Element.isDerivedType())
957 ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
960 Buffer.addChild(ElemDie);
963 if (CTy.isAppleBlockExtension())
964 addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
966 unsigned RLang = CTy.getRunTimeLang();
968 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
969 dwarf::DW_FORM_data1, RLang);
971 DICompositeType ContainingType = CTy.getContainingType();
972 if (DIDescriptor(ContainingType.getNode()).isCompositeType())
973 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
974 getOrCreateTypeDIE(DIType(ContainingType.getNode())));
981 // Add name if not anonymous or intermediate type.
983 addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
985 if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
986 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
987 // Add size if non-zero (derived types might be zero-sized.)
989 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
991 // Add zero size if it is not a forward declaration.
992 if (CTy.isForwardDecl())
993 addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
995 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
998 // Add source line info if available.
999 if (!CTy.isForwardDecl())
1000 addSourceLine(&Buffer, &CTy);
1004 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1005 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1006 int64_t L = SR.getLo();
1007 int64_t H = SR.getHi();
1008 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1010 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1012 addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1013 addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1015 Buffer.addChild(DW_Subrange);
1018 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1019 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1020 DICompositeType *CTy) {
1021 Buffer.setTag(dwarf::DW_TAG_array_type);
1022 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1023 addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1025 // Emit derived type.
1026 addType(&Buffer, CTy->getTypeDerivedFrom());
1027 DIArray Elements = CTy->getTypeArray();
1029 // Get an anonymous type for index type.
1030 DIE *IdxTy = ModuleCU->getIndexTyDie();
1032 // Construct an anonymous type for index type.
1033 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1034 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1035 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1036 dwarf::DW_ATE_signed);
1037 ModuleCU->addDie(IdxTy);
1038 ModuleCU->setIndexTyDie(IdxTy);
1041 // Add subranges to array type.
1042 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1043 DIDescriptor Element = Elements.getElement(i);
1044 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1045 constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
1049 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1050 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1051 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1052 StringRef Name = ETy.getName();
1053 addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1054 int64_t Value = ETy.getEnumValue();
1055 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1059 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1060 /// printer to not emit usual symbol prefix before the symbol name is used then
1061 /// return linkage name after skipping this special LLVM prefix.
1062 static StringRef getRealLinkageName(StringRef LinkageName) {
1064 if (LinkageName.startswith(StringRef(&One, 1)))
1065 return LinkageName.substr(1);
1069 /// createGlobalVariableDIE - Create new DIE using GV.
1070 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1071 // If the global variable was optmized out then no need to create debug info
1073 if (!GV.getGlobal()) return NULL;
1074 if (GV.getDisplayName().empty()) return NULL;
1076 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1077 addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1078 GV.getDisplayName());
1080 StringRef LinkageName = GV.getLinkageName();
1081 if (!LinkageName.empty())
1082 addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1083 getRealLinkageName(LinkageName));
1085 addType(GVDie, GV.getType());
1086 if (!GV.isLocalToUnit())
1087 addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1088 addSourceLine(GVDie, &GV);
1093 /// createMemberDIE - Create new member DIE.
1094 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1095 DIE *MemberDie = new DIE(DT.getTag());
1096 StringRef Name = DT.getName();
1098 addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1100 addType(MemberDie, DT.getTypeDerivedFrom());
1102 addSourceLine(MemberDie, &DT);
1104 DIEBlock *MemLocationDie = new DIEBlock();
1105 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1107 uint64_t Size = DT.getSizeInBits();
1108 uint64_t FieldSize = DT.getOriginalTypeSize();
1110 if (Size != FieldSize) {
1112 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1113 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1115 uint64_t Offset = DT.getOffsetInBits();
1116 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1117 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1118 uint64_t FieldOffset = (HiMark - FieldSize);
1119 Offset -= FieldOffset;
1121 // Maybe we need to work from the other end.
1122 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1123 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1125 // Here WD_AT_data_member_location points to the anonymous
1126 // field that includes this bit field.
1127 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1130 // This is not a bitfield.
1131 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1133 if (DT.getTag() == dwarf::DW_TAG_inheritance
1134 && DT.isVirtual()) {
1136 // For C++, virtual base classes are not at fixed offset. Use following
1137 // expression to extract appropriate offset from vtable.
1138 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1140 DIEBlock *VBaseLocationDie = new DIEBlock();
1141 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1142 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1143 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1144 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1145 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1146 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1147 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1149 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1152 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1154 if (DT.isProtected())
1155 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1156 dwarf::DW_ACCESS_protected);
1157 else if (DT.isPrivate())
1158 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1159 dwarf::DW_ACCESS_private);
1160 else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1161 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1162 dwarf::DW_ACCESS_public);
1164 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1165 dwarf::DW_VIRTUALITY_virtual);
1169 /// createSubprogramDIE - Create new DIE using SP.
1170 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1171 DIE *SPDie = ModuleCU->getDIE(SP.getNode());
1175 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1176 // Constructors and operators for anonymous aggregates do not have names.
1177 if (!SP.getName().empty())
1178 addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1180 StringRef LinkageName = SP.getLinkageName();
1181 if (!LinkageName.empty())
1182 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1183 getRealLinkageName(LinkageName));
1185 addSourceLine(SPDie, &SP);
1187 // Add prototyped tag, if C or ObjC.
1188 unsigned Lang = SP.getCompileUnit().getLanguage();
1189 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1190 Lang == dwarf::DW_LANG_ObjC)
1191 addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1194 DICompositeType SPTy = SP.getType();
1195 DIArray Args = SPTy.getTypeArray();
1196 unsigned SPTag = SPTy.getTag();
1198 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1199 addType(SPDie, SPTy);
1201 addType(SPDie, DIType(Args.getElement(0).getNode()));
1203 unsigned VK = SP.getVirtuality();
1205 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1206 DIEBlock *Block = new DIEBlock();
1207 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1208 addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1209 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1210 ContainingTypeMap.insert(std::make_pair(SPDie,
1211 SP.getContainingType().getNode()));
1214 if (MakeDecl || !SP.isDefinition()) {
1215 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1217 // Add arguments. Do not add arguments for subprogram definition. They will
1218 // be handled while processing variables.
1219 DICompositeType SPTy = SP.getType();
1220 DIArray Args = SPTy.getTypeArray();
1221 unsigned SPTag = SPTy.getTag();
1223 if (SPTag == dwarf::DW_TAG_subroutine_type)
1224 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1225 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1226 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1228 if (ATy.isArtificial())
1229 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1230 SPDie->addChild(Arg);
1234 if (SP.isArtificial())
1235 addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1237 // DW_TAG_inlined_subroutine may refer to this DIE.
1238 ModuleCU->insertDIE(SP.getNode(), SPDie);
1242 /// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
1243 /// Initialize scope and update scope hierarchy.
1244 DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
1245 MDNode *InlinedAt) {
1246 assert (N && "Invalid Scope encoding!");
1247 assert (MI && "Missing machine instruction!");
1248 bool GetConcreteScope = (MI && InlinedAt);
1250 DbgScope *NScope = NULL;
1253 NScope = DbgScopeMap.lookup(InlinedAt);
1255 NScope = DbgScopeMap.lookup(N);
1256 assert (NScope && "Unable to find working scope!");
1258 if (NScope->getFirstInsn())
1261 DbgScope *Parent = NULL;
1262 if (GetConcreteScope) {
1263 DILocation IL(InlinedAt);
1264 Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
1265 IL.getOrigLocation().getNode());
1266 assert (Parent && "Unable to find Parent scope!");
1267 NScope->setParent(Parent);
1268 Parent->addScope(NScope);
1269 } else if (DIDescriptor(N).isLexicalBlock()) {
1270 DILexicalBlock DB(N);
1271 Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
1272 NScope->setParent(Parent);
1273 Parent->addScope(NScope);
1276 NScope->setFirstInsn(MI);
1278 if (!Parent && !InlinedAt) {
1279 StringRef SPName = DISubprogram(N).getLinkageName();
1280 if (SPName == MF->getFunction()->getName())
1281 CurrentFnDbgScope = NScope;
1284 if (GetConcreteScope) {
1285 ConcreteScopes[InlinedAt] = NScope;
1286 getOrCreateAbstractScope(N);
1292 DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
1293 assert (N && "Invalid Scope encoding!");
1295 DbgScope *AScope = AbstractScopes.lookup(N);
1299 DbgScope *Parent = NULL;
1301 DIDescriptor Scope(N);
1302 if (Scope.isLexicalBlock()) {
1303 DILexicalBlock DB(N);
1304 DIDescriptor ParentDesc = DB.getContext();
1305 Parent = getOrCreateAbstractScope(ParentDesc.getNode());
1308 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1311 Parent->addScope(AScope);
1312 AScope->setAbstractScope();
1313 AbstractScopes[N] = AScope;
1314 if (DIDescriptor(N).isSubprogram())
1315 AbstractScopesList.push_back(AScope);
1319 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1320 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1321 /// If there are global variables in this scope then create and insert
1322 /// DIEs for these variables.
1323 DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
1324 DIE *SPDie = ModuleCU->getDIE(SPNode);
1325 assert(SPDie && "Unable to find subprogram DIE!");
1326 DISubprogram SP(SPNode);
1328 // There is not any need to generate specification DIE for a function
1329 // defined at compile unit level. If a function is defined inside another
1330 // function then gdb prefers the definition at top level and but does not
1331 // expect specification DIE in parent function. So avoid creating
1332 // specification DIE for a function defined inside a function.
1333 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1334 !SP.getContext().isFile() && !SP.getContext().isSubprogram()) {
1335 addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1338 DICompositeType SPTy = SP.getType();
1339 DIArray Args = SPTy.getTypeArray();
1340 unsigned SPTag = SPTy.getTag();
1341 if (SPTag == dwarf::DW_TAG_subroutine_type)
1342 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1343 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1344 DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
1346 if (ATy.isArtificial())
1347 addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1348 SPDie->addChild(Arg);
1350 DIE *SPDeclDie = SPDie;
1351 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1352 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1354 ModuleCU->addDie(SPDie);
1357 addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1358 getDWLabel("func_begin", SubprogramCount));
1359 addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1360 getDWLabel("func_end", SubprogramCount));
1361 MachineLocation Location(RI->getFrameRegister(*MF));
1362 addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1364 if (!DISubprogram(SPNode).isLocalToUnit())
1365 addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1370 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1371 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1372 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1373 MCSymbol *Start = Scope->getStartLabel();
1374 MCSymbol *End = Scope->getEndLabel();
1375 if (Start == 0) return 0;
1377 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1378 assert(End->isDefined() && "Invalid end label for an inlined scope!");
1380 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1381 if (Scope->isAbstractScope())
1384 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1385 Start ? Start : getDWLabel("func_begin", SubprogramCount));
1386 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1387 End ? End : getDWLabel("func_end", SubprogramCount));
1392 /// constructInlinedScopeDIE - This scope represents inlined body of
1393 /// a function. Construct DIE to represent this concrete inlined copy
1394 /// of the function.
1395 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1396 MCSymbol *StartLabel = Scope->getStartLabel();
1397 MCSymbol *EndLabel = Scope->getEndLabel();
1398 if (StartLabel == 0) return 0;
1400 assert(StartLabel->isDefined() &&
1401 "Invalid starting label for an inlined scope!");
1402 assert(EndLabel->isDefined() &&
1403 "Invalid end label for an inlined scope!");
1404 if (!Scope->getScopeNode())
1406 DIScope DS(Scope->getScopeNode());
1407 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1409 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1410 DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
1411 assert (OriginDIE && "Unable to find Origin DIE!");
1412 addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1413 dwarf::DW_FORM_ref4, OriginDIE);
1415 addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1416 addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1418 InlinedSubprogramDIEs.insert(OriginDIE);
1420 // Track the start label for this inlined function.
1421 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1422 I = InlineInfo.find(InlinedSP.getNode());
1424 if (I == InlineInfo.end()) {
1425 InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartLabel,
1427 InlinedSPNodes.push_back(InlinedSP.getNode());
1429 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1431 DILocation DL(Scope->getInlinedAt());
1432 addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1433 addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1439 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1440 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1441 // Get the descriptor.
1442 const DIVariable &VD = DV->getVariable();
1443 StringRef Name = VD.getName();
1447 // Translate tag to proper Dwarf tag. The result variable is dropped for
1450 switch (VD.getTag()) {
1451 case dwarf::DW_TAG_return_variable:
1453 case dwarf::DW_TAG_arg_variable:
1454 Tag = dwarf::DW_TAG_formal_parameter;
1456 case dwarf::DW_TAG_auto_variable: // fall thru
1458 Tag = dwarf::DW_TAG_variable;
1462 // Define variable debug information entry.
1463 DIE *VariableDie = new DIE(Tag);
1467 if (DbgVariable *AV = DV->getAbstractVariable())
1468 AbsDIE = AV->getDIE();
1471 DIScope DS(Scope->getScopeNode());
1472 DISubprogram InlinedSP = getDISubprogram(DS.getNode());
1473 DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
1475 assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
1476 DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1477 assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
1478 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1479 dwarf::DW_FORM_ref4, AbsDIE);
1482 addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1483 addSourceLine(VariableDie, &VD);
1485 // Add variable type.
1486 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1487 // addresses instead.
1488 if (VD.isBlockByrefVariable())
1489 addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1491 addType(VariableDie, VD.getType());
1494 // Add variable address.
1495 if (!Scope->isAbstractScope()) {
1496 MachineLocation Location;
1498 int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
1499 Location.set(FrameReg, Offset);
1501 if (VD.hasComplexAddress())
1502 addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1503 else if (VD.isBlockByrefVariable())
1504 addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1506 addAddress(VariableDie, dwarf::DW_AT_location, Location);
1509 if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1510 addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1511 DV->setDIE(VariableDie);
1516 void DwarfDebug::addPubTypes(DISubprogram SP) {
1517 DICompositeType SPTy = SP.getType();
1518 unsigned SPTag = SPTy.getTag();
1519 if (SPTag != dwarf::DW_TAG_subroutine_type)
1522 DIArray Args = SPTy.getTypeArray();
1523 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1524 DIType ATy(Args.getElement(i).getNode());
1527 DICompositeType CATy = getDICompositeType(ATy);
1528 if (DIDescriptor(CATy.getNode()).Verify() && !CATy.getName().empty()) {
1529 if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
1530 ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
1535 /// constructScopeDIE - Construct a DIE for this scope.
1536 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1537 if (!Scope || !Scope->getScopeNode())
1540 DIScope DS(Scope->getScopeNode());
1541 DIE *ScopeDIE = NULL;
1542 if (Scope->getInlinedAt())
1543 ScopeDIE = constructInlinedScopeDIE(Scope);
1544 else if (DS.isSubprogram()) {
1545 if (Scope->isAbstractScope())
1546 ScopeDIE = ModuleCU->getDIE(DS.getNode());
1548 ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
1551 ScopeDIE = constructLexicalScopeDIE(Scope);
1552 if (!ScopeDIE) return NULL;
1555 // Add variables to scope.
1556 const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1557 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1558 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1560 ScopeDIE->addChild(VariableDIE);
1563 // Add nested scopes.
1564 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1565 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1566 // Define the Scope debug information entry.
1567 DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1569 ScopeDIE->addChild(NestedDIE);
1572 if (DS.isSubprogram())
1573 addPubTypes(DISubprogram(DS.getNode()));
1578 /// GetOrCreateSourceID - Look up the source id with the given directory and
1579 /// source file names. If none currently exists, create a new id and insert it
1580 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1582 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) {
1584 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1585 if (DI != DirectoryIdMap.end()) {
1586 DId = DI->getValue();
1588 DId = DirectoryNames.size() + 1;
1589 DirectoryIdMap[DirName] = DId;
1590 DirectoryNames.push_back(DirName);
1594 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1595 if (FI != SourceFileIdMap.end()) {
1596 FId = FI->getValue();
1598 FId = SourceFileNames.size() + 1;
1599 SourceFileIdMap[FileName] = FId;
1600 SourceFileNames.push_back(FileName);
1603 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1604 SourceIdMap.find(std::make_pair(DId, FId));
1605 if (SI != SourceIdMap.end())
1608 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1609 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1610 SourceIds.push_back(std::make_pair(DId, FId));
1615 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1616 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1617 DIE *NDie = ModuleCU->getDIE(NS.getNode());
1620 NDie = new DIE(dwarf::DW_TAG_namespace);
1621 ModuleCU->insertDIE(NS.getNode(), NDie);
1622 if (!NS.getName().empty())
1623 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1624 addSourceLine(NDie, &NS);
1625 addToContextOwner(NDie, NS.getContext());
1629 void DwarfDebug::constructCompileUnit(MDNode *N) {
1630 DICompileUnit DIUnit(N);
1631 // Use first compile unit marked as isMain as the compile unit for this
1633 if (ModuleCU || !DIUnit.isMain())
1635 StringRef FN = DIUnit.getFilename();
1636 StringRef Dir = DIUnit.getDirectory();
1637 unsigned ID = GetOrCreateSourceID(Dir, FN);
1639 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1640 // FIXME: Why getting the delta between two identical labels??
1641 addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1642 getTempLabel("section_line"), getTempLabel("section_line"),
1644 addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1645 DIUnit.getProducer());
1646 addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1647 DIUnit.getLanguage());
1648 addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1651 addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1652 if (DIUnit.isOptimized())
1653 addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1655 StringRef Flags = DIUnit.getFlags();
1657 addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1659 unsigned RVer = DIUnit.getRunTimeVersion();
1661 addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1662 dwarf::DW_FORM_data1, RVer);
1665 "ModuleCU assigned since the top of constructCompileUnit");
1666 ModuleCU = new CompileUnit(ID, Die);
1669 void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
1670 DIGlobalVariable DI_GV(N);
1672 // If debug information is malformed then ignore it.
1673 if (DI_GV.Verify() == false)
1676 // Check for pre-existence.
1677 if (ModuleCU->getDIE(DI_GV.getNode()))
1680 DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1685 ModuleCU->insertDIE(N, VariableDie);
1687 // Add to context owner.
1688 DIDescriptor GVContext = DI_GV.getContext();
1689 // Do not create specification DIE if context is either compile unit
1691 if (DI_GV.isDefinition() && !GVContext.isCompileUnit()
1692 && !GVContext.isFile() && !GVContext.isSubprogram()) {
1693 // Create specification DIE.
1694 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1695 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1696 dwarf::DW_FORM_ref4, VariableDie);
1697 DIEBlock *Block = new DIEBlock();
1698 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1699 addLabel(Block, 0, dwarf::DW_FORM_udata,
1700 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1701 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1702 addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1703 ModuleCU->addDie(VariableSpecDIE);
1705 DIEBlock *Block = new DIEBlock();
1706 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1707 addLabel(Block, 0, dwarf::DW_FORM_udata,
1708 Asm->Mang->getSymbol(DI_GV.getGlobal()));
1709 addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1711 addToContextOwner(VariableDie, GVContext);
1713 // Expose as global. FIXME - need to check external flag.
1714 ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
1716 DIType GTy = DI_GV.getType();
1717 if (GTy.isCompositeType() && !GTy.getName().empty()) {
1718 DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
1719 assert (Entry && "Missing global type!");
1720 ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
1725 void DwarfDebug::constructSubprogramDIE(MDNode *N) {
1728 // Check for pre-existence.
1729 if (ModuleCU->getDIE(N))
1732 if (!SP.isDefinition())
1733 // This is a method declaration which will be handled while constructing
1737 DIE *SubprogramDie = createSubprogramDIE(SP);
1740 ModuleCU->insertDIE(N, SubprogramDie);
1742 // Add to context owner.
1743 addToContextOwner(SubprogramDie, SP.getContext());
1745 // Expose as global.
1746 ModuleCU->addGlobal(SP.getName(), SubprogramDie);
1751 /// beginModule - Emit all Dwarf sections that should come prior to the
1752 /// content. Create global DIEs and emit initial debug info sections.
1753 /// This is inovked by the target AsmPrinter.
1754 void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
1757 if (TimePassesIsEnabled)
1758 DebugTimer->startTimer();
1760 if (!MAI->doesSupportDebugInformation())
1763 DebugInfoFinder DbgFinder;
1764 DbgFinder.processModule(*M);
1766 // Create all the compile unit DIEs.
1767 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1768 E = DbgFinder.compile_unit_end(); I != E; ++I)
1769 constructCompileUnit(*I);
1774 // Create DIEs for each subprogram.
1775 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1776 E = DbgFinder.subprogram_end(); I != E; ++I)
1777 constructSubprogramDIE(*I);
1779 // Create DIEs for each global variable.
1780 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1781 E = DbgFinder.global_variable_end(); I != E; ++I)
1782 constructGlobalVariableDIE(*I);
1786 MMI->setDebugInfoAvailability(true);
1788 // Prime section data.
1789 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1791 // Print out .file directives to specify files for .loc directives. These are
1792 // printed out early so that they precede any .loc directives.
1793 if (MAI->hasDotLocAndDotFile()) {
1794 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1795 // Remember source id starts at 1.
1796 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1797 // FIXME: don't use sys::path for this! This should not depend on the
1799 sys::Path FullPath(getSourceDirectoryName(Id.first));
1801 FullPath.appendComponent(getSourceFileName(Id.second));
1802 assert(AppendOk && "Could not append filename to directory!");
1804 Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1808 // Emit initial sections
1811 if (TimePassesIsEnabled)
1812 DebugTimer->stopTimer();
1815 /// endModule - Emit all Dwarf sections that should come after the content.
1817 void DwarfDebug::endModule() {
1821 if (TimePassesIsEnabled)
1822 DebugTimer->startTimer();
1824 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1825 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1826 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1828 addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1831 // Insert top level DIEs.
1832 for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(),
1833 TE = TopLevelDIEsVector.end(); TI != TE; ++TI)
1834 ModuleCU->getCUDie()->addChild(*TI);
1836 for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
1837 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1838 DIE *SPDie = CI->first;
1839 MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1841 DIE *NDie = ModuleCU->getDIE(N);
1842 if (!NDie) continue;
1843 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1844 // FIXME - This is not the correct approach.
1845 // addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1848 // Standard sections final addresses.
1849 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1850 Asm->OutStreamer.EmitLabel(getTempLabel("text_end"));
1851 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1852 Asm->OutStreamer.EmitLabel(getTempLabel("data_end"));
1854 // End text sections.
1855 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1856 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1857 Asm->OutStreamer.EmitLabel(getDWLabel("section_end", i));
1860 // Emit common frame information.
1861 emitCommonDebugFrame();
1863 // Emit function debug frame information
1864 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1865 E = DebugFrames.end(); I != E; ++I)
1866 emitFunctionDebugFrame(*I);
1868 // Compute DIE offsets and sizes.
1869 computeSizeAndOffsets();
1871 // Emit all the DIEs into a debug info section
1874 // Corresponding abbreviations into a abbrev section.
1875 emitAbbreviations();
1877 // Emit source line correspondence into a debug line section.
1880 // Emit info into a debug pubnames section.
1881 emitDebugPubNames();
1883 // Emit info into a debug pubtypes section.
1884 emitDebugPubTypes();
1886 // Emit info into a debug loc section.
1889 // Emit info into a debug aranges section.
1892 // Emit info into a debug ranges section.
1895 // Emit info into a debug macinfo section.
1898 // Emit inline info.
1899 emitDebugInlineInfo();
1901 // Emit info into a debug str section.
1905 ModuleCU = NULL; // Reset for the next Module, if any.
1907 if (TimePassesIsEnabled)
1908 DebugTimer->stopTimer();
1911 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1912 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1914 DILocation &ScopeLoc) {
1916 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
1918 return AbsDbgVariable;
1920 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
1924 AbsDbgVariable = new DbgVariable(Var, FrameIdx,
1925 NULL /* No more-abstract variable*/);
1926 Scope->addVariable(AbsDbgVariable);
1927 AbstractVariables[Var.getNode()] = AbsDbgVariable;
1928 return AbsDbgVariable;
1931 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1932 void DwarfDebug::collectVariableInfo() {
1935 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1936 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1937 VE = VMap.end(); VI != VE; ++VI) {
1938 MDNode *Var = VI->first;
1940 DIVariable DV (Var);
1941 std::pair< unsigned, MDNode *> VP = VI->second;
1942 DILocation ScopeLoc(VP.second);
1945 ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
1947 Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
1948 // If variable scope is not found then skip this variable.
1952 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, ScopeLoc);
1953 DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
1954 Scope->addVariable(RegVar);
1958 /// beginScope - Process beginning of a scope starting at Label.
1959 void DwarfDebug::beginScope(const MachineInstr *MI, MCSymbol *Label) {
1960 InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
1961 if (I == DbgScopeBeginMap.end())
1963 ScopeVector &SD = I->second;
1964 for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
1966 (*SDI)->setStartLabel(Label);
1969 /// endScope - Process end of a scope.
1970 void DwarfDebug::endScope(const MachineInstr *MI) {
1971 InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
1972 if (I == DbgScopeEndMap.end())
1975 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
1976 Asm->OutStreamer.EmitLabel(Label);
1978 SmallVector<DbgScope*, 2> &SD = I->second;
1979 for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
1981 (*SDI)->setEndLabel(Label);
1985 /// createDbgScope - Create DbgScope for the scope.
1986 void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
1989 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1992 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1993 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1994 if (DIDescriptor(Scope).isLexicalBlock())
1995 createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
1999 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2003 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2004 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2005 DILocation DL(InlinedAt);
2006 createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
2009 /// extractScopeInformation - Scan machine instructions in this function
2010 /// and collect DbgScopes. Return true, if atleast one scope was found.
2011 bool DwarfDebug::extractScopeInformation() {
2012 // If scope information was extracted using .dbg intrinsics then there is not
2013 // any need to extract these information by scanning each instruction.
2014 if (!DbgScopeMap.empty())
2017 DenseMap<const MachineInstr *, unsigned> MIIndexMap;
2018 unsigned MIIndex = 0;
2019 // Scan each instruction and create scopes. First build working set of scopes.
2020 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2022 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2024 const MachineInstr *MInsn = II;
2025 MIIndexMap[MInsn] = MIIndex++;
2026 DebugLoc DL = MInsn->getDebugLoc();
2027 if (DL.isUnknown()) continue;
2028 DILocation DLT = MF->getDILocation(DL);
2029 DIScope DLTScope = DLT.getScope();
2030 // There is no need to create another DIE for compile unit. For all
2031 // other scopes, create one DbgScope now. This will be translated
2032 // into a scope DIE at the end.
2033 if (DLTScope.isCompileUnit()) continue;
2034 createDbgScope(DLTScope.getNode(), DLT.getOrigLocation().getNode());
2039 // Build scope hierarchy using working set of scopes.
2040 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2042 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2044 const MachineInstr *MInsn = II;
2045 DebugLoc DL = MInsn->getDebugLoc();
2046 if (DL.isUnknown()) continue;
2047 DILocation DLT = MF->getDILocation(DL);
2048 DIScope DLTScope = DLT.getScope();
2049 // There is no need to create another DIE for compile unit. For all
2050 // other scopes, create one DbgScope now. This will be translated
2051 // into a scope DIE at the end.
2052 if (DLTScope.isCompileUnit()) continue;
2053 DbgScope *Scope = getUpdatedDbgScope(DLTScope.getNode(), MInsn,
2054 DLT.getOrigLocation().getNode());
2055 Scope->setLastInsn(MInsn);
2059 if (!CurrentFnDbgScope)
2062 CurrentFnDbgScope->fixInstructionMarkers(MIIndexMap);
2064 // Each scope has first instruction and last instruction to mark beginning
2065 // and end of a scope respectively. Create an inverse map that list scopes
2066 // starts (and ends) with an instruction. One instruction may start (or end)
2067 // multiple scopes. Ignore scopes that are not reachable.
2068 SmallVector<DbgScope *, 4> WorkList;
2069 WorkList.push_back(CurrentFnDbgScope);
2070 while (!WorkList.empty()) {
2071 DbgScope *S = WorkList.back(); WorkList.pop_back();
2073 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2074 if (!Children.empty())
2075 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2076 SE = Children.end(); SI != SE; ++SI)
2077 WorkList.push_back(*SI);
2079 if (S->isAbstractScope())
2081 const MachineInstr *MI = S->getFirstInsn();
2082 assert (MI && "DbgScope does not have first instruction!");
2084 InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
2085 if (IDI != DbgScopeBeginMap.end())
2086 IDI->second.push_back(S);
2088 DbgScopeBeginMap[MI].push_back(S);
2090 MI = S->getLastInsn();
2091 assert (MI && "DbgScope does not have last instruction!");
2092 IDI = DbgScopeEndMap.find(MI);
2093 if (IDI != DbgScopeEndMap.end())
2094 IDI->second.push_back(S);
2096 DbgScopeEndMap[MI].push_back(S);
2099 return !DbgScopeMap.empty();
2102 /// beginFunction - Gather pre-function debug information. Assumes being
2103 /// emitted immediately after the function entry point.
2104 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2107 if (!ShouldEmitDwarfDebug()) return;
2109 if (TimePassesIsEnabled)
2110 DebugTimer->startTimer();
2112 if (!extractScopeInformation())
2115 collectVariableInfo();
2117 // Assumes in correct section after the entry point.
2118 Asm->OutStreamer.EmitLabel(getDWLabel("func_begin", ++SubprogramCount));
2120 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2122 DebugLoc FDL = MF->getDefaultDebugLoc();
2123 if (!FDL.isUnknown()) {
2124 DILocation DLT = MF->getDILocation(FDL);
2125 DISubprogram SP = getDISubprogram(DLT.getScope().getNode());
2128 Line = SP.getLineNumber();
2131 Line = DLT.getLineNumber();
2132 Col = DLT.getColumnNumber();
2135 recordSourceLine(Line, Col, DLT.getScope().getNode());
2137 if (TimePassesIsEnabled)
2138 DebugTimer->stopTimer();
2141 /// endFunction - Gather and emit post-function debug information.
2143 void DwarfDebug::endFunction(const MachineFunction *MF) {
2144 if (!ShouldEmitDwarfDebug()) return;
2146 if (TimePassesIsEnabled)
2147 DebugTimer->startTimer();
2149 if (DbgScopeMap.empty())
2152 if (CurrentFnDbgScope) {
2153 // Define end label for subprogram.
2154 Asm->OutStreamer.EmitLabel(getDWLabel("func_end", SubprogramCount));
2156 // Get function line info.
2157 if (!Lines.empty()) {
2158 // Get section line info.
2159 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2160 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2161 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2162 // Append the function info to section info.
2163 SectionLineInfos.insert(SectionLineInfos.end(),
2164 Lines.begin(), Lines.end());
2167 // Construct abstract scopes.
2168 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2169 AE = AbstractScopesList.end(); AI != AE; ++AI)
2170 constructScopeDIE(*AI);
2172 constructScopeDIE(CurrentFnDbgScope);
2174 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2175 MMI->getFrameMoves()));
2179 CurrentFnDbgScope = NULL;
2180 DeleteContainerSeconds(DbgScopeMap);
2181 DbgScopeBeginMap.clear();
2182 DbgScopeEndMap.clear();
2183 ConcreteScopes.clear();
2184 DeleteContainerSeconds(AbstractScopes);
2185 AbstractScopesList.clear();
2186 AbstractVariables.clear();
2189 if (TimePassesIsEnabled)
2190 DebugTimer->stopTimer();
2193 /// recordSourceLine - Register a source line with debug info. Returns the
2194 /// unique label that was emitted and which provides correspondence to
2195 /// the source line list.
2196 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, MDNode *S) {
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 MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2224 Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2226 if (TimePassesIsEnabled)
2227 DebugTimer->stopTimer();
2229 Asm->OutStreamer.EmitLabel(Label);
2233 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2234 /// timed. Look up the source id with the given directory and source file
2235 /// names. If none currently exists, create a new id and insert it in the
2236 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2238 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2239 const std::string &FileName) {
2240 if (TimePassesIsEnabled)
2241 DebugTimer->startTimer();
2243 unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
2245 if (TimePassesIsEnabled)
2246 DebugTimer->stopTimer();
2251 //===----------------------------------------------------------------------===//
2253 //===----------------------------------------------------------------------===//
2255 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2258 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2259 // Get the children.
2260 const std::vector<DIE *> &Children = Die->getChildren();
2262 // If not last sibling and has children then add sibling offset attribute.
2263 if (!Last && !Children.empty()) Die->addSiblingOffset();
2265 // Record the abbreviation.
2266 assignAbbrevNumber(Die->getAbbrev());
2268 // Get the abbreviation for this DIE.
2269 unsigned AbbrevNumber = Die->getAbbrevNumber();
2270 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2273 Die->setOffset(Offset);
2275 // Start the size with the size of abbreviation code.
2276 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2278 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2279 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2281 // Size the DIE attribute values.
2282 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2283 // Size attribute value.
2284 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
2286 // Size the DIE children if any.
2287 if (!Children.empty()) {
2288 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2289 "Children flag not set");
2291 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2292 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2294 // End of children marker.
2295 Offset += sizeof(int8_t);
2298 Die->setSize(Offset - Die->getOffset());
2302 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2304 void DwarfDebug::computeSizeAndOffsets() {
2305 // Compute size of compile unit header.
2306 static unsigned Offset =
2307 sizeof(int32_t) + // Length of Compilation Unit Info
2308 sizeof(int16_t) + // DWARF version number
2309 sizeof(int32_t) + // Offset Into Abbrev. Section
2310 sizeof(int8_t); // Pointer Size (in bytes)
2312 computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
2313 CompileUnitOffsets[ModuleCU] = 0;
2316 /// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
2317 /// tools to recognize the object file contains Dwarf information.
2318 void DwarfDebug::emitInitial() {
2319 // Check to see if we already emitted intial headers.
2320 if (didInitial) return;
2323 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2325 // Dwarf sections base addresses.
2326 if (MAI->doesDwarfRequireFrameSection()) {
2327 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
2328 Asm->OutStreamer.EmitLabel(getTempLabel("section_debug_frame"));
2331 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
2332 Asm->OutStreamer.EmitLabel(getTempLabel("section_info"));
2333 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
2334 Asm->OutStreamer.EmitLabel(getTempLabel("section_abbrev"));
2335 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
2336 Asm->OutStreamer.EmitLabel(getTempLabel("section_aranges"));
2338 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
2339 Asm->OutStreamer.SwitchSection(LineInfoDirective);
2340 Asm->OutStreamer.EmitLabel(getTempLabel("section_macinfo"));
2343 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
2344 Asm->OutStreamer.EmitLabel(getTempLabel("section_line"));
2345 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
2346 Asm->OutStreamer.EmitLabel(getTempLabel("section_loc"));
2347 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
2348 Asm->OutStreamer.EmitLabel(getTempLabel("section_pubnames"));
2349 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection());
2350 Asm->OutStreamer.EmitLabel(getTempLabel("section_pubtypes"));
2351 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
2352 Asm->OutStreamer.EmitLabel(getTempLabel("section_str"));
2353 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
2354 Asm->OutStreamer.EmitLabel(getTempLabel("section_ranges"));
2356 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
2357 Asm->OutStreamer.EmitLabel(getTempLabel("text_begin"));
2358 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
2359 Asm->OutStreamer.EmitLabel(getTempLabel("data_begin"));
2362 /// emitDIE - Recusively Emits a debug information entry.
2364 void DwarfDebug::emitDIE(DIE *Die) {
2365 // Get the abbreviation for this DIE.
2366 unsigned AbbrevNumber = Die->getAbbrevNumber();
2367 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2369 // Emit the code (index) for the abbreviation.
2370 if (Asm->VerboseAsm)
2371 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2372 Twine::utohexstr(Die->getOffset()) + ":0x" +
2373 Twine::utohexstr(Die->getSize()) + " " +
2374 dwarf::TagString(Abbrev->getTag()));
2375 EmitULEB128(AbbrevNumber);
2377 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2378 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2380 // Emit the DIE attribute values.
2381 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2382 unsigned Attr = AbbrevData[i].getAttribute();
2383 unsigned Form = AbbrevData[i].getForm();
2384 assert(Form && "Too many attributes for DIE (check abbreviation)");
2386 if (Asm->VerboseAsm)
2387 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2390 case dwarf::DW_AT_sibling:
2391 Asm->EmitInt32(Die->getSiblingOffset());
2393 case dwarf::DW_AT_abstract_origin: {
2394 DIEEntry *E = cast<DIEEntry>(Values[i]);
2395 DIE *Origin = E->getEntry();
2396 unsigned Addr = Origin->getOffset();
2397 Asm->EmitInt32(Addr);
2401 // Emit an attribute using the defined form.
2402 Values[i]->EmitValue(this, Form);
2407 // Emit the DIE children if any.
2408 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2409 const std::vector<DIE *> &Children = Die->getChildren();
2411 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2412 emitDIE(Children[j]);
2414 if (Asm->VerboseAsm)
2415 Asm->OutStreamer.AddComment("End Of Children Mark");
2420 /// emitDebugInfo - Emit the debug info section.
2422 void DwarfDebug::emitDebugInfo() {
2423 // Start debug info section.
2424 Asm->OutStreamer.SwitchSection(
2425 Asm->getObjFileLowering().getDwarfInfoSection());
2426 DIE *Die = ModuleCU->getCUDie();
2428 // Emit the compile units header.
2429 Asm->OutStreamer.EmitLabel(getDWLabel("info_begin", ModuleCU->getID()));
2431 // Emit size of content not including length itself
2432 unsigned ContentSize = Die->getSize() +
2433 sizeof(int16_t) + // DWARF version number
2434 sizeof(int32_t) + // Offset Into Abbrev. Section
2435 sizeof(int8_t) + // Pointer Size (in bytes)
2436 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2438 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2439 Asm->EmitInt32(ContentSize);
2440 Asm->OutStreamer.AddComment("DWARF version number");
2441 Asm->EmitInt16(dwarf::DWARF_VERSION);
2442 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2443 EmitSectionOffset(getTempLabel("abbrev_begin"),getTempLabel("section_abbrev"),
2445 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2446 Asm->EmitInt8(TD->getPointerSize());
2449 // FIXME - extra padding for gdb bug.
2450 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2455 Asm->OutStreamer.EmitLabel(getDWLabel("info_end", ModuleCU->getID()));
2458 /// emitAbbreviations - Emit the abbreviation section.
2460 void DwarfDebug::emitAbbreviations() const {
2461 // Check to see if it is worth the effort.
2462 if (!Abbreviations.empty()) {
2463 // Start the debug abbrev section.
2464 Asm->OutStreamer.SwitchSection(
2465 Asm->getObjFileLowering().getDwarfAbbrevSection());
2467 Asm->OutStreamer.EmitLabel(getTempLabel("abbrev_begin"));
2469 // For each abbrevation.
2470 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2471 // Get abbreviation data
2472 const DIEAbbrev *Abbrev = Abbreviations[i];
2474 // Emit the abbrevations code (base 1 index.)
2475 EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2477 // Emit the abbreviations data.
2481 // Mark end of abbreviations.
2482 EmitULEB128(0, "EOM(3)");
2484 Asm->OutStreamer.EmitLabel(getTempLabel("abbrev_end"));
2488 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2489 /// the line matrix.
2491 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2492 // Define last address of section.
2493 Asm->OutStreamer.AddComment("Extended Op");
2496 Asm->OutStreamer.AddComment("Op size");
2497 Asm->EmitInt8(TD->getPointerSize() + 1);
2498 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2499 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2501 Asm->OutStreamer.AddComment("Section end label");
2503 Asm->OutStreamer.EmitSymbolValue(getDWLabel("section_end", SectionEnd),
2504 TD->getPointerSize(), 0/*AddrSpace*/);
2506 // Mark end of matrix.
2507 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2513 /// emitDebugLines - Emit source line information.
2515 void DwarfDebug::emitDebugLines() {
2516 // If the target is using .loc/.file, the assembler will be emitting the
2517 // .debug_line table automatically.
2518 if (MAI->hasDotLocAndDotFile())
2521 // Minimum line delta, thus ranging from -10..(255-10).
2522 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2523 // Maximum line delta, thus ranging from -10..(255-10).
2524 const int MaxLineDelta = 255 + MinLineDelta;
2526 // Start the dwarf line section.
2527 Asm->OutStreamer.SwitchSection(
2528 Asm->getObjFileLowering().getDwarfLineSection());
2530 // Construct the section header.
2531 Asm->OutStreamer.AddComment("Length of Source Line Info");
2532 EmitDifference(getTempLabel("line_end"), getTempLabel("line_begin"), true);
2533 Asm->OutStreamer.EmitLabel(getTempLabel("line_begin"));
2535 Asm->OutStreamer.AddComment("DWARF version number");
2536 Asm->EmitInt16(dwarf::DWARF_VERSION);
2538 Asm->OutStreamer.AddComment("Prolog Length");
2539 EmitDifference(getTempLabel("line_prolog_end"),
2540 getTempLabel("line_prolog_begin"), true);
2541 Asm->OutStreamer.EmitLabel(getTempLabel("line_prolog_begin"));
2543 Asm->OutStreamer.AddComment("Minimum Instruction Length");
2545 Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2547 Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2548 Asm->EmitInt8(MinLineDelta);
2549 Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
2550 Asm->EmitInt8(MaxLineDelta);
2551 Asm->OutStreamer.AddComment("Special Opcode Base");
2552 Asm->EmitInt8(-MinLineDelta);
2554 // Line number standard opcode encodings argument count
2555 Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
2557 Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
2559 Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
2561 Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
2563 Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
2565 Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
2567 Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
2569 Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
2571 Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
2574 // Emit directories.
2575 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2576 const std::string &Dir = getSourceDirectoryName(DI);
2577 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("Directory");
2578 Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
2581 Asm->OutStreamer.AddComment("End of directories");
2585 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2586 // Remember source id starts at 1.
2587 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2588 const std::string &FN = getSourceFileName(Id.second);
2589 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("Source");
2590 Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
2592 EmitULEB128(Id.first, "Directory #");
2593 EmitULEB128(0, "Mod date");
2594 EmitULEB128(0, "File size");
2597 Asm->OutStreamer.AddComment("End of files");
2600 Asm->OutStreamer.EmitLabel(getTempLabel("line_prolog_end"));
2602 // A sequence for each text section.
2603 unsigned SecSrcLinesSize = SectionSourceLines.size();
2605 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2606 // Isolate current sections line info.
2607 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2609 // Dwarf assumes we start with first line of first source file.
2610 unsigned Source = 1;
2613 // Construct rows of the address, source, line, column matrix.
2614 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2615 const SrcLineInfo &LineInfo = LineInfos[i];
2616 MCSymbol *Label = LineInfo.getLabel();
2617 if (!Label->isDefined()) continue; // Not emitted, in dead code.
2619 if (LineInfo.getLine() == 0) continue;
2621 if (Asm->isVerbose()) {
2622 std::pair<unsigned, unsigned> SrcID =
2623 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2624 Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
2626 Twine(getSourceFileName(SrcID.second)) +
2627 ":" + Twine(LineInfo.getLine()));
2630 // Define the line address.
2631 Asm->OutStreamer.AddComment("Extended Op");
2633 Asm->OutStreamer.AddComment("Op size");
2634 Asm->EmitInt8(TD->getPointerSize() + 1);
2636 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2637 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2639 Asm->OutStreamer.AddComment("Location label");
2640 Asm->OutStreamer.EmitSymbolValue(Label, TD->getPointerSize(),
2643 // If change of source, then switch to the new source.
2644 if (Source != LineInfo.getSourceID()) {
2645 Source = LineInfo.getSourceID();
2646 Asm->OutStreamer.AddComment("DW_LNS_set_file");
2647 Asm->EmitInt8(dwarf::DW_LNS_set_file);
2648 EmitULEB128(Source, "New Source");
2651 // If change of line.
2652 if (Line != LineInfo.getLine()) {
2653 // Determine offset.
2654 int Offset = LineInfo.getLine() - Line;
2655 int Delta = Offset - MinLineDelta;
2658 Line = LineInfo.getLine();
2660 // If delta is small enough and in range...
2661 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2662 // ... then use fast opcode.
2663 Asm->OutStreamer.AddComment("Line Delta");
2664 Asm->EmitInt8(Delta - MinLineDelta);
2666 // ... otherwise use long hand.
2667 Asm->OutStreamer.AddComment("DW_LNS_advance_line");
2668 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2669 EmitSLEB128(Offset, "Line Offset");
2670 Asm->OutStreamer.AddComment("DW_LNS_copy");
2671 Asm->EmitInt8(dwarf::DW_LNS_copy);
2674 // Copy the previous row (different address or source)
2675 Asm->OutStreamer.AddComment("DW_LNS_copy");
2676 Asm->EmitInt8(dwarf::DW_LNS_copy);
2680 emitEndOfLineMatrix(j + 1);
2683 if (SecSrcLinesSize == 0)
2684 // Because we're emitting a debug_line section, we still need a line
2685 // table. The linker and friends expect it to exist. If there's nothing to
2686 // put into it, emit an empty table.
2687 emitEndOfLineMatrix(1);
2689 Asm->OutStreamer.EmitLabel(getTempLabel("line_end"));
2692 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2694 void DwarfDebug::emitCommonDebugFrame() {
2695 if (!MAI->doesDwarfRequireFrameSection())
2699 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2700 TargetFrameInfo::StackGrowsUp ?
2701 TD->getPointerSize() : -TD->getPointerSize();
2703 // Start the dwarf frame section.
2704 Asm->OutStreamer.SwitchSection(
2705 Asm->getObjFileLowering().getDwarfFrameSection());
2707 Asm->OutStreamer.EmitLabel(getTempLabel("debug_frame_common"));
2708 Asm->OutStreamer.AddComment("Length of Common Information Entry");
2709 EmitDifference(getTempLabel("debug_frame_common_end"),
2710 getTempLabel("debug_frame_common_begin"), true);
2712 Asm->OutStreamer.EmitLabel(getTempLabel("debug_frame_common_begin"));
2713 Asm->OutStreamer.AddComment("CIE Identifier Tag");
2714 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2715 Asm->OutStreamer.AddComment("CIE Version");
2716 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2717 Asm->OutStreamer.AddComment("CIE Augmentation");
2718 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
2719 EmitULEB128(1, "CIE Code Alignment Factor");
2720 EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
2721 Asm->OutStreamer.AddComment("CIE RA Column");
2722 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2724 std::vector<MachineMove> Moves;
2725 RI->getInitialFrameState(Moves);
2727 EmitFrameMoves(0, Moves, false);
2729 Asm->EmitAlignment(2, 0, 0, false);
2730 Asm->OutStreamer.EmitLabel(getTempLabel("debug_frame_common_end"));
2733 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2736 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2737 if (!MAI->doesDwarfRequireFrameSection())
2740 // Start the dwarf frame section.
2741 Asm->OutStreamer.SwitchSection(
2742 Asm->getObjFileLowering().getDwarfFrameSection());
2744 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
2745 MCSymbol *DebugFrameBegin =
2746 getDWLabel("debug_frame_begin", DebugFrameInfo.Number);
2747 MCSymbol *DebugFrameEnd =
2748 getDWLabel("debug_frame_end", DebugFrameInfo.Number);
2749 EmitDifference(DebugFrameEnd, DebugFrameBegin, true);
2751 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
2753 Asm->OutStreamer.AddComment("FDE CIE offset");
2754 EmitSectionOffset(getTempLabel("debug_frame_common"),
2755 getTempLabel("section_debug_frame"), true, false);
2757 Asm->OutStreamer.AddComment("FDE initial location");
2758 MCSymbol *FuncBeginSym = getDWLabel("func_begin", DebugFrameInfo.Number);
2759 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
2760 TD->getPointerSize(), 0/*AddrSpace*/);
2763 Asm->OutStreamer.AddComment("FDE address range");
2764 EmitDifference(getDWLabel("func_end", DebugFrameInfo.Number), FuncBeginSym);
2766 EmitFrameMoves(FuncBeginSym, DebugFrameInfo.Moves, false);
2768 Asm->EmitAlignment(2, 0, 0, false);
2769 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
2772 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2774 void DwarfDebug::emitDebugPubNames() {
2775 // Start the dwarf pubnames section.
2776 Asm->OutStreamer.SwitchSection(
2777 Asm->getObjFileLowering().getDwarfPubNamesSection());
2779 Asm->OutStreamer.AddComment("Length of Public Names Info");
2780 EmitDifference(getDWLabel("pubnames_end", ModuleCU->getID()),
2781 getDWLabel("pubnames_begin", ModuleCU->getID()), true);
2783 Asm->OutStreamer.EmitLabel(getDWLabel("pubnames_begin", ModuleCU->getID()));
2785 Asm->OutStreamer.AddComment("DWARF Version");
2786 Asm->EmitInt16(dwarf::DWARF_VERSION);
2788 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2789 EmitSectionOffset(getDWLabel("info_begin", ModuleCU->getID()),
2790 getTempLabel("section_info"),
2793 Asm->OutStreamer.AddComment("Compilation Unit Length");
2794 EmitDifference(getDWLabel("info_end", ModuleCU->getID()),
2795 getDWLabel("info_begin", ModuleCU->getID()),
2798 const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
2799 for (StringMap<DIE*>::const_iterator
2800 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2801 const char *Name = GI->getKeyData();
2802 DIE *Entity = GI->second;
2804 Asm->OutStreamer.AddComment("DIE offset");
2805 Asm->EmitInt32(Entity->getOffset());
2807 if (Asm->VerboseAsm)
2808 Asm->OutStreamer.AddComment("External Name");
2809 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2812 Asm->OutStreamer.AddComment("End Mark");
2814 Asm->OutStreamer.EmitLabel(getDWLabel("pubnames_end", ModuleCU->getID()));
2817 void DwarfDebug::emitDebugPubTypes() {
2818 // Start the dwarf pubnames section.
2819 Asm->OutStreamer.SwitchSection(
2820 Asm->getObjFileLowering().getDwarfPubTypesSection());
2821 Asm->OutStreamer.AddComment("Length of Public Types Info");
2822 EmitDifference(getDWLabel("pubtypes_end", ModuleCU->getID()),
2823 getDWLabel("pubtypes_begin", ModuleCU->getID()), true);
2825 Asm->OutStreamer.EmitLabel(getDWLabel("pubtypes_begin", ModuleCU->getID()));
2827 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DWARF Version");
2828 Asm->EmitInt16(dwarf::DWARF_VERSION);
2830 Asm->OutStreamer.AddComment("Offset of Compilation ModuleCU Info");
2831 EmitSectionOffset(getDWLabel("info_begin", ModuleCU->getID()),
2832 getTempLabel("section_info"), true, false);
2834 Asm->OutStreamer.AddComment("Compilation ModuleCU Length");
2835 EmitDifference(getDWLabel("info_end", ModuleCU->getID()),
2836 getDWLabel("info_begin", ModuleCU->getID()),
2839 const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
2840 for (StringMap<DIE*>::const_iterator
2841 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2842 const char *Name = GI->getKeyData();
2843 DIE * Entity = GI->second;
2845 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DIE offset");
2846 Asm->EmitInt32(Entity->getOffset());
2848 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("External Name");
2849 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2852 Asm->OutStreamer.AddComment("End Mark");
2854 Asm->OutStreamer.EmitLabel(getDWLabel("pubtypes_end", ModuleCU->getID()));
2857 /// emitDebugStr - Emit visible names into a debug str section.
2859 void DwarfDebug::emitDebugStr() {
2860 // Check to see if it is worth the effort.
2861 if (StringPool.empty()) return;
2863 // Start the dwarf str section.
2864 Asm->OutStreamer.SwitchSection(
2865 Asm->getObjFileLowering().getDwarfStrSection());
2867 // Get all of the string pool entries and put them in an array by their ID so
2868 // we can sort them.
2869 SmallVector<std::pair<unsigned,
2870 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2872 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2873 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2874 Entries.push_back(std::make_pair(I->second.second, &*I));
2876 array_pod_sort(Entries.begin(), Entries.end());
2878 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2879 // Emit a label for reference from debug information entries.
2880 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2882 // Emit the string itself.
2883 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
2887 /// emitDebugLoc - Emit visible names into a debug loc section.
2889 void DwarfDebug::emitDebugLoc() {
2890 // Start the dwarf loc section.
2891 Asm->OutStreamer.SwitchSection(
2892 Asm->getObjFileLowering().getDwarfLocSection());
2895 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2897 void DwarfDebug::EmitDebugARanges() {
2898 // Start the dwarf aranges section.
2899 Asm->OutStreamer.SwitchSection(
2900 Asm->getObjFileLowering().getDwarfARangesSection());
2903 /// emitDebugRanges - Emit visible names into a debug ranges section.
2905 void DwarfDebug::emitDebugRanges() {
2906 // Start the dwarf ranges section.
2907 Asm->OutStreamer.SwitchSection(
2908 Asm->getObjFileLowering().getDwarfRangesSection());
2911 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2913 void DwarfDebug::emitDebugMacInfo() {
2914 if (const MCSection *LineInfo =
2915 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2916 // Start the dwarf macinfo section.
2917 Asm->OutStreamer.SwitchSection(LineInfo);
2921 /// emitDebugInlineInfo - Emit inline info using following format.
2923 /// 1. length of section
2924 /// 2. Dwarf version number
2925 /// 3. address size.
2927 /// Entries (one "entry" for each function that was inlined):
2929 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2930 /// otherwise offset into __debug_str for regular function name.
2931 /// 2. offset into __debug_str section for regular function name.
2932 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2933 /// instances for the function.
2935 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2936 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2937 /// __debug_info section, and the low_pc is the starting address for the
2938 /// inlining instance.
2939 void DwarfDebug::emitDebugInlineInfo() {
2940 if (!MAI->doesDwarfUsesInlineInfoSection())
2946 Asm->OutStreamer.SwitchSection(
2947 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2949 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2950 EmitDifference(getDWLabel("debug_inlined_end", 1),
2951 getDWLabel("debug_inlined_begin", 1), true);
2953 Asm->OutStreamer.EmitLabel(getDWLabel("debug_inlined_begin", 1));
2955 Asm->OutStreamer.AddComment("Dwarf Version");
2956 Asm->EmitInt16(dwarf::DWARF_VERSION);
2957 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2958 Asm->EmitInt8(TD->getPointerSize());
2960 for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2961 E = InlinedSPNodes.end(); I != E; ++I) {
2964 DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2965 = InlineInfo.find(Node);
2966 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2967 DISubprogram SP(Node);
2968 StringRef LName = SP.getLinkageName();
2969 StringRef Name = SP.getName();
2971 Asm->OutStreamer.AddComment("MIPS linkage name");
2972 if (LName.empty()) {
2973 Asm->OutStreamer.EmitBytes(Name, 0);
2974 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2976 EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2977 getTempLabel("section_str"), true);
2979 Asm->OutStreamer.AddComment("Function name");
2980 EmitSectionOffset(getStringPoolEntry(Name), getTempLabel("section_str"),
2982 EmitULEB128(Labels.size(), "Inline count");
2984 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2985 LE = Labels.end(); LI != LE; ++LI) {
2986 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DIE offset");
2987 Asm->EmitInt32(LI->second->getOffset());
2989 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("low_pc");
2990 Asm->OutStreamer.EmitSymbolValue(LI->first, TD->getPointerSize(), 0);
2994 Asm->OutStreamer.EmitLabel(getDWLabel("debug_inlined_end", 1));