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