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