blob: 086a8a5f60ef9aef2b5baab6724923152984020d [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
278/// NewDIEEntry - Creates a new DIEEntry to be a proxy for a debug information
279/// entry.
280DIEEntry *DwarfDebug::NewDIEEntry(DIE *Entry) {
281 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.
548 Slot = NewDIEEntry();
549
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
928/// NewDbgScopeVariable - Create a new scope variable.
929///
930DIE *DwarfDebug::NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
931 // 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) {
1015 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
1016 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///
1095void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope) {
1096 // 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
1114 // 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);
1121
1122 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
1123}
1124
1125/// 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
1151/// 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
1199/// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1200/// tools to recognize the object file contains Dwarf information.
1201void DwarfDebug::EmitInitial() {
1202 // Check to see if we already emitted intial headers.
1203 if (didInitial) return;
1204 didInitial = true;
1205
1206 // Dwarf sections base addresses.
1207 if (TAI->doesDwarfRequireFrameSection()) {
1208 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1209 EmitLabel("section_debug_frame", 0);
1210 }
1211
1212 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1213 EmitLabel("section_info", 0);
1214 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1215 EmitLabel("section_abbrev", 0);
1216 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1217 EmitLabel("section_aranges", 0);
1218
1219 if (TAI->doesSupportMacInfoSection()) {
1220 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1221 EmitLabel("section_macinfo", 0);
1222 }
1223
1224 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1225 EmitLabel("section_line", 0);
1226 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1227 EmitLabel("section_loc", 0);
1228 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1229 EmitLabel("section_pubnames", 0);
1230 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1231 EmitLabel("section_str", 0);
1232 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1233 EmitLabel("section_ranges", 0);
1234
1235 Asm->SwitchToSection(TAI->getTextSection());
1236 EmitLabel("text_begin", 0);
1237 Asm->SwitchToSection(TAI->getDataSection());
1238 EmitLabel("data_begin", 0);
1239}
1240
1241/// EmitDIE - Recusively Emits a debug information entry.
1242///
1243void DwarfDebug::EmitDIE(DIE *Die) {
1244 // Get the abbreviation for this DIE.
1245 unsigned AbbrevNumber = Die->getAbbrevNumber();
1246 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1247
1248 Asm->EOL();
1249
1250 // Emit the code (index) for the abbreviation.
1251 Asm->EmitULEB128Bytes(AbbrevNumber);
1252
1253 if (Asm->isVerbose())
1254 Asm->EOL(std::string("Abbrev [" +
1255 utostr(AbbrevNumber) +
1256 "] 0x" + utohexstr(Die->getOffset()) +
1257 ":0x" + utohexstr(Die->getSize()) + " " +
1258 dwarf::TagString(Abbrev->getTag())));
1259 else
1260 Asm->EOL();
1261
1262 SmallVector<DIEValue*, 32> &Values = Die->getValues();
1263 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1264
1265 // Emit the DIE attribute values.
1266 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1267 unsigned Attr = AbbrevData[i].getAttribute();
1268 unsigned Form = AbbrevData[i].getForm();
1269 assert(Form && "Too many attributes for DIE (check abbreviation)");
1270
1271 switch (Attr) {
1272 case dwarf::DW_AT_sibling:
1273 Asm->EmitInt32(Die->SiblingOffset());
1274 break;
1275 case dwarf::DW_AT_abstract_origin: {
1276 DIEEntry *E = cast<DIEEntry>(Values[i]);
1277 DIE *Origin = E->getEntry();
1278 unsigned Addr =
1279 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
1280 Origin->getOffset();
1281
1282 Asm->EmitInt32(Addr);
1283 break;
1284 }
1285 default:
1286 // Emit an attribute using the defined form.
1287 Values[i]->EmitValue(this, Form);
1288 break;
1289 }
1290
1291 Asm->EOL(dwarf::AttributeString(Attr));
1292 }
1293
1294 // Emit the DIE children if any.
1295 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1296 const std::vector<DIE *> &Children = Die->getChildren();
1297
1298 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1299 EmitDIE(Children[j]);
1300
1301 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1302 }
1303}
1304
1305/// SizeAndOffsetDie - Compute the size and offset of a DIE.
1306///
1307unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1308 // Get the children.
1309 const std::vector<DIE *> &Children = Die->getChildren();
1310
1311 // If not last sibling and has children then add sibling offset attribute.
1312 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1313
1314 // Record the abbreviation.
1315 AssignAbbrevNumber(Die->getAbbrev());
1316
1317 // Get the abbreviation for this DIE.
1318 unsigned AbbrevNumber = Die->getAbbrevNumber();
1319 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1320
1321 // Set DIE offset
1322 Die->setOffset(Offset);
1323
1324 // Start the size with the size of abbreviation code.
1325 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1326
1327 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1328 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1329
1330 // Size the DIE attribute values.
1331 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1332 // Size attribute value.
1333 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1334
1335 // Size the DIE children if any.
1336 if (!Children.empty()) {
1337 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1338 "Children flag not set");
1339
1340 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1341 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1342
1343 // End of children marker.
1344 Offset += sizeof(int8_t);
1345 }
1346
1347 Die->setSize(Offset - Die->getOffset());
1348 return Offset;
1349}
1350
1351/// SizeAndOffsets - Compute the size and offset of all the DIEs.
1352///
1353void DwarfDebug::SizeAndOffsets() {
1354 // Compute size of compile unit header.
1355 static unsigned Offset =
1356 sizeof(int32_t) + // Length of Compilation Unit Info
1357 sizeof(int16_t) + // DWARF version number
1358 sizeof(int32_t) + // Offset Into Abbrev. Section
1359 sizeof(int8_t); // Pointer Size (in bytes)
1360
1361 // Process base compile unit.
1362 if (MainCU) {
1363 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
1364 CompileUnitOffsets[MainCU] = 0;
1365 return;
1366 }
1367
1368 // Process all compile units.
1369 unsigned PrevOffset = 0;
1370
1371 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1372 CompileUnit *Unit = CompileUnits[i];
1373 CompileUnitOffsets[Unit] = PrevOffset;
1374 PrevOffset += SizeAndOffsetDie(Unit->getDie(), Offset, true)
1375 + sizeof(int32_t); // FIXME - extra pad for gdb bug.
1376 }
1377}
1378
1379/// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
1380///
1381void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
1382 DIE *Die = Unit->getDie();
1383
1384 // Emit the compile units header.
1385 EmitLabel("info_begin", Unit->getID());
1386
1387 // Emit size of content not including length itself
1388 unsigned ContentSize = Die->getSize() +
1389 sizeof(int16_t) + // DWARF version number
1390 sizeof(int32_t) + // Offset Into Abbrev. Section
1391 sizeof(int8_t) + // Pointer Size (in bytes)
1392 sizeof(int32_t); // FIXME - extra pad for gdb bug.
1393
1394 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
1395 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1396 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
1397 Asm->EOL("Offset Into Abbrev. Section");
1398 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1399
1400 EmitDIE(Die);
1401 // FIXME - extra padding for gdb bug.
1402 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1403 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1404 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1405 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1406 EmitLabel("info_end", Unit->getID());
1407
1408 Asm->EOL();
1409}
1410
1411void DwarfDebug::EmitDebugInfo() {
1412 // Start debug info section.
1413 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1414
1415 if (MainCU) {
1416 EmitDebugInfoPerCU(MainCU);
1417 return;
1418 }
1419
1420 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1421 EmitDebugInfoPerCU(CompileUnits[i]);
1422}
1423
1424/// EmitAbbreviations - Emit the abbreviation section.
1425///
1426void DwarfDebug::EmitAbbreviations() const {
1427 // Check to see if it is worth the effort.
1428 if (!Abbreviations.empty()) {
1429 // Start the debug abbrev section.
1430 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1431
1432 EmitLabel("abbrev_begin", 0);
1433
1434 // For each abbrevation.
1435 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1436 // Get abbreviation data
1437 const DIEAbbrev *Abbrev = Abbreviations[i];
1438
1439 // Emit the abbrevations code (base 1 index.)
1440 Asm->EmitULEB128Bytes(Abbrev->getNumber());
1441 Asm->EOL("Abbreviation Code");
1442
1443 // Emit the abbreviations data.
1444 Abbrev->Emit(Asm);
1445
1446 Asm->EOL();
1447 }
1448
1449 // Mark end of abbreviations.
1450 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
1451
1452 EmitLabel("abbrev_end", 0);
1453 Asm->EOL();
1454 }
1455}
1456
1457/// EmitEndOfLineMatrix - Emit the last address of the section and the end of
1458/// the line matrix.
1459///
1460void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
1461 // Define last address of section.
1462 Asm->EmitInt8(0); Asm->EOL("Extended Op");
1463 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1464 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1465 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
1466
1467 // Mark end of matrix.
1468 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
1469 Asm->EmitULEB128Bytes(1); Asm->EOL();
1470 Asm->EmitInt8(1); Asm->EOL();
1471}
1472
1473/// EmitDebugLines - Emit source line information.
1474///
1475void DwarfDebug::EmitDebugLines() {
1476 // If the target is using .loc/.file, the assembler will be emitting the
1477 // .debug_line table automatically.
1478 if (TAI->hasDotLocAndDotFile())
1479 return;
1480
1481 // Minimum line delta, thus ranging from -10..(255-10).
1482 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
1483 // Maximum line delta, thus ranging from -10..(255-10).
1484 const int MaxLineDelta = 255 + MinLineDelta;
1485
1486 // Start the dwarf line section.
1487 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1488
1489 // Construct the section header.
1490 EmitDifference("line_end", 0, "line_begin", 0, true);
1491 Asm->EOL("Length of Source Line Info");
1492 EmitLabel("line_begin", 0);
1493
1494 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1495
1496 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
1497 Asm->EOL("Prolog Length");
1498 EmitLabel("line_prolog_begin", 0);
1499
1500 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
1501
1502 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
1503
1504 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
1505
1506 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
1507
1508 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
1509
1510 // Line number standard opcode encodings argument count
1511 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
1512 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
1513 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
1514 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
1515 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
1516 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
1517 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
1518 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
1519 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
1520
1521 // Emit directories.
1522 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
1523 Asm->EmitString(getSourceDirectoryName(DI));
1524 Asm->EOL("Directory");
1525 }
1526
1527 Asm->EmitInt8(0); Asm->EOL("End of directories");
1528
1529 // Emit files.
1530 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
1531 // Remember source id starts at 1.
1532 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
1533 Asm->EmitString(getSourceFileName(Id.second));
1534 Asm->EOL("Source");
1535 Asm->EmitULEB128Bytes(Id.first);
1536 Asm->EOL("Directory #");
1537 Asm->EmitULEB128Bytes(0);
1538 Asm->EOL("Mod date");
1539 Asm->EmitULEB128Bytes(0);
1540 Asm->EOL("File size");
1541 }
1542
1543 Asm->EmitInt8(0); Asm->EOL("End of files");
1544
1545 EmitLabel("line_prolog_end", 0);
1546
1547 // A sequence for each text section.
1548 unsigned SecSrcLinesSize = SectionSourceLines.size();
1549
1550 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
1551 // Isolate current sections line info.
1552 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
1553
1554 if (Asm->isVerbose()) {
1555 const Section* S = SectionMap[j + 1];
1556 O << '\t' << TAI->getCommentString() << " Section"
1557 << S->getName() << '\n';
1558 } else {
1559 Asm->EOL();
1560 }
1561
1562 // Dwarf assumes we start with first line of first source file.
1563 unsigned Source = 1;
1564 unsigned Line = 1;
1565
1566 // Construct rows of the address, source, line, column matrix.
1567 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
1568 const SrcLineInfo &LineInfo = LineInfos[i];
1569 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
1570 if (!LabelID) continue;
1571
1572 if (!Asm->isVerbose())
1573 Asm->EOL();
1574 else {
1575 std::pair<unsigned, unsigned> SourceID =
1576 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
1577 O << '\t' << TAI->getCommentString() << ' '
1578 << getSourceDirectoryName(SourceID.first) << ' '
1579 << getSourceFileName(SourceID.second)
1580 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
1581 }
1582
1583 // Define the line address.
1584 Asm->EmitInt8(0); Asm->EOL("Extended Op");
1585 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1586 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1587 EmitReference("label", LabelID); Asm->EOL("Location label");
1588
1589 // If change of source, then switch to the new source.
1590 if (Source != LineInfo.getSourceID()) {
1591 Source = LineInfo.getSourceID();
1592 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
1593 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
1594 }
1595
1596 // If change of line.
1597 if (Line != LineInfo.getLine()) {
1598 // Determine offset.
1599 int Offset = LineInfo.getLine() - Line;
1600 int Delta = Offset - MinLineDelta;
1601
1602 // Update line.
1603 Line = LineInfo.getLine();
1604
1605 // If delta is small enough and in range...
1606 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
1607 // ... then use fast opcode.
1608 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
1609 } else {
1610 // ... otherwise use long hand.
1611 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
1612 Asm->EOL("DW_LNS_advance_line");
1613 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
1614 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1615 }
1616 } else {
1617 // Copy the previous row (different address or source)
1618 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1619 }
1620 }
1621
1622 EmitEndOfLineMatrix(j + 1);
1623 }
1624
1625 if (SecSrcLinesSize == 0)
1626 // Because we're emitting a debug_line section, we still need a line
1627 // table. The linker and friends expect it to exist. If there's nothing to
1628 // put into it, emit an empty table.
1629 EmitEndOfLineMatrix(1);
1630
1631 EmitLabel("line_end", 0);
1632 Asm->EOL();
1633}
1634
1635/// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
1636///
1637void DwarfDebug::EmitCommonDebugFrame() {
1638 if (!TAI->doesDwarfRequireFrameSection())
1639 return;
1640
1641 int stackGrowth =
1642 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1643 TargetFrameInfo::StackGrowsUp ?
1644 TD->getPointerSize() : -TD->getPointerSize();
1645
1646 // Start the dwarf frame section.
1647 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1648
1649 EmitLabel("debug_frame_common", 0);
1650 EmitDifference("debug_frame_common_end", 0,
1651 "debug_frame_common_begin", 0, true);
1652 Asm->EOL("Length of Common Information Entry");
1653
1654 EmitLabel("debug_frame_common_begin", 0);
1655 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
1656 Asm->EOL("CIE Identifier Tag");
1657 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
1658 Asm->EOL("CIE Version");
1659 Asm->EmitString("");
1660 Asm->EOL("CIE Augmentation");
1661 Asm->EmitULEB128Bytes(1);
1662 Asm->EOL("CIE Code Alignment Factor");
1663 Asm->EmitSLEB128Bytes(stackGrowth);
1664 Asm->EOL("CIE Data Alignment Factor");
1665 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
1666 Asm->EOL("CIE RA Column");
1667
1668 std::vector<MachineMove> Moves;
1669 RI->getInitialFrameState(Moves);
1670
1671 EmitFrameMoves(NULL, 0, Moves, false);
1672
1673 Asm->EmitAlignment(2, 0, 0, false);
1674 EmitLabel("debug_frame_common_end", 0);
1675
1676 Asm->EOL();
1677}
1678
1679/// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
1680/// section.
1681void
1682DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
1683 if (!TAI->doesDwarfRequireFrameSection())
1684 return;
1685
1686 // Start the dwarf frame section.
1687 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1688
1689 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
1690 "debug_frame_begin", DebugFrameInfo.Number, true);
1691 Asm->EOL("Length of Frame Information Entry");
1692
1693 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
1694
1695 EmitSectionOffset("debug_frame_common", "section_debug_frame",
1696 0, 0, true, false);
1697 Asm->EOL("FDE CIE offset");
1698
1699 EmitReference("func_begin", DebugFrameInfo.Number);
1700 Asm->EOL("FDE initial location");
1701 EmitDifference("func_end", DebugFrameInfo.Number,
1702 "func_begin", DebugFrameInfo.Number);
1703 Asm->EOL("FDE address range");
1704
1705 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
1706 false);
1707
1708 Asm->EmitAlignment(2, 0, 0, false);
1709 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
1710
1711 Asm->EOL();
1712}
1713
1714void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
1715 EmitDifference("pubnames_end", Unit->getID(),
1716 "pubnames_begin", Unit->getID(), true);
1717 Asm->EOL("Length of Public Names Info");
1718
1719 EmitLabel("pubnames_begin", Unit->getID());
1720
1721 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
1722
1723 EmitSectionOffset("info_begin", "section_info",
1724 Unit->getID(), 0, true, false);
1725 Asm->EOL("Offset of Compilation Unit Info");
1726
1727 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
1728 true);
1729 Asm->EOL("Compilation Unit Length");
1730
1731 StringMap<DIE*> &Globals = Unit->getGlobals();
1732 for (StringMap<DIE*>::const_iterator
1733 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1734 const char *Name = GI->getKeyData();
1735 DIE * Entity = GI->second;
1736
1737 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
1738 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
1739 }
1740
1741 Asm->EmitInt32(0); Asm->EOL("End Mark");
1742 EmitLabel("pubnames_end", Unit->getID());
1743
1744 Asm->EOL();
1745}
1746
1747/// EmitDebugPubNames - Emit visible names into a debug pubnames section.
1748///
1749void DwarfDebug::EmitDebugPubNames() {
1750 // Start the dwarf pubnames section.
1751 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1752
1753 if (MainCU) {
1754 EmitDebugPubNamesPerCU(MainCU);
1755 return;
1756 }
1757
1758 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1759 EmitDebugPubNamesPerCU(CompileUnits[i]);
1760}
1761
1762/// EmitDebugStr - Emit visible names into a debug str section.
1763///
1764void DwarfDebug::EmitDebugStr() {
1765 // Check to see if it is worth the effort.
1766 if (!StringPool.empty()) {
1767 // Start the dwarf str section.
1768 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1769
1770 // For each of strings in the string pool.
1771 for (unsigned StringID = 1, N = StringPool.size();
1772 StringID <= N; ++StringID) {
1773 // Emit a label for reference from debug information entries.
1774 EmitLabel("string", StringID);
1775
1776 // Emit the string itself.
1777 const std::string &String = StringPool[StringID];
1778 Asm->EmitString(String); Asm->EOL();
1779 }
1780
1781 Asm->EOL();
1782 }
1783}
1784
1785/// EmitDebugLoc - Emit visible names into a debug loc section.
1786///
1787void DwarfDebug::EmitDebugLoc() {
1788 // Start the dwarf loc section.
1789 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1790 Asm->EOL();
1791}
1792
1793/// EmitDebugARanges - Emit visible names into a debug aranges section.
1794///
1795void DwarfDebug::EmitDebugARanges() {
1796 // Start the dwarf aranges section.
1797 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1798
1799 // FIXME - Mock up
1800#if 0
1801 CompileUnit *Unit = GetBaseCompileUnit();
1802
1803 // Don't include size of length
1804 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
1805
1806 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
1807
1808 EmitReference("info_begin", Unit->getID());
1809 Asm->EOL("Offset of Compilation Unit Info");
1810
1811 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
1812
1813 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
1814
1815 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
1816 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
1817
1818 // Range 1
1819 EmitReference("text_begin", 0); Asm->EOL("Address");
1820 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
1821
1822 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
1823 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
1824#endif
1825
1826 Asm->EOL();
1827}
1828
1829/// EmitDebugRanges - Emit visible names into a debug ranges section.
1830///
1831void DwarfDebug::EmitDebugRanges() {
1832 // Start the dwarf ranges section.
1833 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1834 Asm->EOL();
1835}
1836
1837/// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
1838///
1839void DwarfDebug::EmitDebugMacInfo() {
1840 if (TAI->doesSupportMacInfoSection()) {
1841 // Start the dwarf macinfo section.
1842 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1843 Asm->EOL();
1844 }
1845}
1846
1847/// EmitDebugInlineInfo - Emit inline info using following format.
1848/// Section Header:
1849/// 1. length of section
1850/// 2. Dwarf version number
1851/// 3. address size.
1852///
1853/// Entries (one "entry" for each function that was inlined):
1854///
1855/// 1. offset into __debug_str section for MIPS linkage name, if exists;
1856/// otherwise offset into __debug_str for regular function name.
1857/// 2. offset into __debug_str section for regular function name.
1858/// 3. an unsigned LEB128 number indicating the number of distinct inlining
1859/// instances for the function.
1860///
1861/// The rest of the entry consists of a {die_offset, low_pc} pair for each
1862/// inlined instance; the die_offset points to the inlined_subroutine die in the
1863/// __debug_info section, and the low_pc is the starting address for the
1864/// inlining instance.
1865void DwarfDebug::EmitDebugInlineInfo() {
1866 if (!TAI->doesDwarfUsesInlineInfoSection())
1867 return;
1868
1869 if (!MainCU)
1870 return;
1871
1872 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
1873 Asm->EOL();
1874 EmitDifference("debug_inlined_end", 1,
1875 "debug_inlined_begin", 1, true);
1876 Asm->EOL("Length of Debug Inlined Information Entry");
1877
1878 EmitLabel("debug_inlined_begin", 1);
1879
1880 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
1881 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1882
1883 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1884 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
1885 GlobalVariable *GV = I->first;
1886 SmallVector<unsigned, 4> &Labels = I->second;
1887 DISubprogram SP(GV);
1888 std::string Name;
1889 std::string LName;
1890
1891 SP.getLinkageName(LName);
1892 SP.getName(Name);
1893
1894 Asm->EmitString(LName.empty() ? Name : LName);
1895 Asm->EOL("MIPS linkage name");
1896
1897 Asm->EmitString(Name); Asm->EOL("Function name");
1898
1899 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
1900
1901 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
1902 LE = Labels.end(); LI != LE; ++LI) {
1903 DIE *SP = MainCU->getDieMapSlotFor(GV);
1904 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
1905
1906 if (TD->getPointerSize() == sizeof(int32_t))
1907 O << TAI->getData32bitsDirective();
1908 else
1909 O << TAI->getData64bitsDirective();
1910
1911 PrintLabelName("label", *LI); Asm->EOL("low_pc");
1912 }
1913 }
1914
1915 EmitLabel("debug_inlined_end", 1);
1916 Asm->EOL();
1917}
1918
1919/// GetOrCreateSourceID - Look up the source id with the given directory and
1920/// source file names. If none currently exists, create a new id and insert it
1921/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1922/// maps as well.
1923unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1924 const std::string &FileName) {
1925 unsigned DId;
1926 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1927 if (DI != DirectoryIdMap.end()) {
1928 DId = DI->getValue();
1929 } else {
1930 DId = DirectoryNames.size() + 1;
1931 DirectoryIdMap[DirName] = DId;
1932 DirectoryNames.push_back(DirName);
1933 }
1934
1935 unsigned FId;
1936 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1937 if (FI != SourceFileIdMap.end()) {
1938 FId = FI->getValue();
1939 } else {
1940 FId = SourceFileNames.size() + 1;
1941 SourceFileIdMap[FileName] = FId;
1942 SourceFileNames.push_back(FileName);
1943 }
1944
1945 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1946 SourceIdMap.find(std::make_pair(DId, FId));
1947 if (SI != SourceIdMap.end())
1948 return SI->second;
1949
1950 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1951 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1952 SourceIds.push_back(std::make_pair(DId, FId));
1953
1954 return SrcId;
1955}
1956
1957void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1958 DICompileUnit DIUnit(GV);
1959 std::string Dir, FN, Prod;
1960 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1961 DIUnit.getFilename(FN));
1962
1963 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1964 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1965 DWLabel("section_line", 0), DWLabel("section_line", 0),
1966 false);
1967 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1968 DIUnit.getProducer(Prod));
1969 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1970 DIUnit.getLanguage());
1971 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1972
1973 if (!Dir.empty())
1974 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1975 if (DIUnit.isOptimized())
1976 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1977
1978 std::string Flags;
1979 DIUnit.getFlags(Flags);
1980 if (!Flags.empty())
1981 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1982
1983 unsigned RVer = DIUnit.getRunTimeVersion();
1984 if (RVer)
1985 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1986 dwarf::DW_FORM_data1, RVer);
1987
1988 CompileUnit *Unit = new CompileUnit(ID, Die);
1989 if (DIUnit.isMain()) {
1990 assert(!MainCU && "Multiple main compile units are found!");
1991 MainCU = Unit;
1992 }
1993
1994 CompileUnitMap[DIUnit.getGV()] = Unit;
1995 CompileUnits.push_back(Unit);
1996}
1997
1998/// ConstructCompileUnits - Create a compile unit DIEs.
1999void DwarfDebug::ConstructCompileUnits() {
2000 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2001 if (!Root)
2002 return;
2003 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2004 "Malformed compile unit descriptor anchor type");
2005 Constant *RootC = cast<Constant>(*Root->use_begin());
2006 assert(RootC->hasNUsesOrMore(1) &&
2007 "Malformed compile unit descriptor anchor type");
2008
2009 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2010 UI != UE; ++UI)
2011 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2012 UUI != UUE; ++UUI) {
2013 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2014 ConstructCompileUnit(GV);
2015 }
2016}
2017
2018bool DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
2019 DIGlobalVariable DI_GV(GV);
2020 CompileUnit *DW_Unit = MainCU;
2021 if (!DW_Unit)
2022 DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
2023
2024 // Check for pre-existence.
2025 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2026 if (Slot)
2027 return false;
2028
2029 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2030
2031 // Add address.
2032 DIEBlock *Block = new DIEBlock();
2033 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
2034 std::string GLN;
2035 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
2036 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
2037 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
2038
2039 // Add to map.
2040 Slot = VariableDie;
2041
2042 // Add to context owner.
2043 DW_Unit->getDie()->AddChild(VariableDie);
2044
2045 // Expose as global. FIXME - need to check external flag.
2046 std::string Name;
2047 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2048 return true;
2049}
2050
2051/// ConstructGlobalVariableDIEs - Create DIEs for each of the externally visible
2052/// global variables. Return true if at least one global DIE is created.
2053bool DwarfDebug::ConstructGlobalVariableDIEs() {
2054 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2055 if (!Root)
2056 return false;
2057
2058 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2059 "Malformed global variable descriptor anchor type");
2060 Constant *RootC = cast<Constant>(*Root->use_begin());
2061 assert(RootC->hasNUsesOrMore(1) &&
2062 "Malformed global variable descriptor anchor type");
2063
2064 bool Result = false;
2065 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2066 UI != UE; ++UI)
2067 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2068 UUI != UUE; ++UUI)
2069 Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
2070
2071 return Result;
2072}
2073
2074bool DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
2075 DISubprogram SP(GV);
2076 CompileUnit *Unit = MainCU;
2077 if (!Unit)
2078 Unit = &FindCompileUnit(SP.getCompileUnit());
2079
2080 // Check for pre-existence.
2081 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2082 if (Slot)
2083 return false;
2084
2085 if (!SP.isDefinition())
2086 // This is a method declaration which will be handled while constructing
2087 // class type.
2088 return false;
2089
2090 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2091
2092 // Add to map.
2093 Slot = SubprogramDie;
2094
2095 // Add to context owner.
2096 Unit->getDie()->AddChild(SubprogramDie);
2097
2098 // Expose as global.
2099 std::string Name;
2100 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2101 return true;
2102}
2103
2104/// ConstructSubprograms - Create DIEs for each of the externally visible
2105/// subprograms. Return true if at least one subprogram DIE is created.
2106bool DwarfDebug::ConstructSubprograms() {
2107 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2108 if (!Root)
2109 return false;
2110
2111 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2112 "Malformed subprogram descriptor anchor type");
2113 Constant *RootC = cast<Constant>(*Root->use_begin());
2114 assert(RootC->hasNUsesOrMore(1) &&
2115 "Malformed subprogram descriptor anchor type");
2116
2117 bool Result = false;
2118 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2119 UI != UE; ++UI)
2120 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2121 UUI != UUE; ++UUI)
2122 Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
2123
2124 return Result;
2125}
2126
2127/// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2128/// This is inovked by the target AsmPrinter.
2129void DwarfDebug::SetDebugInfo(MachineModuleInfo *mmi) {
2130 if (TimePassesIsEnabled)
2131 DebugTimer->startTimer();
2132
2133 // Create all the compile unit DIEs.
2134 ConstructCompileUnits();
2135
2136 if (CompileUnits.empty()) {
2137 if (TimePassesIsEnabled)
2138 DebugTimer->stopTimer();
2139
2140 return;
2141 }
2142
2143 // Create DIEs for each of the externally visible global variables.
2144 bool globalDIEs = ConstructGlobalVariableDIEs();
2145
2146 // Create DIEs for each of the externally visible subprograms.
2147 bool subprogramDIEs = ConstructSubprograms();
2148
2149 // If there is not any debug info available for any global variables and any
2150 // subprograms then there is not any debug info to emit.
2151 if (!globalDIEs && !subprogramDIEs) {
2152 if (TimePassesIsEnabled)
2153 DebugTimer->stopTimer();
2154
2155 return;
2156 }
2157
2158 MMI = mmi;
2159 shouldEmit = true;
2160 MMI->setDebugInfoAvailability(true);
2161
2162 // Prime section data.
2163 SectionMap.insert(TAI->getTextSection());
2164
2165 // Print out .file directives to specify files for .loc directives. These are
2166 // printed out early so that they precede any .loc directives.
2167 if (TAI->hasDotLocAndDotFile()) {
2168 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2169 // Remember source id starts at 1.
2170 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2171 sys::Path FullPath(getSourceDirectoryName(Id.first));
2172 bool AppendOk =
2173 FullPath.appendComponent(getSourceFileName(Id.second));
2174 assert(AppendOk && "Could not append filename to directory!");
2175 AppendOk = false;
2176 Asm->EmitFile(i, FullPath.toString());
2177 Asm->EOL();
2178 }
2179 }
2180
2181 // Emit initial sections
2182 EmitInitial();
2183
2184 if (TimePassesIsEnabled)
2185 DebugTimer->stopTimer();
2186}
2187
2188/// EndModule - Emit all Dwarf sections that should come after the content.
2189///
2190void DwarfDebug::EndModule() {
2191 if (!ShouldEmitDwarfDebug())
2192 return;
2193
2194 if (TimePassesIsEnabled)
2195 DebugTimer->startTimer();
2196
2197 // Standard sections final addresses.
2198 Asm->SwitchToSection(TAI->getTextSection());
2199 EmitLabel("text_end", 0);
2200 Asm->SwitchToSection(TAI->getDataSection());
2201 EmitLabel("data_end", 0);
2202
2203 // End text sections.
2204 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2205 Asm->SwitchToSection(SectionMap[i]);
2206 EmitLabel("section_end", i);
2207 }
2208
2209 // Emit common frame information.
2210 EmitCommonDebugFrame();
2211
2212 // Emit function debug frame information
2213 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2214 E = DebugFrames.end(); I != E; ++I)
2215 EmitFunctionDebugFrame(*I);
2216
2217 // Compute DIE offsets and sizes.
2218 SizeAndOffsets();
2219
2220 // Emit all the DIEs into a debug info section
2221 EmitDebugInfo();
2222
2223 // Corresponding abbreviations into a abbrev section.
2224 EmitAbbreviations();
2225
2226 // Emit source line correspondence into a debug line section.
2227 EmitDebugLines();
2228
2229 // Emit info into a debug pubnames section.
2230 EmitDebugPubNames();
2231
2232 // Emit info into a debug str section.
2233 EmitDebugStr();
2234
2235 // Emit info into a debug loc section.
2236 EmitDebugLoc();
2237
2238 // Emit info into a debug aranges section.
2239 EmitDebugARanges();
2240
2241 // Emit info into a debug ranges section.
2242 EmitDebugRanges();
2243
2244 // Emit info into a debug macinfo section.
2245 EmitDebugMacInfo();
2246
2247 // Emit inline info.
2248 EmitDebugInlineInfo();
2249
2250 if (TimePassesIsEnabled)
2251 DebugTimer->stopTimer();
2252}
2253
2254/// BeginFunction - Gather pre-function debug information. Assumes being
2255/// emitted immediately after the function entry point.
2256void DwarfDebug::BeginFunction(MachineFunction *MF) {
2257 this->MF = MF;
2258
2259 if (!ShouldEmitDwarfDebug()) return;
2260
2261 if (TimePassesIsEnabled)
2262 DebugTimer->startTimer();
2263
2264 // Begin accumulating function debug information.
2265 MMI->BeginFunction(MF);
2266
2267 // Assumes in correct section after the entry point.
2268 EmitLabel("func_begin", ++SubprogramCount);
2269
2270 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2271 // function.
2272 DebugLoc FDL = MF->getDefaultDebugLoc();
2273 if (!FDL.isUnknown()) {
2274 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2275 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
2276 DICompileUnit(DLT.CompileUnit));
2277 Asm->printLabel(LabelID);
2278 }
2279
2280 if (TimePassesIsEnabled)
2281 DebugTimer->stopTimer();
2282}
2283
2284/// EndFunction - Gather and emit post-function debug information.
2285///
2286void DwarfDebug::EndFunction(MachineFunction *MF) {
2287 if (!ShouldEmitDwarfDebug()) return;
2288
2289 if (TimePassesIsEnabled)
2290 DebugTimer->startTimer();
2291
2292 // Define end label for subprogram.
2293 EmitLabel("func_end", SubprogramCount);
2294
2295 // Get function line info.
2296 if (!Lines.empty()) {
2297 // Get section line info.
2298 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2299 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2300 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2301 // Append the function info to section info.
2302 SectionLineInfos.insert(SectionLineInfos.end(),
2303 Lines.begin(), Lines.end());
2304 }
2305
2306 // Construct the DbgScope for abstract instances.
2307 for (SmallVector<DbgScope *, 32>::iterator
2308 I = AbstractInstanceRootList.begin(),
2309 E = AbstractInstanceRootList.end(); I != E; ++I)
2310 ConstructAbstractDbgScope(*I);
2311
2312 // Construct scopes for subprogram.
2313 if (FunctionDbgScope)
2314 ConstructFunctionDbgScope(FunctionDbgScope);
2315 else
2316 // FIXME: This is wrong. We are essentially getting past a problem with
2317 // debug information not being able to handle unreachable blocks that have
2318 // debug information in them. In particular, those unreachable blocks that
2319 // have "region end" info in them. That situation results in the "root
2320 // scope" not being created. If that's the case, then emit a "default"
2321 // scope, i.e., one that encompasses the whole function. This isn't
2322 // desirable. And a better way of handling this (and all of the debugging
2323 // information) needs to be explored.
2324 ConstructDefaultDbgScope(MF);
2325
2326 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2327 MMI->getFrameMoves()));
2328
2329 // Clear debug info
2330 if (FunctionDbgScope) {
2331 delete FunctionDbgScope;
2332 DbgScopeMap.clear();
2333 DbgAbstractScopeMap.clear();
2334 DbgConcreteScopeMap.clear();
2335 InlinedVariableScopes.clear();
2336 FunctionDbgScope = NULL;
2337 LexicalScopeStack.clear();
2338 AbstractInstanceRootList.clear();
2339 }
2340
2341 Lines.clear();
2342
2343 if (TimePassesIsEnabled)
2344 DebugTimer->stopTimer();
2345}
2346
2347/// RecordSourceLine - Records location information and associates it with a
2348/// label. Returns a unique label ID used to generate a label and provide
2349/// correspondence to the source line list.
2350unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2351 if (TimePassesIsEnabled)
2352 DebugTimer->startTimer();
2353
2354 CompileUnit *Unit = CompileUnitMap[V];
2355 assert(Unit && "Unable to find CompileUnit");
2356 unsigned ID = MMI->NextLabelID();
2357 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2358
2359 if (TimePassesIsEnabled)
2360 DebugTimer->stopTimer();
2361
2362 return ID;
2363}
2364
2365/// RecordSourceLine - Records location information and associates it with a
2366/// label. Returns a unique label ID used to generate a label and provide
2367/// correspondence to the source line list.
2368unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
2369 DICompileUnit CU) {
2370 if (TimePassesIsEnabled)
2371 DebugTimer->startTimer();
2372
2373 std::string Dir, Fn;
2374 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
2375 CU.getFilename(Fn));
2376 unsigned ID = MMI->NextLabelID();
2377 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2378
2379 if (TimePassesIsEnabled)
2380 DebugTimer->stopTimer();
2381
2382 return ID;
2383}
2384
2385/// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2386/// timed. Look up the source id with the given directory and source file
2387/// names. If none currently exists, create a new id and insert it in the
2388/// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2389/// well.
2390unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2391 const std::string &FileName) {
2392 if (TimePassesIsEnabled)
2393 DebugTimer->startTimer();
2394
2395 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
2396
2397 if (TimePassesIsEnabled)
2398 DebugTimer->stopTimer();
2399
2400 return SrcId;
2401}
2402
2403/// RecordRegionStart - Indicate the start of a region.
2404unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
2405 if (TimePassesIsEnabled)
2406 DebugTimer->startTimer();
2407
2408 DbgScope *Scope = getOrCreateScope(V);
2409 unsigned ID = MMI->NextLabelID();
2410 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2411 LexicalScopeStack.push_back(Scope);
2412
2413 if (TimePassesIsEnabled)
2414 DebugTimer->stopTimer();
2415
2416 return ID;
2417}
2418
2419/// RecordRegionEnd - Indicate the end of a region.
2420unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
2421 if (TimePassesIsEnabled)
2422 DebugTimer->startTimer();
2423
2424 DbgScope *Scope = getOrCreateScope(V);
2425 unsigned ID = MMI->NextLabelID();
2426 Scope->setEndLabelID(ID);
2427 if (LexicalScopeStack.size() != 0)
2428 LexicalScopeStack.pop_back();
2429
2430 if (TimePassesIsEnabled)
2431 DebugTimer->stopTimer();
2432
2433 return ID;
2434}
2435
Bill Wendling6679ee42009-05-18 22:02:36 +00002436/// RecordVariable - Indicate the declaration of a local variable.
Bill Wendling0310d762009-05-15 09:23:25 +00002437void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
2438 const MachineInstr *MI) {
2439 if (TimePassesIsEnabled)
2440 DebugTimer->startTimer();
2441
2442 DIDescriptor Desc(GV);
2443 DbgScope *Scope = NULL;
Bill Wendling1180c782009-05-18 23:08:55 +00002444 bool InlinedFnVar = false;
Bill Wendling0310d762009-05-15 09:23:25 +00002445
2446 if (Desc.getTag() == dwarf::DW_TAG_variable) {
2447 // GV is a global variable.
2448 DIGlobalVariable DG(GV);
2449 Scope = getOrCreateScope(DG.getContext().getGV());
2450 } else {
2451 DenseMap<const MachineInstr *, DbgScope *>::iterator
2452 SI = InlinedVariableScopes.find(MI);
2453
2454 if (SI != InlinedVariableScopes.end()) {
2455 // or GV is an inlined local variable.
2456 Scope = SI->second;
2457 } else {
2458 DIVariable DV(GV);
2459 GlobalVariable *V = DV.getContext().getGV();
2460
2461 // FIXME: The code that checks for the inlined local variable is a hack!
2462 DenseMap<const GlobalVariable *, DbgScope *>::iterator
2463 AI = AbstractInstanceRootMap.find(V);
2464
Bill Wendling6679ee42009-05-18 22:02:36 +00002465 if (AI != AbstractInstanceRootMap.end()) {
2466 // This method is called each time a DECLARE node is encountered. For an
2467 // inlined function, this could be many, many times. We don't want to
2468 // re-add variables to that DIE for each time. We just want to add them
2469 // once. Check to make sure that we haven't added them already.
2470 DenseMap<const GlobalVariable *,
2471 SmallSet<const GlobalVariable *, 32> >::iterator
2472 IP = InlinedParamMap.find(V);
2473
Bill Wendlingcde5d632009-05-18 22:33:01 +00002474 if (IP != InlinedParamMap.end() && IP->second.count(GV) > 0) {
2475 if (TimePassesIsEnabled)
2476 DebugTimer->stopTimer();
2477 return;
Bill Wendling6679ee42009-05-18 22:02:36 +00002478 }
2479
Bill Wendling0310d762009-05-15 09:23:25 +00002480 // or GV is an inlined local variable.
2481 Scope = AI->second;
Bill Wendling6679ee42009-05-18 22:02:36 +00002482 InlinedParamMap[V].insert(GV);
Bill Wendling1180c782009-05-18 23:08:55 +00002483 InlinedFnVar = true;
Bill Wendling6679ee42009-05-18 22:02:36 +00002484 } else {
Bill Wendling0310d762009-05-15 09:23:25 +00002485 // or GV is a local variable.
2486 Scope = getOrCreateScope(V);
Bill Wendling6679ee42009-05-18 22:02:36 +00002487 }
Bill Wendling0310d762009-05-15 09:23:25 +00002488 }
2489 }
2490
2491 assert(Scope && "Unable to find the variable's scope");
Bill Wendling1180c782009-05-18 23:08:55 +00002492 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex, InlinedFnVar);
Bill Wendling0310d762009-05-15 09:23:25 +00002493 Scope->AddVariable(DV);
2494
2495 if (TimePassesIsEnabled)
2496 DebugTimer->stopTimer();
2497}
2498
2499//// RecordInlinedFnStart - Indicate the start of inlined subroutine.
2500unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
2501 unsigned Line, unsigned Col) {
2502 unsigned LabelID = MMI->NextLabelID();
2503
2504 if (!TAI->doesDwarfUsesInlineInfoSection())
2505 return LabelID;
2506
2507 if (TimePassesIsEnabled)
2508 DebugTimer->startTimer();
2509
2510 GlobalVariable *GV = SP.getGV();
2511 DenseMap<const GlobalVariable *, DbgScope *>::iterator
2512 II = AbstractInstanceRootMap.find(GV);
2513
2514 if (II == AbstractInstanceRootMap.end()) {
2515 // Create an abstract instance entry for this inlined function if it doesn't
2516 // already exist.
2517 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
2518
2519 // Get the compile unit context.
2520 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2521 DIE *SPDie = Unit->getDieMapSlotFor(GV);
2522 if (!SPDie)
Bill Wendling6679ee42009-05-18 22:02:36 +00002523 SPDie = CreateSubprogramDIE(Unit, SP, false, true);
Bill Wendling0310d762009-05-15 09:23:25 +00002524
2525 // Mark as being inlined. This makes this subprogram entry an abstract
2526 // instance root.
2527 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
Bill Wendling6679ee42009-05-18 22:02:36 +00002528 // that it's defined. That probably won't change in the future. However,
2529 // this could be more elegant.
Bill Wendling0310d762009-05-15 09:23:25 +00002530 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
2531
2532 // Keep track of the abstract scope for this function.
2533 DbgAbstractScopeMap[GV] = Scope;
2534
2535 AbstractInstanceRootMap[GV] = Scope;
2536 AbstractInstanceRootList.push_back(Scope);
2537 }
2538
2539 // Create a concrete inlined instance for this inlined function.
2540 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
2541 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
2542 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2543 ScopeDie->setAbstractCompileUnit(Unit);
2544
2545 DIE *Origin = Unit->getDieMapSlotFor(GV);
2546 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
2547 dwarf::DW_FORM_ref4, Origin);
2548 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, Unit->getID());
2549 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
2550 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
2551
2552 ConcreteScope->setDie(ScopeDie);
2553 ConcreteScope->setStartLabelID(LabelID);
2554 MMI->RecordUsedDbgLabel(LabelID);
2555
2556 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
2557
2558 // Keep track of the concrete scope that's inlined into this function.
2559 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2560 SI = DbgConcreteScopeMap.find(GV);
2561
2562 if (SI == DbgConcreteScopeMap.end())
2563 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
2564 else
2565 SI->second.push_back(ConcreteScope);
2566
2567 // Track the start label for this inlined function.
2568 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2569 I = InlineInfo.find(GV);
2570
2571 if (I == InlineInfo.end())
2572 InlineInfo[GV].push_back(LabelID);
2573 else
2574 I->second.push_back(LabelID);
2575
2576 if (TimePassesIsEnabled)
2577 DebugTimer->stopTimer();
2578
2579 return LabelID;
2580}
2581
2582/// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2583unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
2584 if (!TAI->doesDwarfUsesInlineInfoSection())
2585 return 0;
2586
2587 if (TimePassesIsEnabled)
2588 DebugTimer->startTimer();
2589
2590 GlobalVariable *GV = SP.getGV();
2591 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2592 I = DbgConcreteScopeMap.find(GV);
2593
2594 if (I == DbgConcreteScopeMap.end()) {
Bill Wendling6679ee42009-05-18 22:02:36 +00002595 // FIXME: Can this situation actually happen? And if so, should it?
Bill Wendling0310d762009-05-15 09:23:25 +00002596 if (TimePassesIsEnabled)
2597 DebugTimer->stopTimer();
2598
2599 return 0;
2600 }
2601
2602 SmallVector<DbgScope *, 8> &Scopes = I->second;
2603 assert(!Scopes.empty() && "We should have at least one debug scope!");
2604 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
2605 unsigned ID = MMI->NextLabelID();
2606 MMI->RecordUsedDbgLabel(ID);
2607 Scope->setEndLabelID(ID);
2608
2609 if (TimePassesIsEnabled)
2610 DebugTimer->stopTimer();
2611
2612 return ID;
2613}
2614
2615/// RecordVariableScope - Record scope for the variable declared by
2616/// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
2617/// for only inlined subroutine variables. Other variables's scopes are
2618/// determined during RecordVariable().
2619void DwarfDebug::RecordVariableScope(DIVariable &DV,
2620 const MachineInstr *DeclareMI) {
2621 if (TimePassesIsEnabled)
2622 DebugTimer->startTimer();
2623
2624 DISubprogram SP(DV.getContext().getGV());
2625
2626 if (SP.isNull()) {
2627 if (TimePassesIsEnabled)
2628 DebugTimer->stopTimer();
2629
2630 return;
2631 }
2632
2633 DenseMap<GlobalVariable *, DbgScope *>::iterator
2634 I = DbgAbstractScopeMap.find(SP.getGV());
2635 if (I != DbgAbstractScopeMap.end())
2636 InlinedVariableScopes[DeclareMI] = I->second;
2637
2638 if (TimePassesIsEnabled)
2639 DebugTimer->stopTimer();
2640}