blob: 3e6ac356a5afcb14a3d4ed2c733a6b7bc27a399f [file] [log] [blame]
Bill Wendling0310d762009-05-15 09:23:25 +00001//===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for writing dwarf debug info into asm files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DwarfDebug.h"
15#include "llvm/Module.h"
16#include "llvm/CodeGen/MachineModuleInfo.h"
17#include "llvm/Support/Timer.h"
18#include "llvm/System/Path.h"
19#include "llvm/Target/TargetAsmInfo.h"
20#include "llvm/Target/TargetRegisterInfo.h"
21#include "llvm/Target/TargetData.h"
22#include "llvm/Target/TargetFrameInfo.h"
23#include <ostream>
24using namespace llvm;
25
26static TimerGroup &getDwarfTimerGroup() {
27 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
28 return DwarfTimerGroup;
29}
30
31//===----------------------------------------------------------------------===//
32
33/// Configuration values for initial hash set sizes (log2).
34///
35static const unsigned InitDiesSetSize = 9; // log2(512)
36static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
37static const unsigned InitValuesSetSize = 9; // log2(512)
38
39namespace llvm {
40
41//===----------------------------------------------------------------------===//
42/// CompileUnit - This dwarf writer support class manages information associate
43/// with a source file.
44class VISIBILITY_HIDDEN CompileUnit {
45 /// ID - File identifier for source.
46 ///
47 unsigned ID;
48
49 /// Die - Compile unit debug information entry.
50 ///
51 DIE *Die;
52
53 /// GVToDieMap - Tracks the mapping of unit level debug informaton
54 /// variables to debug information entries.
55 std::map<GlobalVariable *, DIE *> GVToDieMap;
56
57 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
58 /// descriptors to debug information entries using a DIEEntry proxy.
59 std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
60
61 /// Globals - A map of globally visible named entities for this unit.
62 ///
63 StringMap<DIE*> Globals;
64
65 /// DiesSet - Used to uniquely define dies within the compile unit.
66 ///
67 FoldingSet<DIE> DiesSet;
68public:
69 CompileUnit(unsigned I, DIE *D)
70 : ID(I), Die(D), GVToDieMap(),
71 GVToDIEEntryMap(), Globals(), DiesSet(InitDiesSetSize)
72 {}
73
74 ~CompileUnit() {
75 delete Die;
76 }
77
78 // Accessors.
79 unsigned getID() const { return ID; }
80 DIE* getDie() const { return Die; }
81 StringMap<DIE*> &getGlobals() { return Globals; }
82
83 /// hasContent - Return true if this compile unit has something to write out.
84 ///
85 bool hasContent() const {
86 return !Die->getChildren().empty();
87 }
88
89 /// AddGlobal - Add a new global entity to the compile unit.
90 ///
91 void AddGlobal(const std::string &Name, DIE *Die) {
92 Globals[Name] = Die;
93 }
94
95 /// getDieMapSlotFor - Returns the debug information entry map slot for the
96 /// specified debug variable.
97 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
98 return GVToDieMap[GV];
99 }
100
101 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for the
102 /// specified debug variable.
103 DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
104 return GVToDIEEntryMap[GV];
105 }
106
107 /// AddDie - Adds or interns the DIE to the compile unit.
108 ///
109 DIE *AddDie(DIE &Buffer) {
110 FoldingSetNodeID ID;
111 Buffer.Profile(ID);
112 void *Where;
113 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
114
115 if (!Die) {
116 Die = new DIE(Buffer);
117 DiesSet.InsertNode(Die, Where);
118 this->Die->AddChild(Die);
119 Buffer.Detach();
120 }
121
122 return Die;
123 }
124};
125
126//===----------------------------------------------------------------------===//
127/// DbgVariable - This class is used to track local variable information.
128///
129class VISIBILITY_HIDDEN DbgVariable {
130 DIVariable Var; // Variable Descriptor.
131 unsigned FrameIndex; // Variable frame index.
Bill Wendling1180c782009-05-18 23:08:55 +0000132 bool InlinedFnVar; // Variable for an inlined function.
Bill Wendling0310d762009-05-15 09:23:25 +0000133public:
Bill Wendling1180c782009-05-18 23:08:55 +0000134 DbgVariable(DIVariable V, unsigned I, bool IFV)
135 : Var(V), FrameIndex(I), InlinedFnVar(IFV) {}
Bill Wendling0310d762009-05-15 09:23:25 +0000136
137 // Accessors.
Bill Wendling1180c782009-05-18 23:08:55 +0000138 DIVariable getVariable() const { return Var; }
Bill Wendling0310d762009-05-15 09:23:25 +0000139 unsigned getFrameIndex() const { return FrameIndex; }
Bill Wendling1180c782009-05-18 23:08:55 +0000140 bool isInlinedFnVar() const { return InlinedFnVar; }
Bill Wendling0310d762009-05-15 09:23:25 +0000141};
142
143//===----------------------------------------------------------------------===//
144/// DbgScope - This class is used to track scope information.
145///
146class DbgConcreteScope;
147class VISIBILITY_HIDDEN DbgScope {
148 DbgScope *Parent; // Parent to this scope.
149 DIDescriptor Desc; // Debug info descriptor for scope.
150 // Either subprogram or block.
151 unsigned StartLabelID; // Label ID of the beginning of scope.
152 unsigned EndLabelID; // Label ID of the end of scope.
153 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
154 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
155 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
156public:
157 DbgScope(DbgScope *P, DIDescriptor D)
158 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0) {}
159 virtual ~DbgScope();
160
161 // Accessors.
162 DbgScope *getParent() const { return Parent; }
163 DIDescriptor getDesc() const { return Desc; }
164 unsigned getStartLabelID() const { return StartLabelID; }
165 unsigned getEndLabelID() const { return EndLabelID; }
166 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
167 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
168 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
169 void setStartLabelID(unsigned S) { StartLabelID = S; }
170 void setEndLabelID(unsigned E) { EndLabelID = E; }
171
172 /// AddScope - Add a scope to the scope.
173 ///
174 void AddScope(DbgScope *S) { Scopes.push_back(S); }
175
176 /// AddVariable - Add a variable to the scope.
177 ///
178 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
179
180 /// AddConcreteInst - Add a concrete instance to the scope.
181 ///
182 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
183
184#ifndef NDEBUG
185 void dump() const;
186#endif
187};
188
189#ifndef NDEBUG
190void DbgScope::dump() const {
191 static unsigned IndentLevel = 0;
192 std::string Indent(IndentLevel, ' ');
193
194 cerr << Indent; Desc.dump();
195 cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
196
197 IndentLevel += 2;
198
199 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
200 if (Scopes[i] != this)
201 Scopes[i]->dump();
202
203 IndentLevel -= 2;
204}
205#endif
206
207//===----------------------------------------------------------------------===//
208/// DbgConcreteScope - This class is used to track a scope that holds concrete
209/// instance information.
210///
211class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
212 CompileUnit *Unit;
213 DIE *Die; // Debug info for this concrete scope.
214public:
215 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
216
217 // Accessors.
218 DIE *getDie() const { return Die; }
219 void setDie(DIE *D) { Die = D; }
220};
221
222DbgScope::~DbgScope() {
223 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
224 delete Scopes[i];
225 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
226 delete Variables[j];
227 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
228 delete ConcreteInsts[k];
229}
230
231} // end llvm namespace
232
233DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
234 : Dwarf(OS, A, T, "dbg"), MainCU(0),
235 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
236 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
237 SectionSourceLines(), didInitial(false), shouldEmit(false),
238 FunctionDbgScope(0), DebugTimer(0) {
239 if (TimePassesIsEnabled)
240 DebugTimer = new Timer("Dwarf Debug Writer",
241 getDwarfTimerGroup());
242}
243DwarfDebug::~DwarfDebug() {
244 for (unsigned j = 0, M = Values.size(); j < M; ++j)
245 delete Values[j];
246
247 for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
248 I = AbstractInstanceRootMap.begin(),
249 E = AbstractInstanceRootMap.end(); I != E;++I)
250 delete I->second;
251
252 delete DebugTimer;
253}
254
255/// AssignAbbrevNumber - Define a unique number for the abbreviation.
256///
257void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
258 // Profile the node so that we can make it unique.
259 FoldingSetNodeID ID;
260 Abbrev.Profile(ID);
261
262 // Check the set for priors.
263 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
264
265 // If it's newly added.
266 if (InSet == &Abbrev) {
267 // Add to abbreviation list.
268 Abbreviations.push_back(&Abbrev);
269
270 // Assign the vector position + 1 as its number.
271 Abbrev.setNumber(Abbreviations.size());
272 } else {
273 // Assign existing abbreviation number.
274 Abbrev.setNumber(InSet->getNumber());
275 }
276}
277
Bill Wendlingf0fb9872009-05-20 23:19:06 +0000278/// NewDIEEntry - Creates a new DIEEntry to be a proxy for a debug information
279/// entry.
280DIEEntry *DwarfDebug::NewDIEEntry(DIE *Entry) {
Bill Wendling0310d762009-05-15 09:23:25 +0000281 DIEEntry *Value;
282
283 if (Entry) {
284 FoldingSetNodeID ID;
285 DIEEntry::Profile(ID, Entry);
286 void *Where;
287 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
288
289 if (Value) return Value;
290
291 Value = new DIEEntry(Entry);
292 ValuesSet.InsertNode(Value, Where);
293 } else {
294 Value = new DIEEntry(Entry);
295 }
296
297 Values.push_back(Value);
298 return Value;
299}
300
301/// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
302///
303void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
304 Value->setEntry(Entry);
305
306 // Add to values set if not already there. If it is, we merely have a
307 // duplicate in the values list (no harm.)
308 ValuesSet.GetOrInsertNode(Value);
309}
310
311/// AddUInt - Add an unsigned integer attribute data and value.
312///
313void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
314 unsigned Form, uint64_t Integer) {
315 if (!Form) Form = DIEInteger::BestForm(false, Integer);
316
317 FoldingSetNodeID ID;
318 DIEInteger::Profile(ID, Integer);
319 void *Where;
320 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
321
322 if (!Value) {
323 Value = new DIEInteger(Integer);
324 ValuesSet.InsertNode(Value, Where);
325 Values.push_back(Value);
326 }
327
328 Die->AddValue(Attribute, Form, Value);
329}
330
331/// AddSInt - Add an signed integer attribute data and value.
332///
333void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
334 unsigned Form, int64_t Integer) {
335 if (!Form) Form = DIEInteger::BestForm(true, Integer);
336
337 FoldingSetNodeID ID;
338 DIEInteger::Profile(ID, (uint64_t)Integer);
339 void *Where;
340 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
341
342 if (!Value) {
343 Value = new DIEInteger(Integer);
344 ValuesSet.InsertNode(Value, Where);
345 Values.push_back(Value);
346 }
347
348 Die->AddValue(Attribute, Form, Value);
349}
350
351/// AddString - Add a string attribute data and value.
352///
353void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
354 const std::string &String) {
355 FoldingSetNodeID ID;
356 DIEString::Profile(ID, String);
357 void *Where;
358 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
359
360 if (!Value) {
361 Value = new DIEString(String);
362 ValuesSet.InsertNode(Value, Where);
363 Values.push_back(Value);
364 }
365
366 Die->AddValue(Attribute, Form, Value);
367}
368
369/// AddLabel - Add a Dwarf label attribute data and value.
370///
371void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
372 const DWLabel &Label) {
373 FoldingSetNodeID ID;
374 DIEDwarfLabel::Profile(ID, Label);
375 void *Where;
376 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
377
378 if (!Value) {
379 Value = new DIEDwarfLabel(Label);
380 ValuesSet.InsertNode(Value, Where);
381 Values.push_back(Value);
382 }
383
384 Die->AddValue(Attribute, Form, Value);
385}
386
387/// AddObjectLabel - Add an non-Dwarf label attribute data and value.
388///
389void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
390 const std::string &Label) {
391 FoldingSetNodeID ID;
392 DIEObjectLabel::Profile(ID, Label);
393 void *Where;
394 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
395
396 if (!Value) {
397 Value = new DIEObjectLabel(Label);
398 ValuesSet.InsertNode(Value, Where);
399 Values.push_back(Value);
400 }
401
402 Die->AddValue(Attribute, Form, Value);
403}
404
405/// AddSectionOffset - Add a section offset label attribute data and value.
406///
407void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
408 const DWLabel &Label, const DWLabel &Section,
409 bool isEH, bool useSet) {
410 FoldingSetNodeID ID;
411 DIESectionOffset::Profile(ID, Label, Section);
412 void *Where;
413 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
414
415 if (!Value) {
416 Value = new DIESectionOffset(Label, Section, isEH, useSet);
417 ValuesSet.InsertNode(Value, Where);
418 Values.push_back(Value);
419 }
420
421 Die->AddValue(Attribute, Form, Value);
422}
423
424/// AddDelta - Add a label delta attribute data and value.
425///
426void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
427 const DWLabel &Hi, const DWLabel &Lo) {
428 FoldingSetNodeID ID;
429 DIEDelta::Profile(ID, Hi, Lo);
430 void *Where;
431 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
432
433 if (!Value) {
434 Value = new DIEDelta(Hi, Lo);
435 ValuesSet.InsertNode(Value, Where);
436 Values.push_back(Value);
437 }
438
439 Die->AddValue(Attribute, Form, Value);
440}
441
442/// AddBlock - Add block data.
443///
444void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
445 DIEBlock *Block) {
446 Block->ComputeSize(TD);
447 FoldingSetNodeID ID;
448 Block->Profile(ID);
449 void *Where;
450 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
451
452 if (!Value) {
453 Value = Block;
454 ValuesSet.InsertNode(Value, Where);
455 Values.push_back(Value);
456 } else {
457 // Already exists, reuse the previous one.
458 delete Block;
459 Block = cast<DIEBlock>(Value);
460 }
461
462 Die->AddValue(Attribute, Block->BestForm(), Value);
463}
464
465/// AddSourceLine - Add location information to specified debug information
466/// entry.
467void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
468 // If there is no compile unit specified, don't add a line #.
469 if (V->getCompileUnit().isNull())
470 return;
471
472 unsigned Line = V->getLineNumber();
473 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
474 assert(FileID && "Invalid file id");
475 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
476 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
477}
478
479/// AddSourceLine - Add location information to specified debug information
480/// entry.
481void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
482 // If there is no compile unit specified, don't add a line #.
483 if (G->getCompileUnit().isNull())
484 return;
485
486 unsigned Line = G->getLineNumber();
487 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
488 assert(FileID && "Invalid file id");
489 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
490 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
491}
492void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
493 // If there is no compile unit specified, don't add a line #.
494 DICompileUnit CU = Ty->getCompileUnit();
495 if (CU.isNull())
496 return;
497
498 unsigned Line = Ty->getLineNumber();
499 unsigned FileID = FindCompileUnit(CU).getID();
500 assert(FileID && "Invalid file id");
501 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
502 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
503}
504
505/// AddAddress - Add an address attribute to a die based on the location
506/// provided.
507void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
508 const MachineLocation &Location) {
509 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
510 DIEBlock *Block = new DIEBlock();
511
512 if (Location.isReg()) {
513 if (Reg < 32) {
514 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
515 } else {
516 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
517 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
518 }
519 } else {
520 if (Reg < 32) {
521 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
522 } else {
523 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
524 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
525 }
526
527 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
528 }
529
530 AddBlock(Die, Attribute, 0, Block);
531}
532
533/// AddType - Add a new type attribute to the specified entity.
534void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
535 if (Ty.isNull())
536 return;
537
538 // Check for pre-existence.
539 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
540
541 // If it exists then use the existing value.
542 if (Slot) {
543 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
544 return;
545 }
546
547 // Set up proxy.
Bill Wendlingf0fb9872009-05-20 23:19:06 +0000548 Slot = NewDIEEntry();
Bill Wendling0310d762009-05-15 09:23:25 +0000549
550 // Construct type.
551 DIE Buffer(dwarf::DW_TAG_base_type);
552 if (Ty.isBasicType(Ty.getTag()))
553 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
554 else if (Ty.isDerivedType(Ty.getTag()))
555 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
556 else {
557 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
558 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
559 }
560
561 // Add debug information entry to entity and appropriate context.
562 DIE *Die = NULL;
563 DIDescriptor Context = Ty.getContext();
564 if (!Context.isNull())
565 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
566
567 if (Die) {
568 DIE *Child = new DIE(Buffer);
569 Die->AddChild(Child);
570 Buffer.Detach();
571 SetDIEEntry(Slot, Child);
572 } else {
573 Die = DW_Unit->AddDie(Buffer);
574 SetDIEEntry(Slot, Die);
575 }
576
577 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
578}
579
580/// ConstructTypeDIE - Construct basic type die from DIBasicType.
581void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
582 DIBasicType BTy) {
583 // Get core information.
584 std::string Name;
585 BTy.getName(Name);
586 Buffer.setTag(dwarf::DW_TAG_base_type);
587 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
588 BTy.getEncoding());
589
590 // Add name if not anonymous or intermediate type.
591 if (!Name.empty())
592 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
593 uint64_t Size = BTy.getSizeInBits() >> 3;
594 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
595}
596
597/// ConstructTypeDIE - Construct derived type die from DIDerivedType.
598void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
599 DIDerivedType DTy) {
600 // Get core information.
601 std::string Name;
602 DTy.getName(Name);
603 uint64_t Size = DTy.getSizeInBits() >> 3;
604 unsigned Tag = DTy.getTag();
605
606 // FIXME - Workaround for templates.
607 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
608
609 Buffer.setTag(Tag);
610
611 // Map to main type, void will not have a type.
612 DIType FromTy = DTy.getTypeDerivedFrom();
613 AddType(DW_Unit, &Buffer, FromTy);
614
615 // Add name if not anonymous or intermediate type.
616 if (!Name.empty())
617 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
618
619 // Add size if non-zero (derived types might be zero-sized.)
620 if (Size)
621 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
622
623 // Add source line info if available and TyDesc is not a forward declaration.
624 if (!DTy.isForwardDecl())
625 AddSourceLine(&Buffer, &DTy);
626}
627
628/// ConstructTypeDIE - Construct type DIE from DICompositeType.
629void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
630 DICompositeType CTy) {
631 // Get core information.
632 std::string Name;
633 CTy.getName(Name);
634
635 uint64_t Size = CTy.getSizeInBits() >> 3;
636 unsigned Tag = CTy.getTag();
637 Buffer.setTag(Tag);
638
639 switch (Tag) {
640 case dwarf::DW_TAG_vector_type:
641 case dwarf::DW_TAG_array_type:
642 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
643 break;
644 case dwarf::DW_TAG_enumeration_type: {
645 DIArray Elements = CTy.getTypeArray();
646
647 // Add enumerators to enumeration type.
648 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
649 DIE *ElemDie = NULL;
650 DIEnumerator Enum(Elements.getElement(i).getGV());
651 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
652 Buffer.AddChild(ElemDie);
653 }
654 }
655 break;
656 case dwarf::DW_TAG_subroutine_type: {
657 // Add return type.
658 DIArray Elements = CTy.getTypeArray();
659 DIDescriptor RTy = Elements.getElement(0);
660 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
661
662 // Add prototype flag.
663 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
664
665 // Add arguments.
666 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
667 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
668 DIDescriptor Ty = Elements.getElement(i);
669 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
670 Buffer.AddChild(Arg);
671 }
672 }
673 break;
674 case dwarf::DW_TAG_structure_type:
675 case dwarf::DW_TAG_union_type:
676 case dwarf::DW_TAG_class_type: {
677 // Add elements to structure type.
678 DIArray Elements = CTy.getTypeArray();
679
680 // A forward struct declared type may not have elements available.
681 if (Elements.isNull())
682 break;
683
684 // Add elements to structure type.
685 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
686 DIDescriptor Element = Elements.getElement(i);
687 DIE *ElemDie = NULL;
688 if (Element.getTag() == dwarf::DW_TAG_subprogram)
689 ElemDie = CreateSubprogramDIE(DW_Unit,
690 DISubprogram(Element.getGV()));
691 else if (Element.getTag() == dwarf::DW_TAG_variable) // ??
692 ElemDie = CreateGlobalVariableDIE(DW_Unit,
693 DIGlobalVariable(Element.getGV()));
694 else
695 ElemDie = CreateMemberDIE(DW_Unit,
696 DIDerivedType(Element.getGV()));
697 Buffer.AddChild(ElemDie);
698 }
699
700 // FIXME: We'd like an API to register additional attributes for the
701 // frontend to use while synthesizing, and then we'd use that api in clang
702 // instead of this.
703 if (Name == "__block_literal_generic")
704 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
705
706 unsigned RLang = CTy.getRunTimeLang();
707 if (RLang)
708 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
709 dwarf::DW_FORM_data1, RLang);
710 break;
711 }
712 default:
713 break;
714 }
715
716 // Add name if not anonymous or intermediate type.
717 if (!Name.empty())
718 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
719
720 if (Tag == dwarf::DW_TAG_enumeration_type ||
721 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
722 // Add size if non-zero (derived types might be zero-sized.)
723 if (Size)
724 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
725 else {
726 // Add zero size if it is not a forward declaration.
727 if (CTy.isForwardDecl())
728 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
729 else
730 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
731 }
732
733 // Add source line info if available.
734 if (!CTy.isForwardDecl())
735 AddSourceLine(&Buffer, &CTy);
736 }
737}
738
739/// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
740void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
741 int64_t L = SR.getLo();
742 int64_t H = SR.getHi();
743 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
744
745 if (L != H) {
746 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
747 if (L)
748 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
749 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
750 }
751
752 Buffer.AddChild(DW_Subrange);
753}
754
755/// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
756void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
757 DICompositeType *CTy) {
758 Buffer.setTag(dwarf::DW_TAG_array_type);
759 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
760 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
761
762 // Emit derived type.
763 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
764 DIArray Elements = CTy->getTypeArray();
765
766 // Construct an anonymous type for index type.
767 DIE IdxBuffer(dwarf::DW_TAG_base_type);
768 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
769 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
770 dwarf::DW_ATE_signed);
771 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
772
773 // Add subranges to array type.
774 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
775 DIDescriptor Element = Elements.getElement(i);
776 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
777 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
778 }
779}
780
781/// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
782DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
783 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
784 std::string Name;
785 ETy->getName(Name);
786 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
787 int64_t Value = ETy->getEnumValue();
788 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
789 return Enumerator;
790}
791
792/// CreateGlobalVariableDIE - Create new DIE using GV.
793DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
794 const DIGlobalVariable &GV) {
795 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
796 std::string Name;
797 GV.getDisplayName(Name);
798 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
799 std::string LinkageName;
800 GV.getLinkageName(LinkageName);
801 if (!LinkageName.empty())
802 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
803 LinkageName);
804 AddType(DW_Unit, GVDie, GV.getType());
805 if (!GV.isLocalToUnit())
806 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
807 AddSourceLine(GVDie, &GV);
808 return GVDie;
809}
810
811/// CreateMemberDIE - Create new member DIE.
812DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
813 DIE *MemberDie = new DIE(DT.getTag());
814 std::string Name;
815 DT.getName(Name);
816 if (!Name.empty())
817 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
818
819 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
820
821 AddSourceLine(MemberDie, &DT);
822
823 uint64_t Size = DT.getSizeInBits();
824 uint64_t FieldSize = DT.getOriginalTypeSize();
825
826 if (Size != FieldSize) {
827 // Handle bitfield.
828 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
829 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
830
831 uint64_t Offset = DT.getOffsetInBits();
832 uint64_t FieldOffset = Offset;
833 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
834 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
835 FieldOffset = (HiMark - FieldSize);
836 Offset -= FieldOffset;
837
838 // Maybe we need to work from the other end.
839 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
840 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
841 }
842
843 DIEBlock *Block = new DIEBlock();
844 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
845 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
846 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
847
848 if (DT.isProtected())
849 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
850 dwarf::DW_ACCESS_protected);
851 else if (DT.isPrivate())
852 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
853 dwarf::DW_ACCESS_private);
854
855 return MemberDie;
856}
857
858/// CreateSubprogramDIE - Create new DIE using SP.
859DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
860 const DISubprogram &SP,
Bill Wendling6679ee42009-05-18 22:02:36 +0000861 bool IsConstructor,
862 bool IsInlined) {
Bill Wendling0310d762009-05-15 09:23:25 +0000863 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
864
865 std::string Name;
866 SP.getName(Name);
867 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
868
869 std::string LinkageName;
870 SP.getLinkageName(LinkageName);
871
872 if (!LinkageName.empty())
873 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
874 LinkageName);
875
876 AddSourceLine(SPDie, &SP);
877
878 DICompositeType SPTy = SP.getType();
879 DIArray Args = SPTy.getTypeArray();
880
881 // Add prototyped tag, if C or ObjC.
882 unsigned Lang = SP.getCompileUnit().getLanguage();
883 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
884 Lang == dwarf::DW_LANG_ObjC)
885 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
886
887 // Add Return Type.
888 unsigned SPTag = SPTy.getTag();
889 if (!IsConstructor) {
890 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
891 AddType(DW_Unit, SPDie, SPTy);
892 else
893 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
894 }
895
896 if (!SP.isDefinition()) {
897 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
898
899 // Add arguments. Do not add arguments for subprogram definition. They will
900 // be handled through RecordVariable.
901 if (SPTag == dwarf::DW_TAG_subroutine_type)
902 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
903 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
904 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
905 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
906 SPDie->AddChild(Arg);
907 }
908 }
909
Bill Wendling6679ee42009-05-18 22:02:36 +0000910 if (!SP.isLocalToUnit() && !IsInlined)
Bill Wendling0310d762009-05-15 09:23:25 +0000911 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
912
913 // DW_TAG_inlined_subroutine may refer to this DIE.
914 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
915 Slot = SPDie;
916 return SPDie;
917}
918
919/// FindCompileUnit - Get the compile unit for the given descriptor.
920///
921CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
922 DenseMap<Value *, CompileUnit *>::const_iterator I =
923 CompileUnitMap.find(Unit.getGV());
924 assert(I != CompileUnitMap.end() && "Missing compile unit.");
925 return *I->second;
926}
927
Bill Wendlingf0fb9872009-05-20 23:19:06 +0000928/// NewDbgScopeVariable - Create a new scope variable.
Bill Wendling0310d762009-05-15 09:23:25 +0000929///
Bill Wendlingf0fb9872009-05-20 23:19:06 +0000930DIE *DwarfDebug::NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
Bill Wendling0310d762009-05-15 09:23:25 +0000931 // Get the descriptor.
932 const DIVariable &VD = DV->getVariable();
933
934 // Translate tag to proper Dwarf tag. The result variable is dropped for
935 // now.
936 unsigned Tag;
937 switch (VD.getTag()) {
938 case dwarf::DW_TAG_return_variable:
939 return NULL;
940 case dwarf::DW_TAG_arg_variable:
941 Tag = dwarf::DW_TAG_formal_parameter;
942 break;
943 case dwarf::DW_TAG_auto_variable: // fall thru
944 default:
945 Tag = dwarf::DW_TAG_variable;
946 break;
947 }
948
949 // Define variable debug information entry.
950 DIE *VariableDie = new DIE(Tag);
951 std::string Name;
952 VD.getName(Name);
953 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
954
955 // Add source line info if available.
956 AddSourceLine(VariableDie, &VD);
957
958 // Add variable type.
959 AddType(Unit, VariableDie, VD.getType());
960
961 // Add variable address.
Bill Wendling1180c782009-05-18 23:08:55 +0000962 if (!DV->isInlinedFnVar()) {
963 // Variables for abstract instances of inlined functions don't get a
964 // location.
965 MachineLocation Location;
966 Location.set(RI->getFrameRegister(*MF),
967 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
968 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
969 }
Bill Wendling0310d762009-05-15 09:23:25 +0000970
971 return VariableDie;
972}
973
974/// getOrCreateScope - Returns the scope associated with the given descriptor.
975///
976DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
977 DbgScope *&Slot = DbgScopeMap[V];
978 if (Slot) return Slot;
979
980 DbgScope *Parent = NULL;
981 DIBlock Block(V);
982
983 // Don't create a new scope if we already created one for an inlined function.
984 DenseMap<const GlobalVariable *, DbgScope *>::iterator
985 II = AbstractInstanceRootMap.find(V);
986 if (II != AbstractInstanceRootMap.end())
987 return LexicalScopeStack.back();
988
989 if (!Block.isNull()) {
990 DIDescriptor ParentDesc = Block.getContext();
991 Parent =
992 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
993 }
994
995 Slot = new DbgScope(Parent, DIDescriptor(V));
996
997 if (Parent)
998 Parent->AddScope(Slot);
999 else
1000 // First function is top level function.
1001 FunctionDbgScope = Slot;
1002
1003 return Slot;
1004}
1005
1006/// ConstructDbgScope - Construct the components of a scope.
1007///
1008void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1009 unsigned ParentStartID,
1010 unsigned ParentEndID,
1011 DIE *ParentDie, CompileUnit *Unit) {
1012 // Add variables to scope.
1013 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1014 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001015 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
Bill Wendling0310d762009-05-15 09:23:25 +00001016 if (VariableDie) ParentDie->AddChild(VariableDie);
1017 }
1018
1019 // Add concrete instances to scope.
1020 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1021 ParentScope->getConcreteInsts();
1022 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1023 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1024 DIE *Die = ConcreteInst->getDie();
1025
1026 unsigned StartID = ConcreteInst->getStartLabelID();
1027 unsigned EndID = ConcreteInst->getEndLabelID();
1028
1029 // Add the scope bounds.
1030 if (StartID)
1031 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1032 DWLabel("label", StartID));
1033 else
1034 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1035 DWLabel("func_begin", SubprogramCount));
1036
1037 if (EndID)
1038 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1039 DWLabel("label", EndID));
1040 else
1041 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1042 DWLabel("func_end", SubprogramCount));
1043
1044 ParentDie->AddChild(Die);
1045 }
1046
1047 // Add nested scopes.
1048 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1049 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1050 // Define the Scope debug information entry.
1051 DbgScope *Scope = Scopes[j];
1052
1053 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1054 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1055
1056 // Ignore empty scopes.
1057 if (StartID == EndID && StartID != 0) continue;
1058
1059 // Do not ignore inlined scopes even if they don't have any variables or
1060 // scopes.
1061 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1062 Scope->getConcreteInsts().empty())
1063 continue;
1064
1065 if (StartID == ParentStartID && EndID == ParentEndID) {
1066 // Just add stuff to the parent scope.
1067 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1068 } else {
1069 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1070
1071 // Add the scope bounds.
1072 if (StartID)
1073 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1074 DWLabel("label", StartID));
1075 else
1076 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1077 DWLabel("func_begin", SubprogramCount));
1078
1079 if (EndID)
1080 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1081 DWLabel("label", EndID));
1082 else
1083 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1084 DWLabel("func_end", SubprogramCount));
1085
1086 // Add the scope's contents.
1087 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1088 ParentDie->AddChild(ScopeDie);
1089 }
1090 }
1091}
1092
1093/// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1094///
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001095void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope) {
Bill Wendling0310d762009-05-15 09:23:25 +00001096 // Exit if there is no root scope.
1097 if (!RootScope) return;
1098 DIDescriptor Desc = RootScope->getDesc();
1099 if (Desc.isNull())
1100 return;
1101
1102 // Get the subprogram debug information entry.
1103 DISubprogram SPD(Desc.getGV());
1104
1105 // Get the compile unit context.
1106 CompileUnit *Unit = MainCU;
1107 if (!Unit)
1108 Unit = &FindCompileUnit(SPD.getCompileUnit());
1109
1110 // Get the subprogram die.
1111 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1112 assert(SPDie && "Missing subprogram descriptor");
1113
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001114 // Add the function bounds.
1115 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1116 DWLabel("func_begin", SubprogramCount));
1117 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1118 DWLabel("func_end", SubprogramCount));
1119 MachineLocation Location(RI->getFrameRegister(*MF));
1120 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
Bill Wendling0310d762009-05-15 09:23:25 +00001121
1122 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
1123}
1124
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001125/// ConstructFunctionDbgScope - Construct the scope for the abstract debug
1126/// scope.
1127///
1128void DwarfDebug::ConstructAbstractDbgScope(DbgScope *AbsScope) {
1129 // Exit if there is no root scope.
1130 if (!AbsScope) return;
1131
1132 DIDescriptor Desc = AbsScope->getDesc();
1133 if (Desc.isNull())
1134 return;
1135
1136 // Get the subprogram debug information entry.
1137 DISubprogram SPD(Desc.getGV());
1138
1139 // Get the compile unit context.
1140 CompileUnit *Unit = MainCU;
1141 if (!Unit)
1142 Unit = &FindCompileUnit(SPD.getCompileUnit());
1143
1144 // Get the subprogram die.
1145 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1146 assert(SPDie && "Missing subprogram descriptor");
1147
1148 ConstructDbgScope(AbsScope, 0, 0, SPDie, Unit);
1149}
1150
Bill Wendling0310d762009-05-15 09:23:25 +00001151/// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1152///
1153void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1154 const char *FnName = MF->getFunction()->getNameStart();
1155 if (MainCU) {
1156 StringMap<DIE*> &Globals = MainCU->getGlobals();
1157 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1158 if (GI != Globals.end()) {
1159 DIE *SPDie = GI->second;
1160
1161 // Add the function bounds.
1162 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1163 DWLabel("func_begin", SubprogramCount));
1164 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1165 DWLabel("func_end", SubprogramCount));
1166
1167 MachineLocation Location(RI->getFrameRegister(*MF));
1168 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1169 return;
1170 }
1171 } else {
1172 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1173 CompileUnit *Unit = CompileUnits[i];
1174 StringMap<DIE*> &Globals = Unit->getGlobals();
1175 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1176 if (GI != Globals.end()) {
1177 DIE *SPDie = GI->second;
1178
1179 // Add the function bounds.
1180 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1181 DWLabel("func_begin", SubprogramCount));
1182 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1183 DWLabel("func_end", SubprogramCount));
1184
1185 MachineLocation Location(RI->getFrameRegister(*MF));
1186 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1187 return;
1188 }
1189 }
1190 }
1191
1192#if 0
1193 // FIXME: This is causing an abort because C++ mangled names are compared with
1194 // their unmangled counterparts. See PR2885. Don't do this assert.
1195 assert(0 && "Couldn't find DIE for machine function!");
1196#endif
1197}
1198
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001199/// GetOrCreateSourceID - Look up the source id with the given directory and
1200/// source file names. If none currently exists, create a new id and insert it
1201/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1202/// maps as well.
1203unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1204 const std::string &FileName) {
1205 unsigned DId;
1206 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1207 if (DI != DirectoryIdMap.end()) {
1208 DId = DI->getValue();
1209 } else {
1210 DId = DirectoryNames.size() + 1;
1211 DirectoryIdMap[DirName] = DId;
1212 DirectoryNames.push_back(DirName);
1213 }
1214
1215 unsigned FId;
1216 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1217 if (FI != SourceFileIdMap.end()) {
1218 FId = FI->getValue();
1219 } else {
1220 FId = SourceFileNames.size() + 1;
1221 SourceFileIdMap[FileName] = FId;
1222 SourceFileNames.push_back(FileName);
1223 }
1224
1225 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1226 SourceIdMap.find(std::make_pair(DId, FId));
1227 if (SI != SourceIdMap.end())
1228 return SI->second;
1229
1230 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1231 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1232 SourceIds.push_back(std::make_pair(DId, FId));
1233
1234 return SrcId;
1235}
1236
1237void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1238 DICompileUnit DIUnit(GV);
1239 std::string Dir, FN, Prod;
1240 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1241 DIUnit.getFilename(FN));
1242
1243 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1244 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1245 DWLabel("section_line", 0), DWLabel("section_line", 0),
1246 false);
1247 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1248 DIUnit.getProducer(Prod));
1249 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1250 DIUnit.getLanguage());
1251 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1252
1253 if (!Dir.empty())
1254 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1255 if (DIUnit.isOptimized())
1256 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1257
1258 std::string Flags;
1259 DIUnit.getFlags(Flags);
1260 if (!Flags.empty())
1261 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1262
1263 unsigned RVer = DIUnit.getRunTimeVersion();
1264 if (RVer)
1265 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1266 dwarf::DW_FORM_data1, RVer);
1267
1268 CompileUnit *Unit = new CompileUnit(ID, Die);
1269 if (DIUnit.isMain()) {
1270 assert(!MainCU && "Multiple main compile units are found!");
1271 MainCU = Unit;
1272 }
1273
1274 CompileUnitMap[DIUnit.getGV()] = Unit;
1275 CompileUnits.push_back(Unit);
1276}
1277
1278/// ConstructCompileUnits - Create a compile unit DIEs.
1279void DwarfDebug::ConstructCompileUnits() {
1280 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
1281 if (!Root)
1282 return;
1283 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1284 "Malformed compile unit descriptor anchor type");
1285 Constant *RootC = cast<Constant>(*Root->use_begin());
1286 assert(RootC->hasNUsesOrMore(1) &&
1287 "Malformed compile unit descriptor anchor type");
1288
1289 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
1290 UI != UE; ++UI)
1291 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
1292 UUI != UUE; ++UUI) {
1293 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
1294 ConstructCompileUnit(GV);
1295 }
1296}
1297
1298bool DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
1299 DIGlobalVariable DI_GV(GV);
1300 CompileUnit *DW_Unit = MainCU;
1301 if (!DW_Unit)
1302 DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
1303
1304 // Check for pre-existence.
1305 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
1306 if (Slot)
1307 return false;
1308
1309 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
1310
1311 // Add address.
1312 DIEBlock *Block = new DIEBlock();
1313 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1314 std::string GLN;
1315 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1316 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
1317 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1318
1319 // Add to map.
1320 Slot = VariableDie;
1321
1322 // Add to context owner.
1323 DW_Unit->getDie()->AddChild(VariableDie);
1324
1325 // Expose as global. FIXME - need to check external flag.
1326 std::string Name;
1327 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
1328 return true;
1329}
1330
1331/// ConstructGlobalVariableDIEs - Create DIEs for each of the externally visible
1332/// global variables. Return true if at least one global DIE is created.
1333bool DwarfDebug::ConstructGlobalVariableDIEs() {
1334 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
1335 if (!Root)
1336 return false;
1337
1338 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1339 "Malformed global variable descriptor anchor type");
1340 Constant *RootC = cast<Constant>(*Root->use_begin());
1341 assert(RootC->hasNUsesOrMore(1) &&
1342 "Malformed global variable descriptor anchor type");
1343
1344 bool Result = false;
1345 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
1346 UI != UE; ++UI)
1347 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
1348 UUI != UUE; ++UUI)
1349 Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
1350
1351 return Result;
1352}
1353
1354bool DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
1355 DISubprogram SP(GV);
1356 CompileUnit *Unit = MainCU;
1357 if (!Unit)
1358 Unit = &FindCompileUnit(SP.getCompileUnit());
1359
1360 // Check for pre-existence.
1361 DIE *&Slot = Unit->getDieMapSlotFor(GV);
1362 if (Slot)
1363 return false;
1364
1365 if (!SP.isDefinition())
1366 // This is a method declaration which will be handled while constructing
1367 // class type.
1368 return false;
1369
1370 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
1371
1372 // Add to map.
1373 Slot = SubprogramDie;
1374
1375 // Add to context owner.
1376 Unit->getDie()->AddChild(SubprogramDie);
1377
1378 // Expose as global.
1379 std::string Name;
1380 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
1381 return true;
1382}
1383
1384/// ConstructSubprograms - Create DIEs for each of the externally visible
1385/// subprograms. Return true if at least one subprogram DIE is created.
1386bool DwarfDebug::ConstructSubprograms() {
1387 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
1388 if (!Root)
1389 return false;
1390
1391 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1392 "Malformed subprogram descriptor anchor type");
1393 Constant *RootC = cast<Constant>(*Root->use_begin());
1394 assert(RootC->hasNUsesOrMore(1) &&
1395 "Malformed subprogram descriptor anchor type");
1396
1397 bool Result = false;
1398 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
1399 UI != UE; ++UI)
1400 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
1401 UUI != UUE; ++UUI)
1402 Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
1403
1404 return Result;
1405}
1406
1407/// SetDebugInfo - Create global DIEs and emit initial debug info sections.
1408/// This is inovked by the target AsmPrinter.
1409void DwarfDebug::SetDebugInfo(MachineModuleInfo *mmi) {
1410 if (TimePassesIsEnabled)
1411 DebugTimer->startTimer();
1412
1413 // Create all the compile unit DIEs.
1414 ConstructCompileUnits();
1415
1416 if (CompileUnits.empty()) {
1417 if (TimePassesIsEnabled)
1418 DebugTimer->stopTimer();
1419
1420 return;
1421 }
1422
1423 // Create DIEs for each of the externally visible global variables.
1424 bool globalDIEs = ConstructGlobalVariableDIEs();
1425
1426 // Create DIEs for each of the externally visible subprograms.
1427 bool subprogramDIEs = ConstructSubprograms();
1428
1429 // If there is not any debug info available for any global variables and any
1430 // subprograms then there is not any debug info to emit.
1431 if (!globalDIEs && !subprogramDIEs) {
1432 if (TimePassesIsEnabled)
1433 DebugTimer->stopTimer();
1434
1435 return;
1436 }
1437
1438 MMI = mmi;
1439 shouldEmit = true;
1440 MMI->setDebugInfoAvailability(true);
1441
1442 // Prime section data.
1443 SectionMap.insert(TAI->getTextSection());
1444
1445 // Print out .file directives to specify files for .loc directives. These are
1446 // printed out early so that they precede any .loc directives.
1447 if (TAI->hasDotLocAndDotFile()) {
1448 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1449 // Remember source id starts at 1.
1450 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1451 sys::Path FullPath(getSourceDirectoryName(Id.first));
1452 bool AppendOk =
1453 FullPath.appendComponent(getSourceFileName(Id.second));
1454 assert(AppendOk && "Could not append filename to directory!");
1455 AppendOk = false;
1456 Asm->EmitFile(i, FullPath.toString());
1457 Asm->EOL();
1458 }
1459 }
1460
1461 // Emit initial sections
1462 EmitInitial();
1463
1464 if (TimePassesIsEnabled)
1465 DebugTimer->stopTimer();
1466}
1467
1468/// EndModule - Emit all Dwarf sections that should come after the content.
1469///
1470void DwarfDebug::EndModule() {
1471 if (!ShouldEmitDwarfDebug())
1472 return;
1473
1474 if (TimePassesIsEnabled)
1475 DebugTimer->startTimer();
1476
1477 // Standard sections final addresses.
1478 Asm->SwitchToSection(TAI->getTextSection());
1479 EmitLabel("text_end", 0);
1480 Asm->SwitchToSection(TAI->getDataSection());
1481 EmitLabel("data_end", 0);
1482
1483 // End text sections.
1484 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1485 Asm->SwitchToSection(SectionMap[i]);
1486 EmitLabel("section_end", i);
1487 }
1488
1489 // Emit common frame information.
1490 EmitCommonDebugFrame();
1491
1492 // Emit function debug frame information
1493 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1494 E = DebugFrames.end(); I != E; ++I)
1495 EmitFunctionDebugFrame(*I);
1496
1497 // Compute DIE offsets and sizes.
1498 SizeAndOffsets();
1499
1500 // Emit all the DIEs into a debug info section
1501 EmitDebugInfo();
1502
1503 // Corresponding abbreviations into a abbrev section.
1504 EmitAbbreviations();
1505
1506 // Emit source line correspondence into a debug line section.
1507 EmitDebugLines();
1508
1509 // Emit info into a debug pubnames section.
1510 EmitDebugPubNames();
1511
1512 // Emit info into a debug str section.
1513 EmitDebugStr();
1514
1515 // Emit info into a debug loc section.
1516 EmitDebugLoc();
1517
1518 // Emit info into a debug aranges section.
1519 EmitDebugARanges();
1520
1521 // Emit info into a debug ranges section.
1522 EmitDebugRanges();
1523
1524 // Emit info into a debug macinfo section.
1525 EmitDebugMacInfo();
1526
1527 // Emit inline info.
1528 EmitDebugInlineInfo();
1529
1530 if (TimePassesIsEnabled)
1531 DebugTimer->stopTimer();
1532}
1533
1534/// BeginFunction - Gather pre-function debug information. Assumes being
1535/// emitted immediately after the function entry point.
1536void DwarfDebug::BeginFunction(MachineFunction *MF) {
1537 this->MF = MF;
1538
1539 if (!ShouldEmitDwarfDebug()) return;
1540
1541 if (TimePassesIsEnabled)
1542 DebugTimer->startTimer();
1543
1544 // Begin accumulating function debug information.
1545 MMI->BeginFunction(MF);
1546
1547 // Assumes in correct section after the entry point.
1548 EmitLabel("func_begin", ++SubprogramCount);
1549
1550 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1551 // function.
1552 DebugLoc FDL = MF->getDefaultDebugLoc();
1553 if (!FDL.isUnknown()) {
1554 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1555 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
1556 DICompileUnit(DLT.CompileUnit));
1557 Asm->printLabel(LabelID);
1558 }
1559
1560 if (TimePassesIsEnabled)
1561 DebugTimer->stopTimer();
1562}
1563
1564/// EndFunction - Gather and emit post-function debug information.
1565///
1566void DwarfDebug::EndFunction(MachineFunction *MF) {
1567 if (!ShouldEmitDwarfDebug()) return;
1568
1569 if (TimePassesIsEnabled)
1570 DebugTimer->startTimer();
1571
1572 // Define end label for subprogram.
1573 EmitLabel("func_end", SubprogramCount);
1574
1575 // Get function line info.
1576 if (!Lines.empty()) {
1577 // Get section line info.
1578 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
1579 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
1580 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
1581 // Append the function info to section info.
1582 SectionLineInfos.insert(SectionLineInfos.end(),
1583 Lines.begin(), Lines.end());
1584 }
1585
1586 // Construct the DbgScope for abstract instances.
1587 for (SmallVector<DbgScope *, 32>::iterator
1588 I = AbstractInstanceRootList.begin(),
1589 E = AbstractInstanceRootList.end(); I != E; ++I)
1590 ConstructAbstractDbgScope(*I);
1591
1592 // Construct scopes for subprogram.
1593 if (FunctionDbgScope)
1594 ConstructFunctionDbgScope(FunctionDbgScope);
1595 else
1596 // FIXME: This is wrong. We are essentially getting past a problem with
1597 // debug information not being able to handle unreachable blocks that have
1598 // debug information in them. In particular, those unreachable blocks that
1599 // have "region end" info in them. That situation results in the "root
1600 // scope" not being created. If that's the case, then emit a "default"
1601 // scope, i.e., one that encompasses the whole function. This isn't
1602 // desirable. And a better way of handling this (and all of the debugging
1603 // information) needs to be explored.
1604 ConstructDefaultDbgScope(MF);
1605
1606 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
1607 MMI->getFrameMoves()));
1608
1609 // Clear debug info
1610 if (FunctionDbgScope) {
1611 delete FunctionDbgScope;
1612 DbgScopeMap.clear();
1613 DbgAbstractScopeMap.clear();
1614 DbgConcreteScopeMap.clear();
1615 InlinedVariableScopes.clear();
1616 FunctionDbgScope = NULL;
1617 LexicalScopeStack.clear();
1618 AbstractInstanceRootList.clear();
1619 }
1620
1621 Lines.clear();
1622
1623 if (TimePassesIsEnabled)
1624 DebugTimer->stopTimer();
1625}
1626
1627/// RecordSourceLine - Records location information and associates it with a
1628/// label. Returns a unique label ID used to generate a label and provide
1629/// correspondence to the source line list.
1630unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
1631 if (TimePassesIsEnabled)
1632 DebugTimer->startTimer();
1633
1634 CompileUnit *Unit = CompileUnitMap[V];
1635 assert(Unit && "Unable to find CompileUnit");
1636 unsigned ID = MMI->NextLabelID();
1637 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
1638
1639 if (TimePassesIsEnabled)
1640 DebugTimer->stopTimer();
1641
1642 return ID;
1643}
1644
1645/// RecordSourceLine - Records location information and associates it with a
1646/// label. Returns a unique label ID used to generate a label and provide
1647/// correspondence to the source line list.
1648unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
1649 DICompileUnit CU) {
1650 if (TimePassesIsEnabled)
1651 DebugTimer->startTimer();
1652
1653 std::string Dir, Fn;
1654 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
1655 CU.getFilename(Fn));
1656 unsigned ID = MMI->NextLabelID();
1657 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
1658
1659 if (TimePassesIsEnabled)
1660 DebugTimer->stopTimer();
1661
1662 return ID;
1663}
1664
1665/// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
1666/// timed. Look up the source id with the given directory and source file
1667/// names. If none currently exists, create a new id and insert it in the
1668/// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
1669/// well.
1670unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
1671 const std::string &FileName) {
1672 if (TimePassesIsEnabled)
1673 DebugTimer->startTimer();
1674
1675 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
1676
1677 if (TimePassesIsEnabled)
1678 DebugTimer->stopTimer();
1679
1680 return SrcId;
1681}
1682
1683/// RecordRegionStart - Indicate the start of a region.
1684unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
1685 if (TimePassesIsEnabled)
1686 DebugTimer->startTimer();
1687
1688 DbgScope *Scope = getOrCreateScope(V);
1689 unsigned ID = MMI->NextLabelID();
1690 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1691 LexicalScopeStack.push_back(Scope);
1692
1693 if (TimePassesIsEnabled)
1694 DebugTimer->stopTimer();
1695
1696 return ID;
1697}
1698
1699/// RecordRegionEnd - Indicate the end of a region.
1700unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
1701 if (TimePassesIsEnabled)
1702 DebugTimer->startTimer();
1703
1704 DbgScope *Scope = getOrCreateScope(V);
1705 unsigned ID = MMI->NextLabelID();
1706 Scope->setEndLabelID(ID);
1707 if (LexicalScopeStack.size() != 0)
1708 LexicalScopeStack.pop_back();
1709
1710 if (TimePassesIsEnabled)
1711 DebugTimer->stopTimer();
1712
1713 return ID;
1714}
1715
1716/// RecordVariable - Indicate the declaration of a local variable.
1717void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
1718 const MachineInstr *MI) {
1719 if (TimePassesIsEnabled)
1720 DebugTimer->startTimer();
1721
1722 DIDescriptor Desc(GV);
1723 DbgScope *Scope = NULL;
1724 bool InlinedFnVar = false;
1725
1726 if (Desc.getTag() == dwarf::DW_TAG_variable) {
1727 // GV is a global variable.
1728 DIGlobalVariable DG(GV);
1729 Scope = getOrCreateScope(DG.getContext().getGV());
1730 } else {
1731 DenseMap<const MachineInstr *, DbgScope *>::iterator
1732 SI = InlinedVariableScopes.find(MI);
1733
1734 if (SI != InlinedVariableScopes.end()) {
1735 // or GV is an inlined local variable.
1736 Scope = SI->second;
1737 } else {
1738 DIVariable DV(GV);
1739 GlobalVariable *V = DV.getContext().getGV();
1740
1741 // FIXME: The code that checks for the inlined local variable is a hack!
1742 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1743 AI = AbstractInstanceRootMap.find(V);
1744
1745 if (AI != AbstractInstanceRootMap.end()) {
1746 // This method is called each time a DECLARE node is encountered. For an
1747 // inlined function, this could be many, many times. We don't want to
1748 // re-add variables to that DIE for each time. We just want to add them
1749 // once. Check to make sure that we haven't added them already.
1750 DenseMap<const GlobalVariable *,
1751 SmallSet<const GlobalVariable *, 32> >::iterator
1752 IP = InlinedParamMap.find(V);
1753
1754 if (IP != InlinedParamMap.end() && IP->second.count(GV) > 0) {
1755 if (TimePassesIsEnabled)
1756 DebugTimer->stopTimer();
1757 return;
1758 }
1759
1760 // or GV is an inlined local variable.
1761 Scope = AI->second;
1762 InlinedParamMap[V].insert(GV);
1763 InlinedFnVar = true;
1764 } else {
1765 // or GV is a local variable.
1766 Scope = getOrCreateScope(V);
1767 }
1768 }
1769 }
1770
1771 assert(Scope && "Unable to find the variable's scope");
1772 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex, InlinedFnVar);
1773 Scope->AddVariable(DV);
1774
1775 if (TimePassesIsEnabled)
1776 DebugTimer->stopTimer();
1777}
1778
1779//// RecordInlinedFnStart - Indicate the start of inlined subroutine.
1780unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
1781 unsigned Line, unsigned Col) {
1782 unsigned LabelID = MMI->NextLabelID();
1783
1784 if (!TAI->doesDwarfUsesInlineInfoSection())
1785 return LabelID;
1786
1787 if (TimePassesIsEnabled)
1788 DebugTimer->startTimer();
1789
1790 GlobalVariable *GV = SP.getGV();
1791 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1792 II = AbstractInstanceRootMap.find(GV);
1793
1794 if (II == AbstractInstanceRootMap.end()) {
1795 // Create an abstract instance entry for this inlined function if it doesn't
1796 // already exist.
1797 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
1798
1799 // Get the compile unit context.
1800 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
1801 DIE *SPDie = Unit->getDieMapSlotFor(GV);
1802 if (!SPDie)
1803 SPDie = CreateSubprogramDIE(Unit, SP, false, true);
1804
1805 // Mark as being inlined. This makes this subprogram entry an abstract
1806 // instance root.
1807 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
1808 // that it's defined. That probably won't change in the future. However,
1809 // this could be more elegant.
1810 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
1811
1812 // Keep track of the abstract scope for this function.
1813 DbgAbstractScopeMap[GV] = Scope;
1814
1815 AbstractInstanceRootMap[GV] = Scope;
1816 AbstractInstanceRootList.push_back(Scope);
1817 }
1818
1819 // Create a concrete inlined instance for this inlined function.
1820 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
1821 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
1822 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
1823 ScopeDie->setAbstractCompileUnit(Unit);
1824
1825 DIE *Origin = Unit->getDieMapSlotFor(GV);
1826 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
1827 dwarf::DW_FORM_ref4, Origin);
1828 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, Unit->getID());
1829 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
1830 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
1831
1832 ConcreteScope->setDie(ScopeDie);
1833 ConcreteScope->setStartLabelID(LabelID);
1834 MMI->RecordUsedDbgLabel(LabelID);
1835
1836 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
1837
1838 // Keep track of the concrete scope that's inlined into this function.
1839 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1840 SI = DbgConcreteScopeMap.find(GV);
1841
1842 if (SI == DbgConcreteScopeMap.end())
1843 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
1844 else
1845 SI->second.push_back(ConcreteScope);
1846
1847 // Track the start label for this inlined function.
1848 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1849 I = InlineInfo.find(GV);
1850
1851 if (I == InlineInfo.end())
1852 InlineInfo[GV].push_back(LabelID);
1853 else
1854 I->second.push_back(LabelID);
1855
1856 if (TimePassesIsEnabled)
1857 DebugTimer->stopTimer();
1858
1859 return LabelID;
1860}
1861
1862/// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
1863unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
1864 if (!TAI->doesDwarfUsesInlineInfoSection())
1865 return 0;
1866
1867 if (TimePassesIsEnabled)
1868 DebugTimer->startTimer();
1869
1870 GlobalVariable *GV = SP.getGV();
1871 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1872 I = DbgConcreteScopeMap.find(GV);
1873
1874 if (I == DbgConcreteScopeMap.end()) {
1875 // FIXME: Can this situation actually happen? And if so, should it?
1876 if (TimePassesIsEnabled)
1877 DebugTimer->stopTimer();
1878
1879 return 0;
1880 }
1881
1882 SmallVector<DbgScope *, 8> &Scopes = I->second;
1883 assert(!Scopes.empty() && "We should have at least one debug scope!");
1884 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
1885 unsigned ID = MMI->NextLabelID();
1886 MMI->RecordUsedDbgLabel(ID);
1887 Scope->setEndLabelID(ID);
1888
1889 if (TimePassesIsEnabled)
1890 DebugTimer->stopTimer();
1891
1892 return ID;
1893}
1894
1895/// RecordVariableScope - Record scope for the variable declared by
1896/// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
1897/// for only inlined subroutine variables. Other variables's scopes are
1898/// determined during RecordVariable().
1899void DwarfDebug::RecordVariableScope(DIVariable &DV,
1900 const MachineInstr *DeclareMI) {
1901 if (TimePassesIsEnabled)
1902 DebugTimer->startTimer();
1903
1904 DISubprogram SP(DV.getContext().getGV());
1905
1906 if (SP.isNull()) {
1907 if (TimePassesIsEnabled)
1908 DebugTimer->stopTimer();
1909
1910 return;
1911 }
1912
1913 DenseMap<GlobalVariable *, DbgScope *>::iterator
1914 I = DbgAbstractScopeMap.find(SP.getGV());
1915 if (I != DbgAbstractScopeMap.end())
1916 InlinedVariableScopes[DeclareMI] = I->second;
1917
1918 if (TimePassesIsEnabled)
1919 DebugTimer->stopTimer();
1920}
Bill Wendling94d04b82009-05-20 23:21:38 +00001921
1922/// SizeAndOffsetDie - Compute the size and offset of a DIE.
1923///
1924unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1925 // Get the children.
1926 const std::vector<DIE *> &Children = Die->getChildren();
1927
1928 // If not last sibling and has children then add sibling offset attribute.
1929 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1930
1931 // Record the abbreviation.
1932 AssignAbbrevNumber(Die->getAbbrev());
1933
1934 // Get the abbreviation for this DIE.
1935 unsigned AbbrevNumber = Die->getAbbrevNumber();
1936 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1937
1938 // Set DIE offset
1939 Die->setOffset(Offset);
1940
1941 // Start the size with the size of abbreviation code.
1942 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1943
1944 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1945 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1946
1947 // Size the DIE attribute values.
1948 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1949 // Size attribute value.
1950 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1951
1952 // Size the DIE children if any.
1953 if (!Children.empty()) {
1954 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1955 "Children flag not set");
1956
1957 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1958 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1959
1960 // End of children marker.
1961 Offset += sizeof(int8_t);
1962 }
1963
1964 Die->setSize(Offset - Die->getOffset());
1965 return Offset;
1966}
1967
1968/// SizeAndOffsets - Compute the size and offset of all the DIEs.
1969///
1970void DwarfDebug::SizeAndOffsets() {
1971 // Compute size of compile unit header.
1972 static unsigned Offset =
1973 sizeof(int32_t) + // Length of Compilation Unit Info
1974 sizeof(int16_t) + // DWARF version number
1975 sizeof(int32_t) + // Offset Into Abbrev. Section
1976 sizeof(int8_t); // Pointer Size (in bytes)
1977
1978 // Process base compile unit.
1979 if (MainCU) {
1980 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
1981 CompileUnitOffsets[MainCU] = 0;
1982 return;
1983 }
1984
1985 // Process all compile units.
1986 unsigned PrevOffset = 0;
1987
1988 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1989 CompileUnit *Unit = CompileUnits[i];
1990 CompileUnitOffsets[Unit] = PrevOffset;
1991 PrevOffset += SizeAndOffsetDie(Unit->getDie(), Offset, true)
1992 + sizeof(int32_t); // FIXME - extra pad for gdb bug.
1993 }
1994}
1995
1996/// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1997/// tools to recognize the object file contains Dwarf information.
1998void DwarfDebug::EmitInitial() {
1999 // Check to see if we already emitted intial headers.
2000 if (didInitial) return;
2001 didInitial = true;
2002
2003 // Dwarf sections base addresses.
2004 if (TAI->doesDwarfRequireFrameSection()) {
2005 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2006 EmitLabel("section_debug_frame", 0);
2007 }
2008
2009 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2010 EmitLabel("section_info", 0);
2011 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2012 EmitLabel("section_abbrev", 0);
2013 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2014 EmitLabel("section_aranges", 0);
2015
2016 if (TAI->doesSupportMacInfoSection()) {
2017 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2018 EmitLabel("section_macinfo", 0);
2019 }
2020
2021 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2022 EmitLabel("section_line", 0);
2023 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2024 EmitLabel("section_loc", 0);
2025 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2026 EmitLabel("section_pubnames", 0);
2027 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2028 EmitLabel("section_str", 0);
2029 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2030 EmitLabel("section_ranges", 0);
2031
2032 Asm->SwitchToSection(TAI->getTextSection());
2033 EmitLabel("text_begin", 0);
2034 Asm->SwitchToSection(TAI->getDataSection());
2035 EmitLabel("data_begin", 0);
2036}
2037
2038/// EmitDIE - Recusively Emits a debug information entry.
2039///
2040void DwarfDebug::EmitDIE(DIE *Die) {
2041 // Get the abbreviation for this DIE.
2042 unsigned AbbrevNumber = Die->getAbbrevNumber();
2043 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2044
2045 Asm->EOL();
2046
2047 // Emit the code (index) for the abbreviation.
2048 Asm->EmitULEB128Bytes(AbbrevNumber);
2049
2050 if (Asm->isVerbose())
2051 Asm->EOL(std::string("Abbrev [" +
2052 utostr(AbbrevNumber) +
2053 "] 0x" + utohexstr(Die->getOffset()) +
2054 ":0x" + utohexstr(Die->getSize()) + " " +
2055 dwarf::TagString(Abbrev->getTag())));
2056 else
2057 Asm->EOL();
2058
2059 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2060 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2061
2062 // Emit the DIE attribute values.
2063 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2064 unsigned Attr = AbbrevData[i].getAttribute();
2065 unsigned Form = AbbrevData[i].getForm();
2066 assert(Form && "Too many attributes for DIE (check abbreviation)");
2067
2068 switch (Attr) {
2069 case dwarf::DW_AT_sibling:
2070 Asm->EmitInt32(Die->SiblingOffset());
2071 break;
2072 case dwarf::DW_AT_abstract_origin: {
2073 DIEEntry *E = cast<DIEEntry>(Values[i]);
2074 DIE *Origin = E->getEntry();
2075 unsigned Addr =
2076 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
2077 Origin->getOffset();
2078
2079 Asm->EmitInt32(Addr);
2080 break;
2081 }
2082 default:
2083 // Emit an attribute using the defined form.
2084 Values[i]->EmitValue(this, Form);
2085 break;
2086 }
2087
2088 Asm->EOL(dwarf::AttributeString(Attr));
2089 }
2090
2091 // Emit the DIE children if any.
2092 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2093 const std::vector<DIE *> &Children = Die->getChildren();
2094
2095 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2096 EmitDIE(Children[j]);
2097
2098 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2099 }
2100}
2101
2102/// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2103///
2104void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
2105 DIE *Die = Unit->getDie();
2106
2107 // Emit the compile units header.
2108 EmitLabel("info_begin", Unit->getID());
2109
2110 // Emit size of content not including length itself
2111 unsigned ContentSize = Die->getSize() +
2112 sizeof(int16_t) + // DWARF version number
2113 sizeof(int32_t) + // Offset Into Abbrev. Section
2114 sizeof(int8_t) + // Pointer Size (in bytes)
2115 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2116
2117 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2118 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2119 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2120 Asm->EOL("Offset Into Abbrev. Section");
2121 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2122
2123 EmitDIE(Die);
2124 // FIXME - extra padding for gdb bug.
2125 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2126 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2127 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2128 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2129 EmitLabel("info_end", Unit->getID());
2130
2131 Asm->EOL();
2132}
2133
2134void DwarfDebug::EmitDebugInfo() {
2135 // Start debug info section.
2136 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2137
2138 if (MainCU) {
2139 EmitDebugInfoPerCU(MainCU);
2140 return;
2141 }
2142
2143 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2144 EmitDebugInfoPerCU(CompileUnits[i]);
2145}
2146
2147/// EmitAbbreviations - Emit the abbreviation section.
2148///
2149void DwarfDebug::EmitAbbreviations() const {
2150 // Check to see if it is worth the effort.
2151 if (!Abbreviations.empty()) {
2152 // Start the debug abbrev section.
2153 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2154
2155 EmitLabel("abbrev_begin", 0);
2156
2157 // For each abbrevation.
2158 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2159 // Get abbreviation data
2160 const DIEAbbrev *Abbrev = Abbreviations[i];
2161
2162 // Emit the abbrevations code (base 1 index.)
2163 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2164 Asm->EOL("Abbreviation Code");
2165
2166 // Emit the abbreviations data.
2167 Abbrev->Emit(Asm);
2168
2169 Asm->EOL();
2170 }
2171
2172 // Mark end of abbreviations.
2173 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2174
2175 EmitLabel("abbrev_end", 0);
2176 Asm->EOL();
2177 }
2178}
2179
2180/// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2181/// the line matrix.
2182///
2183void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2184 // Define last address of section.
2185 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2186 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2187 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2188 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2189
2190 // Mark end of matrix.
2191 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2192 Asm->EmitULEB128Bytes(1); Asm->EOL();
2193 Asm->EmitInt8(1); Asm->EOL();
2194}
2195
2196/// EmitDebugLines - Emit source line information.
2197///
2198void DwarfDebug::EmitDebugLines() {
2199 // If the target is using .loc/.file, the assembler will be emitting the
2200 // .debug_line table automatically.
2201 if (TAI->hasDotLocAndDotFile())
2202 return;
2203
2204 // Minimum line delta, thus ranging from -10..(255-10).
2205 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2206 // Maximum line delta, thus ranging from -10..(255-10).
2207 const int MaxLineDelta = 255 + MinLineDelta;
2208
2209 // Start the dwarf line section.
2210 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2211
2212 // Construct the section header.
2213 EmitDifference("line_end", 0, "line_begin", 0, true);
2214 Asm->EOL("Length of Source Line Info");
2215 EmitLabel("line_begin", 0);
2216
2217 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2218
2219 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2220 Asm->EOL("Prolog Length");
2221 EmitLabel("line_prolog_begin", 0);
2222
2223 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2224
2225 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2226
2227 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2228
2229 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2230
2231 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2232
2233 // Line number standard opcode encodings argument count
2234 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2235 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2236 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2237 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2238 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2239 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2240 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2241 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2242 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2243
2244 // Emit directories.
2245 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2246 Asm->EmitString(getSourceDirectoryName(DI));
2247 Asm->EOL("Directory");
2248 }
2249
2250 Asm->EmitInt8(0); Asm->EOL("End of directories");
2251
2252 // Emit files.
2253 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2254 // Remember source id starts at 1.
2255 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2256 Asm->EmitString(getSourceFileName(Id.second));
2257 Asm->EOL("Source");
2258 Asm->EmitULEB128Bytes(Id.first);
2259 Asm->EOL("Directory #");
2260 Asm->EmitULEB128Bytes(0);
2261 Asm->EOL("Mod date");
2262 Asm->EmitULEB128Bytes(0);
2263 Asm->EOL("File size");
2264 }
2265
2266 Asm->EmitInt8(0); Asm->EOL("End of files");
2267
2268 EmitLabel("line_prolog_end", 0);
2269
2270 // A sequence for each text section.
2271 unsigned SecSrcLinesSize = SectionSourceLines.size();
2272
2273 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2274 // Isolate current sections line info.
2275 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2276
2277 if (Asm->isVerbose()) {
2278 const Section* S = SectionMap[j + 1];
2279 O << '\t' << TAI->getCommentString() << " Section"
2280 << S->getName() << '\n';
2281 } else {
2282 Asm->EOL();
2283 }
2284
2285 // Dwarf assumes we start with first line of first source file.
2286 unsigned Source = 1;
2287 unsigned Line = 1;
2288
2289 // Construct rows of the address, source, line, column matrix.
2290 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2291 const SrcLineInfo &LineInfo = LineInfos[i];
2292 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2293 if (!LabelID) continue;
2294
2295 if (!Asm->isVerbose())
2296 Asm->EOL();
2297 else {
2298 std::pair<unsigned, unsigned> SourceID =
2299 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2300 O << '\t' << TAI->getCommentString() << ' '
2301 << getSourceDirectoryName(SourceID.first) << ' '
2302 << getSourceFileName(SourceID.second)
2303 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2304 }
2305
2306 // Define the line address.
2307 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2308 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2309 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2310 EmitReference("label", LabelID); Asm->EOL("Location label");
2311
2312 // If change of source, then switch to the new source.
2313 if (Source != LineInfo.getSourceID()) {
2314 Source = LineInfo.getSourceID();
2315 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2316 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2317 }
2318
2319 // If change of line.
2320 if (Line != LineInfo.getLine()) {
2321 // Determine offset.
2322 int Offset = LineInfo.getLine() - Line;
2323 int Delta = Offset - MinLineDelta;
2324
2325 // Update line.
2326 Line = LineInfo.getLine();
2327
2328 // If delta is small enough and in range...
2329 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2330 // ... then use fast opcode.
2331 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2332 } else {
2333 // ... otherwise use long hand.
2334 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2335 Asm->EOL("DW_LNS_advance_line");
2336 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2337 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2338 }
2339 } else {
2340 // Copy the previous row (different address or source)
2341 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2342 }
2343 }
2344
2345 EmitEndOfLineMatrix(j + 1);
2346 }
2347
2348 if (SecSrcLinesSize == 0)
2349 // Because we're emitting a debug_line section, we still need a line
2350 // table. The linker and friends expect it to exist. If there's nothing to
2351 // put into it, emit an empty table.
2352 EmitEndOfLineMatrix(1);
2353
2354 EmitLabel("line_end", 0);
2355 Asm->EOL();
2356}
2357
2358/// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2359///
2360void DwarfDebug::EmitCommonDebugFrame() {
2361 if (!TAI->doesDwarfRequireFrameSection())
2362 return;
2363
2364 int stackGrowth =
2365 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2366 TargetFrameInfo::StackGrowsUp ?
2367 TD->getPointerSize() : -TD->getPointerSize();
2368
2369 // Start the dwarf frame section.
2370 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2371
2372 EmitLabel("debug_frame_common", 0);
2373 EmitDifference("debug_frame_common_end", 0,
2374 "debug_frame_common_begin", 0, true);
2375 Asm->EOL("Length of Common Information Entry");
2376
2377 EmitLabel("debug_frame_common_begin", 0);
2378 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2379 Asm->EOL("CIE Identifier Tag");
2380 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2381 Asm->EOL("CIE Version");
2382 Asm->EmitString("");
2383 Asm->EOL("CIE Augmentation");
2384 Asm->EmitULEB128Bytes(1);
2385 Asm->EOL("CIE Code Alignment Factor");
2386 Asm->EmitSLEB128Bytes(stackGrowth);
2387 Asm->EOL("CIE Data Alignment Factor");
2388 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2389 Asm->EOL("CIE RA Column");
2390
2391 std::vector<MachineMove> Moves;
2392 RI->getInitialFrameState(Moves);
2393
2394 EmitFrameMoves(NULL, 0, Moves, false);
2395
2396 Asm->EmitAlignment(2, 0, 0, false);
2397 EmitLabel("debug_frame_common_end", 0);
2398
2399 Asm->EOL();
2400}
2401
2402/// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2403/// section.
2404void
2405DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2406 if (!TAI->doesDwarfRequireFrameSection())
2407 return;
2408
2409 // Start the dwarf frame section.
2410 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2411
2412 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2413 "debug_frame_begin", DebugFrameInfo.Number, true);
2414 Asm->EOL("Length of Frame Information Entry");
2415
2416 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2417
2418 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2419 0, 0, true, false);
2420 Asm->EOL("FDE CIE offset");
2421
2422 EmitReference("func_begin", DebugFrameInfo.Number);
2423 Asm->EOL("FDE initial location");
2424 EmitDifference("func_end", DebugFrameInfo.Number,
2425 "func_begin", DebugFrameInfo.Number);
2426 Asm->EOL("FDE address range");
2427
2428 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2429 false);
2430
2431 Asm->EmitAlignment(2, 0, 0, false);
2432 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2433
2434 Asm->EOL();
2435}
2436
2437void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2438 EmitDifference("pubnames_end", Unit->getID(),
2439 "pubnames_begin", Unit->getID(), true);
2440 Asm->EOL("Length of Public Names Info");
2441
2442 EmitLabel("pubnames_begin", Unit->getID());
2443
2444 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2445
2446 EmitSectionOffset("info_begin", "section_info",
2447 Unit->getID(), 0, true, false);
2448 Asm->EOL("Offset of Compilation Unit Info");
2449
2450 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2451 true);
2452 Asm->EOL("Compilation Unit Length");
2453
2454 StringMap<DIE*> &Globals = Unit->getGlobals();
2455 for (StringMap<DIE*>::const_iterator
2456 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2457 const char *Name = GI->getKeyData();
2458 DIE * Entity = GI->second;
2459
2460 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2461 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2462 }
2463
2464 Asm->EmitInt32(0); Asm->EOL("End Mark");
2465 EmitLabel("pubnames_end", Unit->getID());
2466
2467 Asm->EOL();
2468}
2469
2470/// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2471///
2472void DwarfDebug::EmitDebugPubNames() {
2473 // Start the dwarf pubnames section.
2474 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2475
2476 if (MainCU) {
2477 EmitDebugPubNamesPerCU(MainCU);
2478 return;
2479 }
2480
2481 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2482 EmitDebugPubNamesPerCU(CompileUnits[i]);
2483}
2484
2485/// EmitDebugStr - Emit visible names into a debug str section.
2486///
2487void DwarfDebug::EmitDebugStr() {
2488 // Check to see if it is worth the effort.
2489 if (!StringPool.empty()) {
2490 // Start the dwarf str section.
2491 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2492
2493 // For each of strings in the string pool.
2494 for (unsigned StringID = 1, N = StringPool.size();
2495 StringID <= N; ++StringID) {
2496 // Emit a label for reference from debug information entries.
2497 EmitLabel("string", StringID);
2498
2499 // Emit the string itself.
2500 const std::string &String = StringPool[StringID];
2501 Asm->EmitString(String); Asm->EOL();
2502 }
2503
2504 Asm->EOL();
2505 }
2506}
2507
2508/// EmitDebugLoc - Emit visible names into a debug loc section.
2509///
2510void DwarfDebug::EmitDebugLoc() {
2511 // Start the dwarf loc section.
2512 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2513 Asm->EOL();
2514}
2515
2516/// EmitDebugARanges - Emit visible names into a debug aranges section.
2517///
2518void DwarfDebug::EmitDebugARanges() {
2519 // Start the dwarf aranges section.
2520 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2521
2522 // FIXME - Mock up
2523#if 0
2524 CompileUnit *Unit = GetBaseCompileUnit();
2525
2526 // Don't include size of length
2527 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2528
2529 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2530
2531 EmitReference("info_begin", Unit->getID());
2532 Asm->EOL("Offset of Compilation Unit Info");
2533
2534 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2535
2536 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2537
2538 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2539 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2540
2541 // Range 1
2542 EmitReference("text_begin", 0); Asm->EOL("Address");
2543 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2544
2545 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2546 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2547#endif
2548
2549 Asm->EOL();
2550}
2551
2552/// EmitDebugRanges - Emit visible names into a debug ranges section.
2553///
2554void DwarfDebug::EmitDebugRanges() {
2555 // Start the dwarf ranges section.
2556 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2557 Asm->EOL();
2558}
2559
2560/// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2561///
2562void DwarfDebug::EmitDebugMacInfo() {
2563 if (TAI->doesSupportMacInfoSection()) {
2564 // Start the dwarf macinfo section.
2565 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2566 Asm->EOL();
2567 }
2568}
2569
2570/// EmitDebugInlineInfo - Emit inline info using following format.
2571/// Section Header:
2572/// 1. length of section
2573/// 2. Dwarf version number
2574/// 3. address size.
2575///
2576/// Entries (one "entry" for each function that was inlined):
2577///
2578/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2579/// otherwise offset into __debug_str for regular function name.
2580/// 2. offset into __debug_str section for regular function name.
2581/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2582/// instances for the function.
2583///
2584/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2585/// inlined instance; the die_offset points to the inlined_subroutine die in the
2586/// __debug_info section, and the low_pc is the starting address for the
2587/// inlining instance.
2588void DwarfDebug::EmitDebugInlineInfo() {
2589 if (!TAI->doesDwarfUsesInlineInfoSection())
2590 return;
2591
2592 if (!MainCU)
2593 return;
2594
2595 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
2596 Asm->EOL();
2597 EmitDifference("debug_inlined_end", 1,
2598 "debug_inlined_begin", 1, true);
2599 Asm->EOL("Length of Debug Inlined Information Entry");
2600
2601 EmitLabel("debug_inlined_begin", 1);
2602
2603 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2604 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2605
2606 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2607 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2608 GlobalVariable *GV = I->first;
2609 SmallVector<unsigned, 4> &Labels = I->second;
2610 DISubprogram SP(GV);
2611 std::string Name;
2612 std::string LName;
2613
2614 SP.getLinkageName(LName);
2615 SP.getName(Name);
2616
2617 Asm->EmitString(LName.empty() ? Name : LName);
2618 Asm->EOL("MIPS linkage name");
2619
2620 Asm->EmitString(Name); Asm->EOL("Function name");
2621
2622 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2623
2624 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2625 LE = Labels.end(); LI != LE; ++LI) {
2626 DIE *SP = MainCU->getDieMapSlotFor(GV);
2627 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2628
2629 if (TD->getPointerSize() == sizeof(int32_t))
2630 O << TAI->getData32bitsDirective();
2631 else
2632 O << TAI->getData64bitsDirective();
2633
2634 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2635 }
2636 }
2637
2638 EmitLabel("debug_inlined_end", 1);
2639 Asm->EOL();
2640}