blob: eedf5c1d32c1bc5a7e7652fb60be396adf7a9039 [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"
Chris Lattnera87dea42009-07-31 18:48:30 +000017#include "llvm/MC/MCSection.h"
Chris Lattner6c2f9e12009-08-19 05:49:37 +000018#include "llvm/MC/MCStreamer.h"
Bill Wendling0310d762009-05-15 09:23:25 +000019#include "llvm/Target/TargetAsmInfo.h"
Bill Wendling0310d762009-05-15 09:23:25 +000020#include "llvm/Target/TargetData.h"
21#include "llvm/Target/TargetFrameInfo.h"
Chris Lattnerf0144122009-07-28 03:13:23 +000022#include "llvm/Target/TargetLoweringObjectFile.h"
23#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattnera87dea42009-07-31 18:48:30 +000024#include "llvm/Support/Timer.h"
25#include "llvm/System/Path.h"
Bill Wendling0310d762009-05-15 09:23:25 +000026using namespace llvm;
27
28static TimerGroup &getDwarfTimerGroup() {
29 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
30 return DwarfTimerGroup;
31}
32
33//===----------------------------------------------------------------------===//
34
35/// Configuration values for initial hash set sizes (log2).
36///
37static const unsigned InitDiesSetSize = 9; // log2(512)
38static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
39static const unsigned InitValuesSetSize = 9; // log2(512)
40
41namespace llvm {
42
43//===----------------------------------------------------------------------===//
44/// CompileUnit - This dwarf writer support class manages information associate
45/// with a source file.
46class VISIBILITY_HIDDEN CompileUnit {
47 /// ID - File identifier for source.
48 ///
49 unsigned ID;
50
51 /// Die - Compile unit debug information entry.
52 ///
53 DIE *Die;
54
55 /// GVToDieMap - Tracks the mapping of unit level debug informaton
56 /// variables to debug information entries.
57 std::map<GlobalVariable *, DIE *> GVToDieMap;
58
59 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
60 /// descriptors to debug information entries using a DIEEntry proxy.
61 std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
62
63 /// Globals - A map of globally visible named entities for this unit.
64 ///
65 StringMap<DIE*> Globals;
66
67 /// DiesSet - Used to uniquely define dies within the compile unit.
68 ///
69 FoldingSet<DIE> DiesSet;
70public:
71 CompileUnit(unsigned I, DIE *D)
Bill Wendling39dd6962009-05-20 23:31:45 +000072 : ID(I), Die(D), DiesSet(InitDiesSetSize) {}
73 ~CompileUnit() { delete Die; }
Bill Wendling0310d762009-05-15 09:23:25 +000074
75 // Accessors.
Bill Wendling39dd6962009-05-20 23:31:45 +000076 unsigned getID() const { return ID; }
77 DIE* getDie() const { return Die; }
Bill Wendling0310d762009-05-15 09:23:25 +000078 StringMap<DIE*> &getGlobals() { return Globals; }
79
80 /// hasContent - Return true if this compile unit has something to write out.
81 ///
Bill Wendling39dd6962009-05-20 23:31:45 +000082 bool hasContent() const { return !Die->getChildren().empty(); }
Bill Wendling0310d762009-05-15 09:23:25 +000083
84 /// AddGlobal - Add a new global entity to the compile unit.
85 ///
Bill Wendling39dd6962009-05-20 23:31:45 +000086 void AddGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
Bill Wendling0310d762009-05-15 09:23:25 +000087
88 /// getDieMapSlotFor - Returns the debug information entry map slot for the
89 /// specified debug variable.
Bill Wendling39dd6962009-05-20 23:31:45 +000090 DIE *&getDieMapSlotFor(GlobalVariable *GV) { return GVToDieMap[GV]; }
Bill Wendling0310d762009-05-15 09:23:25 +000091
Chris Lattner1cda87c2009-07-14 04:50:12 +000092 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for
93 /// the specified debug variable.
Bill Wendling0310d762009-05-15 09:23:25 +000094 DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
95 return GVToDIEEntryMap[GV];
96 }
97
98 /// AddDie - Adds or interns the DIE to the compile unit.
99 ///
100 DIE *AddDie(DIE &Buffer) {
101 FoldingSetNodeID ID;
102 Buffer.Profile(ID);
103 void *Where;
104 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
105
106 if (!Die) {
107 Die = new DIE(Buffer);
108 DiesSet.InsertNode(Die, Where);
109 this->Die->AddChild(Die);
110 Buffer.Detach();
111 }
112
113 return Die;
114 }
115};
116
117//===----------------------------------------------------------------------===//
118/// DbgVariable - This class is used to track local variable information.
119///
120class VISIBILITY_HIDDEN DbgVariable {
121 DIVariable Var; // Variable Descriptor.
122 unsigned FrameIndex; // Variable frame index.
Bill Wendling1180c782009-05-18 23:08:55 +0000123 bool InlinedFnVar; // Variable for an inlined function.
Bill Wendling0310d762009-05-15 09:23:25 +0000124public:
Bill Wendling1180c782009-05-18 23:08:55 +0000125 DbgVariable(DIVariable V, unsigned I, bool IFV)
126 : Var(V), FrameIndex(I), InlinedFnVar(IFV) {}
Bill Wendling0310d762009-05-15 09:23:25 +0000127
128 // Accessors.
Bill Wendling1180c782009-05-18 23:08:55 +0000129 DIVariable getVariable() const { return Var; }
Bill Wendling0310d762009-05-15 09:23:25 +0000130 unsigned getFrameIndex() const { return FrameIndex; }
Bill Wendling1180c782009-05-18 23:08:55 +0000131 bool isInlinedFnVar() const { return InlinedFnVar; }
Bill Wendling0310d762009-05-15 09:23:25 +0000132};
133
134//===----------------------------------------------------------------------===//
135/// DbgScope - This class is used to track scope information.
136///
137class DbgConcreteScope;
138class VISIBILITY_HIDDEN DbgScope {
139 DbgScope *Parent; // Parent to this scope.
140 DIDescriptor Desc; // Debug info descriptor for scope.
141 // Either subprogram or block.
142 unsigned StartLabelID; // Label ID of the beginning of scope.
143 unsigned EndLabelID; // Label ID of the end of scope.
144 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
145 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
146 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
Owen Anderson04c05f72009-06-24 22:53:20 +0000147
148 // Private state for dump()
149 mutable unsigned IndentLevel;
Bill Wendling0310d762009-05-15 09:23:25 +0000150public:
151 DbgScope(DbgScope *P, DIDescriptor D)
Owen Anderson04c05f72009-06-24 22:53:20 +0000152 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), IndentLevel(0) {}
Bill Wendling0310d762009-05-15 09:23:25 +0000153 virtual ~DbgScope();
154
155 // Accessors.
156 DbgScope *getParent() const { return Parent; }
157 DIDescriptor getDesc() const { return Desc; }
158 unsigned getStartLabelID() const { return StartLabelID; }
159 unsigned getEndLabelID() const { return EndLabelID; }
160 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
161 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
162 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
163 void setStartLabelID(unsigned S) { StartLabelID = S; }
164 void setEndLabelID(unsigned E) { EndLabelID = E; }
165
166 /// AddScope - Add a scope to the scope.
167 ///
168 void AddScope(DbgScope *S) { Scopes.push_back(S); }
169
170 /// AddVariable - Add a variable to the scope.
171 ///
172 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
173
174 /// AddConcreteInst - Add a concrete instance to the scope.
175 ///
176 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
177
178#ifndef NDEBUG
179 void dump() const;
180#endif
181};
182
183#ifndef NDEBUG
184void DbgScope::dump() const {
Bill Wendling0310d762009-05-15 09:23:25 +0000185 std::string Indent(IndentLevel, ' ');
186
187 cerr << Indent; Desc.dump();
188 cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
189
190 IndentLevel += 2;
191
192 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
193 if (Scopes[i] != this)
194 Scopes[i]->dump();
195
196 IndentLevel -= 2;
197}
198#endif
199
200//===----------------------------------------------------------------------===//
201/// DbgConcreteScope - This class is used to track a scope that holds concrete
202/// instance information.
203///
204class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
205 CompileUnit *Unit;
206 DIE *Die; // Debug info for this concrete scope.
207public:
208 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
209
210 // Accessors.
211 DIE *getDie() const { return Die; }
212 void setDie(DIE *D) { Die = D; }
213};
214
215DbgScope::~DbgScope() {
216 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
217 delete Scopes[i];
218 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
219 delete Variables[j];
220 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
221 delete ConcreteInsts[k];
222}
223
224} // end llvm namespace
225
226DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
Devang Patel1dbc7712009-06-29 20:45:18 +0000227 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
Bill Wendling0310d762009-05-15 09:23:25 +0000228 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
Chris Lattnera87dea42009-07-31 18:48:30 +0000229 ValuesSet(InitValuesSetSize), Values(), StringPool(),
Bill Wendling0310d762009-05-15 09:23:25 +0000230 SectionSourceLines(), didInitial(false), shouldEmit(false),
Devang Patel43da8fb2009-07-13 21:26:33 +0000231 FunctionDbgScope(0), DebugTimer(0) {
Bill Wendling0310d762009-05-15 09:23:25 +0000232 if (TimePassesIsEnabled)
233 DebugTimer = new Timer("Dwarf Debug Writer",
234 getDwarfTimerGroup());
235}
236DwarfDebug::~DwarfDebug() {
237 for (unsigned j = 0, M = Values.size(); j < M; ++j)
238 delete Values[j];
239
240 for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
241 I = AbstractInstanceRootMap.begin(),
242 E = AbstractInstanceRootMap.end(); I != E;++I)
243 delete I->second;
244
245 delete DebugTimer;
246}
247
248/// AssignAbbrevNumber - Define a unique number for the abbreviation.
249///
250void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
251 // Profile the node so that we can make it unique.
252 FoldingSetNodeID ID;
253 Abbrev.Profile(ID);
254
255 // Check the set for priors.
256 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
257
258 // If it's newly added.
259 if (InSet == &Abbrev) {
260 // Add to abbreviation list.
261 Abbreviations.push_back(&Abbrev);
262
263 // Assign the vector position + 1 as its number.
264 Abbrev.setNumber(Abbreviations.size());
265 } else {
266 // Assign existing abbreviation number.
267 Abbrev.setNumber(InSet->getNumber());
268 }
269}
270
Bill Wendling995f80a2009-05-20 23:24:48 +0000271/// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
272/// information entry.
273DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
Bill Wendling0310d762009-05-15 09:23:25 +0000274 DIEEntry *Value;
275
276 if (Entry) {
277 FoldingSetNodeID ID;
278 DIEEntry::Profile(ID, Entry);
279 void *Where;
280 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
281
282 if (Value) return Value;
283
284 Value = new DIEEntry(Entry);
285 ValuesSet.InsertNode(Value, Where);
286 } else {
287 Value = new DIEEntry(Entry);
288 }
289
290 Values.push_back(Value);
291 return Value;
292}
293
294/// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
295///
296void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
297 Value->setEntry(Entry);
298
299 // Add to values set if not already there. If it is, we merely have a
300 // duplicate in the values list (no harm.)
301 ValuesSet.GetOrInsertNode(Value);
302}
303
304/// AddUInt - Add an unsigned integer attribute data and value.
305///
306void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
307 unsigned Form, uint64_t Integer) {
308 if (!Form) Form = DIEInteger::BestForm(false, Integer);
309
310 FoldingSetNodeID ID;
311 DIEInteger::Profile(ID, Integer);
312 void *Where;
313 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
314
315 if (!Value) {
316 Value = new DIEInteger(Integer);
317 ValuesSet.InsertNode(Value, Where);
318 Values.push_back(Value);
319 }
320
321 Die->AddValue(Attribute, Form, Value);
322}
323
324/// AddSInt - Add an signed integer attribute data and value.
325///
326void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
327 unsigned Form, int64_t Integer) {
328 if (!Form) Form = DIEInteger::BestForm(true, Integer);
329
330 FoldingSetNodeID ID;
331 DIEInteger::Profile(ID, (uint64_t)Integer);
332 void *Where;
333 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
334
335 if (!Value) {
336 Value = new DIEInteger(Integer);
337 ValuesSet.InsertNode(Value, Where);
338 Values.push_back(Value);
339 }
340
341 Die->AddValue(Attribute, Form, Value);
342}
343
344/// AddString - Add a string attribute data and value.
345///
346void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
347 const std::string &String) {
348 FoldingSetNodeID ID;
349 DIEString::Profile(ID, String);
350 void *Where;
351 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
352
353 if (!Value) {
354 Value = new DIEString(String);
355 ValuesSet.InsertNode(Value, Where);
356 Values.push_back(Value);
357 }
358
359 Die->AddValue(Attribute, Form, Value);
360}
361
362/// AddLabel - Add a Dwarf label attribute data and value.
363///
364void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
365 const DWLabel &Label) {
366 FoldingSetNodeID ID;
367 DIEDwarfLabel::Profile(ID, Label);
368 void *Where;
369 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
370
371 if (!Value) {
372 Value = new DIEDwarfLabel(Label);
373 ValuesSet.InsertNode(Value, Where);
374 Values.push_back(Value);
375 }
376
377 Die->AddValue(Attribute, Form, Value);
378}
379
380/// AddObjectLabel - Add an non-Dwarf label attribute data and value.
381///
382void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
383 const std::string &Label) {
384 FoldingSetNodeID ID;
385 DIEObjectLabel::Profile(ID, Label);
386 void *Where;
387 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
388
389 if (!Value) {
390 Value = new DIEObjectLabel(Label);
391 ValuesSet.InsertNode(Value, Where);
392 Values.push_back(Value);
393 }
394
395 Die->AddValue(Attribute, Form, Value);
396}
397
398/// AddSectionOffset - Add a section offset label attribute data and value.
399///
400void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
401 const DWLabel &Label, const DWLabel &Section,
402 bool isEH, bool useSet) {
403 FoldingSetNodeID ID;
404 DIESectionOffset::Profile(ID, Label, Section);
405 void *Where;
406 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
407
408 if (!Value) {
409 Value = new DIESectionOffset(Label, Section, isEH, useSet);
410 ValuesSet.InsertNode(Value, Where);
411 Values.push_back(Value);
412 }
413
414 Die->AddValue(Attribute, Form, Value);
415}
416
417/// AddDelta - Add a label delta attribute data and value.
418///
419void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
420 const DWLabel &Hi, const DWLabel &Lo) {
421 FoldingSetNodeID ID;
422 DIEDelta::Profile(ID, Hi, Lo);
423 void *Where;
424 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
425
426 if (!Value) {
427 Value = new DIEDelta(Hi, Lo);
428 ValuesSet.InsertNode(Value, Where);
429 Values.push_back(Value);
430 }
431
432 Die->AddValue(Attribute, Form, Value);
433}
434
435/// AddBlock - Add block data.
436///
437void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
438 DIEBlock *Block) {
439 Block->ComputeSize(TD);
440 FoldingSetNodeID ID;
441 Block->Profile(ID);
442 void *Where;
443 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
444
445 if (!Value) {
446 Value = Block;
447 ValuesSet.InsertNode(Value, Where);
448 Values.push_back(Value);
449 } else {
450 // Already exists, reuse the previous one.
451 delete Block;
452 Block = cast<DIEBlock>(Value);
453 }
454
455 Die->AddValue(Attribute, Block->BestForm(), Value);
456}
457
458/// AddSourceLine - Add location information to specified debug information
459/// entry.
460void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
461 // If there is no compile unit specified, don't add a line #.
462 if (V->getCompileUnit().isNull())
463 return;
464
465 unsigned Line = V->getLineNumber();
466 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
467 assert(FileID && "Invalid file id");
468 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
469 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
470}
471
472/// AddSourceLine - Add location information to specified debug information
473/// entry.
474void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
475 // If there is no compile unit specified, don't add a line #.
476 if (G->getCompileUnit().isNull())
477 return;
478
479 unsigned Line = G->getLineNumber();
480 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
481 assert(FileID && "Invalid file id");
482 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
483 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
484}
485void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
486 // If there is no compile unit specified, don't add a line #.
487 DICompileUnit CU = Ty->getCompileUnit();
488 if (CU.isNull())
489 return;
490
491 unsigned Line = Ty->getLineNumber();
492 unsigned FileID = FindCompileUnit(CU).getID();
493 assert(FileID && "Invalid file id");
494 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
495 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
496}
497
498/// AddAddress - Add an address attribute to a die based on the location
499/// provided.
500void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
501 const MachineLocation &Location) {
502 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
503 DIEBlock *Block = new DIEBlock();
504
505 if (Location.isReg()) {
506 if (Reg < 32) {
507 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
508 } else {
509 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
510 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
511 }
512 } else {
513 if (Reg < 32) {
514 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
515 } else {
516 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
517 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
518 }
519
520 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
521 }
522
523 AddBlock(Die, Attribute, 0, Block);
524}
525
526/// AddType - Add a new type attribute to the specified entity.
527void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
528 if (Ty.isNull())
529 return;
530
531 // Check for pre-existence.
532 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
533
534 // If it exists then use the existing value.
535 if (Slot) {
536 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
537 return;
538 }
539
540 // Set up proxy.
Bill Wendling995f80a2009-05-20 23:24:48 +0000541 Slot = CreateDIEEntry();
Bill Wendling0310d762009-05-15 09:23:25 +0000542
543 // Construct type.
544 DIE Buffer(dwarf::DW_TAG_base_type);
545 if (Ty.isBasicType(Ty.getTag()))
546 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
547 else if (Ty.isDerivedType(Ty.getTag()))
548 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
549 else {
550 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
551 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
552 }
553
554 // Add debug information entry to entity and appropriate context.
555 DIE *Die = NULL;
556 DIDescriptor Context = Ty.getContext();
557 if (!Context.isNull())
558 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
559
560 if (Die) {
561 DIE *Child = new DIE(Buffer);
562 Die->AddChild(Child);
563 Buffer.Detach();
564 SetDIEEntry(Slot, Child);
565 } else {
566 Die = DW_Unit->AddDie(Buffer);
567 SetDIEEntry(Slot, Die);
568 }
569
570 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
571}
572
573/// ConstructTypeDIE - Construct basic type die from DIBasicType.
574void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
575 DIBasicType BTy) {
576 // Get core information.
577 std::string Name;
578 BTy.getName(Name);
579 Buffer.setTag(dwarf::DW_TAG_base_type);
580 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
581 BTy.getEncoding());
582
583 // Add name if not anonymous or intermediate type.
584 if (!Name.empty())
585 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
586 uint64_t Size = BTy.getSizeInBits() >> 3;
587 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
588}
589
590/// ConstructTypeDIE - Construct derived type die from DIDerivedType.
591void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
592 DIDerivedType DTy) {
593 // Get core information.
594 std::string Name;
595 DTy.getName(Name);
596 uint64_t Size = DTy.getSizeInBits() >> 3;
597 unsigned Tag = DTy.getTag();
598
599 // FIXME - Workaround for templates.
600 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
601
602 Buffer.setTag(Tag);
603
604 // Map to main type, void will not have a type.
605 DIType FromTy = DTy.getTypeDerivedFrom();
606 AddType(DW_Unit, &Buffer, FromTy);
607
608 // Add name if not anonymous or intermediate type.
609 if (!Name.empty())
610 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
611
612 // Add size if non-zero (derived types might be zero-sized.)
613 if (Size)
614 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
615
616 // Add source line info if available and TyDesc is not a forward declaration.
617 if (!DTy.isForwardDecl())
618 AddSourceLine(&Buffer, &DTy);
619}
620
621/// ConstructTypeDIE - Construct type DIE from DICompositeType.
622void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
623 DICompositeType CTy) {
624 // Get core information.
625 std::string Name;
626 CTy.getName(Name);
627
628 uint64_t Size = CTy.getSizeInBits() >> 3;
629 unsigned Tag = CTy.getTag();
630 Buffer.setTag(Tag);
631
632 switch (Tag) {
633 case dwarf::DW_TAG_vector_type:
634 case dwarf::DW_TAG_array_type:
635 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
636 break;
637 case dwarf::DW_TAG_enumeration_type: {
638 DIArray Elements = CTy.getTypeArray();
639
640 // Add enumerators to enumeration type.
641 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
642 DIE *ElemDie = NULL;
643 DIEnumerator Enum(Elements.getElement(i).getGV());
644 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
645 Buffer.AddChild(ElemDie);
646 }
647 }
648 break;
649 case dwarf::DW_TAG_subroutine_type: {
650 // Add return type.
651 DIArray Elements = CTy.getTypeArray();
652 DIDescriptor RTy = Elements.getElement(0);
653 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
654
655 // Add prototype flag.
656 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
657
658 // Add arguments.
659 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
660 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
661 DIDescriptor Ty = Elements.getElement(i);
662 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
663 Buffer.AddChild(Arg);
664 }
665 }
666 break;
667 case dwarf::DW_TAG_structure_type:
668 case dwarf::DW_TAG_union_type:
669 case dwarf::DW_TAG_class_type: {
670 // Add elements to structure type.
671 DIArray Elements = CTy.getTypeArray();
672
673 // A forward struct declared type may not have elements available.
674 if (Elements.isNull())
675 break;
676
677 // Add elements to structure type.
678 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
679 DIDescriptor Element = Elements.getElement(i);
680 DIE *ElemDie = NULL;
681 if (Element.getTag() == dwarf::DW_TAG_subprogram)
682 ElemDie = CreateSubprogramDIE(DW_Unit,
683 DISubprogram(Element.getGV()));
Bill Wendling0310d762009-05-15 09:23:25 +0000684 else
685 ElemDie = CreateMemberDIE(DW_Unit,
686 DIDerivedType(Element.getGV()));
687 Buffer.AddChild(ElemDie);
688 }
689
690 // FIXME: We'd like an API to register additional attributes for the
691 // frontend to use while synthesizing, and then we'd use that api in clang
692 // instead of this.
693 if (Name == "__block_literal_generic")
694 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
695
696 unsigned RLang = CTy.getRunTimeLang();
697 if (RLang)
698 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
699 dwarf::DW_FORM_data1, RLang);
700 break;
701 }
702 default:
703 break;
704 }
705
706 // Add name if not anonymous or intermediate type.
707 if (!Name.empty())
708 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
709
710 if (Tag == dwarf::DW_TAG_enumeration_type ||
711 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
712 // Add size if non-zero (derived types might be zero-sized.)
713 if (Size)
714 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
715 else {
716 // Add zero size if it is not a forward declaration.
717 if (CTy.isForwardDecl())
718 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
719 else
720 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
721 }
722
723 // Add source line info if available.
724 if (!CTy.isForwardDecl())
725 AddSourceLine(&Buffer, &CTy);
726 }
727}
728
729/// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
730void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
731 int64_t L = SR.getLo();
732 int64_t H = SR.getHi();
733 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
734
Devang Patel6325a532009-08-14 20:59:16 +0000735 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 if (H)
739 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
Bill Wendling0310d762009-05-15 09:23:25 +0000740
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);
Devang Patel53cb17d2009-07-16 01:01:22 +0000790 if (!LinkageName.empty()) {
Chris Lattner6c2f9e12009-08-19 05:49:37 +0000791 // Skip special LLVM prefix that is used to inform the asm printer to not
792 // emit usual symbol prefix before the symbol name. This happens for
793 // Objective-C symbol names and symbol whose name is replaced using GCC's
794 // __asm__ attribute.
Devang Patel53cb17d2009-07-16 01:01:22 +0000795 if (LinkageName[0] == 1)
796 LinkageName = &LinkageName[1];
Bill Wendling0310d762009-05-15 09:23:25 +0000797 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
Devang Patel1a8d2d22009-07-14 00:55:28 +0000798 LinkageName);
Devang Patel53cb17d2009-07-16 01:01:22 +0000799 }
800 AddType(DW_Unit, GVDie, GV.getType());
Bill Wendling0310d762009-05-15 09:23:25 +0000801 if (!GV.isLocalToUnit())
802 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
803 AddSourceLine(GVDie, &GV);
804 return GVDie;
805}
806
807/// CreateMemberDIE - Create new member DIE.
808DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
809 DIE *MemberDie = new DIE(DT.getTag());
810 std::string Name;
811 DT.getName(Name);
812 if (!Name.empty())
813 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
814
815 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
816
817 AddSourceLine(MemberDie, &DT);
818
819 uint64_t Size = DT.getSizeInBits();
820 uint64_t FieldSize = DT.getOriginalTypeSize();
821
822 if (Size != FieldSize) {
823 // Handle bitfield.
824 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
825 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
826
827 uint64_t Offset = DT.getOffsetInBits();
828 uint64_t FieldOffset = Offset;
829 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
830 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
831 FieldOffset = (HiMark - FieldSize);
832 Offset -= FieldOffset;
833
834 // Maybe we need to work from the other end.
835 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
836 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
837 }
838
839 DIEBlock *Block = new DIEBlock();
840 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
841 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
842 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
843
844 if (DT.isProtected())
845 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
846 dwarf::DW_ACCESS_protected);
847 else if (DT.isPrivate())
848 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
849 dwarf::DW_ACCESS_private);
850
851 return MemberDie;
852}
853
854/// CreateSubprogramDIE - Create new DIE using SP.
855DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
856 const DISubprogram &SP,
Bill Wendling6679ee42009-05-18 22:02:36 +0000857 bool IsConstructor,
858 bool IsInlined) {
Bill Wendling0310d762009-05-15 09:23:25 +0000859 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
860
861 std::string Name;
862 SP.getName(Name);
863 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
864
865 std::string LinkageName;
866 SP.getLinkageName(LinkageName);
Devang Patel53cb17d2009-07-16 01:01:22 +0000867 if (!LinkageName.empty()) {
868 // Skip special LLVM prefix that is used to inform the asm printer to not emit
869 // usual symbol prefix before the symbol name. This happens for Objective-C
870 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
871 if (LinkageName[0] == 1)
872 LinkageName = &LinkageName[1];
Bill Wendling0310d762009-05-15 09:23:25 +0000873 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
Devang Patel1a8d2d22009-07-14 00:55:28 +0000874 LinkageName);
Devang Patel53cb17d2009-07-16 01:01:22 +0000875 }
Bill Wendling0310d762009-05-15 09:23:25 +0000876 AddSourceLine(SPDie, &SP);
877
878 DICompositeType SPTy = SP.getType();
879 DIArray Args = SPTy.getTypeArray();
880
881 // Add prototyped tag, if C or ObjC.
882 unsigned Lang = SP.getCompileUnit().getLanguage();
883 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
884 Lang == dwarf::DW_LANG_ObjC)
885 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
886
887 // Add Return Type.
888 unsigned SPTag = SPTy.getTag();
889 if (!IsConstructor) {
890 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
891 AddType(DW_Unit, SPDie, SPTy);
892 else
893 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
894 }
895
896 if (!SP.isDefinition()) {
897 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
898
899 // Add arguments. Do not add arguments for subprogram definition. They will
900 // be handled through RecordVariable.
901 if (SPTag == dwarf::DW_TAG_subroutine_type)
902 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
903 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
904 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
905 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
906 SPDie->AddChild(Arg);
907 }
908 }
909
Bill Wendling6679ee42009-05-18 22:02:36 +0000910 if (!SP.isLocalToUnit() && !IsInlined)
Bill Wendling0310d762009-05-15 09:23:25 +0000911 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
912
913 // DW_TAG_inlined_subroutine may refer to this DIE.
914 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
915 Slot = SPDie;
916 return SPDie;
917}
918
919/// FindCompileUnit - Get the compile unit for the given descriptor.
920///
921CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
922 DenseMap<Value *, CompileUnit *>::const_iterator I =
923 CompileUnitMap.find(Unit.getGV());
924 assert(I != CompileUnitMap.end() && "Missing compile unit.");
925 return *I->second;
926}
927
Bill Wendling995f80a2009-05-20 23:24:48 +0000928/// CreateDbgScopeVariable - Create a new scope variable.
Bill Wendling0310d762009-05-15 09:23:25 +0000929///
Bill Wendling995f80a2009-05-20 23:24:48 +0000930DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
Bill Wendling0310d762009-05-15 09:23:25 +0000931 // Get the descriptor.
932 const DIVariable &VD = DV->getVariable();
933
934 // Translate tag to proper Dwarf tag. The result variable is dropped for
935 // now.
936 unsigned Tag;
937 switch (VD.getTag()) {
938 case dwarf::DW_TAG_return_variable:
939 return NULL;
940 case dwarf::DW_TAG_arg_variable:
941 Tag = dwarf::DW_TAG_formal_parameter;
942 break;
943 case dwarf::DW_TAG_auto_variable: // fall thru
944 default:
945 Tag = dwarf::DW_TAG_variable;
946 break;
947 }
948
949 // Define variable debug information entry.
950 DIE *VariableDie = new DIE(Tag);
951 std::string Name;
952 VD.getName(Name);
953 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
954
955 // Add source line info if available.
956 AddSourceLine(VariableDie, &VD);
957
958 // Add variable type.
959 AddType(Unit, VariableDie, VD.getType());
960
961 // Add variable address.
Bill Wendling1180c782009-05-18 23:08:55 +0000962 if (!DV->isInlinedFnVar()) {
963 // Variables for abstract instances of inlined functions don't get a
964 // location.
965 MachineLocation Location;
966 Location.set(RI->getFrameRegister(*MF),
967 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
968 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
969 }
Bill Wendling0310d762009-05-15 09:23:25 +0000970
971 return VariableDie;
972}
973
974/// getOrCreateScope - Returns the scope associated with the given descriptor.
975///
976DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
977 DbgScope *&Slot = DbgScopeMap[V];
978 if (Slot) return Slot;
979
980 DbgScope *Parent = NULL;
981 DIBlock Block(V);
982
Bill Wendling8fff19b2009-06-01 20:18:46 +0000983 // Don't create a new scope if we already created one for an inlined function.
984 DenseMap<const GlobalVariable *, DbgScope *>::iterator
985 II = AbstractInstanceRootMap.find(V);
986 if (II != AbstractInstanceRootMap.end())
987 return LexicalScopeStack.back();
988
Bill Wendling0310d762009-05-15 09:23:25 +0000989 if (!Block.isNull()) {
990 DIDescriptor ParentDesc = Block.getContext();
991 Parent =
992 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
993 }
994
995 Slot = new DbgScope(Parent, DIDescriptor(V));
996
997 if (Parent)
998 Parent->AddScope(Slot);
999 else
1000 // First function is top level function.
1001 FunctionDbgScope = Slot;
1002
1003 return Slot;
1004}
1005
1006/// ConstructDbgScope - Construct the components of a scope.
1007///
1008void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1009 unsigned ParentStartID,
1010 unsigned ParentEndID,
1011 DIE *ParentDie, CompileUnit *Unit) {
1012 // Add variables to scope.
1013 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1014 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
Bill Wendling995f80a2009-05-20 23:24:48 +00001015 DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
Bill Wendling0310d762009-05-15 09:23:25 +00001016 if (VariableDie) ParentDie->AddChild(VariableDie);
1017 }
1018
1019 // Add concrete instances to scope.
1020 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1021 ParentScope->getConcreteInsts();
1022 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1023 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1024 DIE *Die = ConcreteInst->getDie();
1025
1026 unsigned StartID = ConcreteInst->getStartLabelID();
1027 unsigned EndID = ConcreteInst->getEndLabelID();
1028
1029 // Add the scope bounds.
1030 if (StartID)
1031 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1032 DWLabel("label", StartID));
1033 else
1034 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1035 DWLabel("func_begin", SubprogramCount));
1036
1037 if (EndID)
1038 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1039 DWLabel("label", EndID));
1040 else
1041 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1042 DWLabel("func_end", SubprogramCount));
1043
1044 ParentDie->AddChild(Die);
1045 }
1046
1047 // Add nested scopes.
1048 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1049 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1050 // Define the Scope debug information entry.
1051 DbgScope *Scope = Scopes[j];
1052
1053 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1054 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1055
1056 // Ignore empty scopes.
1057 if (StartID == EndID && StartID != 0) continue;
1058
1059 // Do not ignore inlined scopes even if they don't have any variables or
1060 // scopes.
1061 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1062 Scope->getConcreteInsts().empty())
1063 continue;
1064
1065 if (StartID == ParentStartID && EndID == ParentEndID) {
1066 // Just add stuff to the parent scope.
1067 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1068 } else {
1069 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1070
1071 // Add the scope bounds.
1072 if (StartID)
1073 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1074 DWLabel("label", StartID));
1075 else
1076 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1077 DWLabel("func_begin", SubprogramCount));
1078
1079 if (EndID)
1080 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1081 DWLabel("label", EndID));
1082 else
1083 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1084 DWLabel("func_end", SubprogramCount));
1085
1086 // Add the scope's contents.
1087 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1088 ParentDie->AddChild(ScopeDie);
1089 }
1090 }
1091}
1092
1093/// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1094///
Bill Wendling17956162009-05-20 23:28:48 +00001095void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
1096 bool AbstractScope) {
Bill Wendling0310d762009-05-15 09:23:25 +00001097 // Exit if there is no root scope.
1098 if (!RootScope) return;
1099 DIDescriptor Desc = RootScope->getDesc();
1100 if (Desc.isNull())
1101 return;
1102
1103 // Get the subprogram debug information entry.
1104 DISubprogram SPD(Desc.getGV());
1105
Bill Wendling0310d762009-05-15 09:23:25 +00001106 // Get the subprogram die.
Devang Patel1dbc7712009-06-29 20:45:18 +00001107 DIE *SPDie = ModuleCU->getDieMapSlotFor(SPD.getGV());
Bill Wendling0310d762009-05-15 09:23:25 +00001108 assert(SPDie && "Missing subprogram descriptor");
1109
Bill Wendling17956162009-05-20 23:28:48 +00001110 if (!AbstractScope) {
1111 // Add the function bounds.
1112 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1113 DWLabel("func_begin", SubprogramCount));
1114 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1115 DWLabel("func_end", SubprogramCount));
1116 MachineLocation Location(RI->getFrameRegister(*MF));
1117 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1118 }
Bill Wendling0310d762009-05-15 09:23:25 +00001119
Devang Patel1dbc7712009-06-29 20:45:18 +00001120 ConstructDbgScope(RootScope, 0, 0, SPDie, ModuleCU);
Bill Wendling0310d762009-05-15 09:23:25 +00001121}
1122
Bill Wendling0310d762009-05-15 09:23:25 +00001123/// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1124///
1125void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
Devang Patel1dbc7712009-06-29 20:45:18 +00001126 StringMap<DIE*> &Globals = ModuleCU->getGlobals();
Daniel Dunbar460f6562009-07-26 09:48:23 +00001127 StringMap<DIE*>::iterator GI = Globals.find(MF->getFunction()->getName());
Devang Patel70f44262009-06-29 20:38:13 +00001128 if (GI != Globals.end()) {
1129 DIE *SPDie = GI->second;
1130
1131 // Add the function bounds.
1132 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1133 DWLabel("func_begin", SubprogramCount));
1134 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1135 DWLabel("func_end", SubprogramCount));
1136
1137 MachineLocation Location(RI->getFrameRegister(*MF));
1138 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
Bill Wendling0310d762009-05-15 09:23:25 +00001139 }
Bill Wendling0310d762009-05-15 09:23:25 +00001140}
1141
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001142/// GetOrCreateSourceID - Look up the source id with the given directory and
1143/// source file names. If none currently exists, create a new id and insert it
1144/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1145/// maps as well.
1146unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1147 const std::string &FileName) {
1148 unsigned DId;
1149 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1150 if (DI != DirectoryIdMap.end()) {
1151 DId = DI->getValue();
1152 } else {
1153 DId = DirectoryNames.size() + 1;
1154 DirectoryIdMap[DirName] = DId;
1155 DirectoryNames.push_back(DirName);
1156 }
1157
1158 unsigned FId;
1159 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1160 if (FI != SourceFileIdMap.end()) {
1161 FId = FI->getValue();
1162 } else {
1163 FId = SourceFileNames.size() + 1;
1164 SourceFileIdMap[FileName] = FId;
1165 SourceFileNames.push_back(FileName);
1166 }
1167
1168 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1169 SourceIdMap.find(std::make_pair(DId, FId));
1170 if (SI != SourceIdMap.end())
1171 return SI->second;
1172
1173 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1174 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1175 SourceIds.push_back(std::make_pair(DId, FId));
1176
1177 return SrcId;
1178}
1179
1180void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1181 DICompileUnit DIUnit(GV);
1182 std::string Dir, FN, Prod;
1183 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1184 DIUnit.getFilename(FN));
1185
1186 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1187 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1188 DWLabel("section_line", 0), DWLabel("section_line", 0),
1189 false);
1190 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1191 DIUnit.getProducer(Prod));
1192 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1193 DIUnit.getLanguage());
1194 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1195
1196 if (!Dir.empty())
1197 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1198 if (DIUnit.isOptimized())
1199 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1200
1201 std::string Flags;
1202 DIUnit.getFlags(Flags);
1203 if (!Flags.empty())
1204 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1205
1206 unsigned RVer = DIUnit.getRunTimeVersion();
1207 if (RVer)
1208 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1209 dwarf::DW_FORM_data1, RVer);
1210
1211 CompileUnit *Unit = new CompileUnit(ID, Die);
Devang Patel1dbc7712009-06-29 20:45:18 +00001212 if (!ModuleCU && DIUnit.isMain()) {
Devang Patel70f44262009-06-29 20:38:13 +00001213 // Use first compile unit marked as isMain as the compile unit
1214 // for this module.
Devang Patel1dbc7712009-06-29 20:45:18 +00001215 ModuleCU = Unit;
Devang Patel70f44262009-06-29 20:38:13 +00001216 }
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001217
1218 CompileUnitMap[DIUnit.getGV()] = Unit;
1219 CompileUnits.push_back(Unit);
1220}
1221
Devang Patel13e16b62009-06-26 01:49:18 +00001222void DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001223 DIGlobalVariable DI_GV(GV);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001224
1225 // Check for pre-existence.
Devang Patel1dbc7712009-06-29 20:45:18 +00001226 DIE *&Slot = ModuleCU->getDieMapSlotFor(DI_GV.getGV());
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001227 if (Slot)
Devang Patel13e16b62009-06-26 01:49:18 +00001228 return;
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001229
Devang Patel1dbc7712009-06-29 20:45:18 +00001230 DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001231
1232 // Add address.
1233 DIEBlock *Block = new DIEBlock();
1234 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1235 std::string GLN;
1236 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1237 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
1238 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1239
1240 // Add to map.
1241 Slot = VariableDie;
1242
1243 // Add to context owner.
Devang Patel1dbc7712009-06-29 20:45:18 +00001244 ModuleCU->getDie()->AddChild(VariableDie);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001245
1246 // Expose as global. FIXME - need to check external flag.
1247 std::string Name;
Devang Patel1dbc7712009-06-29 20:45:18 +00001248 ModuleCU->AddGlobal(DI_GV.getName(Name), VariableDie);
Devang Patel13e16b62009-06-26 01:49:18 +00001249 return;
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001250}
1251
Devang Patel13e16b62009-06-26 01:49:18 +00001252void DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001253 DISubprogram SP(GV);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001254
1255 // Check for pre-existence.
Devang Patel1dbc7712009-06-29 20:45:18 +00001256 DIE *&Slot = ModuleCU->getDieMapSlotFor(GV);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001257 if (Slot)
Devang Patel13e16b62009-06-26 01:49:18 +00001258 return;
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001259
1260 if (!SP.isDefinition())
1261 // This is a method declaration which will be handled while constructing
1262 // class type.
Devang Patel13e16b62009-06-26 01:49:18 +00001263 return;
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001264
Devang Patel1dbc7712009-06-29 20:45:18 +00001265 DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001266
1267 // Add to map.
1268 Slot = SubprogramDie;
1269
1270 // Add to context owner.
Devang Patel1dbc7712009-06-29 20:45:18 +00001271 ModuleCU->getDie()->AddChild(SubprogramDie);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001272
1273 // Expose as global.
1274 std::string Name;
Devang Patel1dbc7712009-06-29 20:45:18 +00001275 ModuleCU->AddGlobal(SP.getName(Name), SubprogramDie);
Devang Patel13e16b62009-06-26 01:49:18 +00001276 return;
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001277}
1278
Devang Patel208622d2009-06-25 22:36:02 +00001279 /// BeginModule - Emit all Dwarf sections that should come prior to the
1280 /// content. Create global DIEs and emit initial debug info sections.
1281 /// This is inovked by the target AsmPrinter.
1282void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
1283 this->M = M;
1284
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001285 if (TimePassesIsEnabled)
1286 DebugTimer->startTimer();
1287
Devang Patel78ab9e22009-07-30 18:56:46 +00001288 DebugInfoFinder DbgFinder;
1289 DbgFinder.processModule(*M);
Devang Patel13e16b62009-06-26 01:49:18 +00001290
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001291 // Create all the compile unit DIEs.
Devang Patel78ab9e22009-07-30 18:56:46 +00001292 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1293 E = DbgFinder.compile_unit_end(); I != E; ++I)
Devang Patel13e16b62009-06-26 01:49:18 +00001294 ConstructCompileUnit(*I);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001295
1296 if (CompileUnits.empty()) {
1297 if (TimePassesIsEnabled)
1298 DebugTimer->stopTimer();
1299
1300 return;
1301 }
1302
Devang Patel70f44262009-06-29 20:38:13 +00001303 // If main compile unit for this module is not seen than randomly
1304 // select first compile unit.
Devang Patel1dbc7712009-06-29 20:45:18 +00001305 if (!ModuleCU)
1306 ModuleCU = CompileUnits[0];
Devang Patel70f44262009-06-29 20:38:13 +00001307
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001308 // If there is not any debug info available for any global variables and any
1309 // subprograms then there is not any debug info to emit.
Devang Patel78ab9e22009-07-30 18:56:46 +00001310 if (DbgFinder.global_variable_count() == 0
1311 && DbgFinder.subprogram_count() == 0) {
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001312 if (TimePassesIsEnabled)
1313 DebugTimer->stopTimer();
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001314 return;
1315 }
Devang Patel78ab9e22009-07-30 18:56:46 +00001316
Devang Patel13e16b62009-06-26 01:49:18 +00001317 // Create DIEs for each of the externally visible global variables.
Devang Patel78ab9e22009-07-30 18:56:46 +00001318 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1319 E = DbgFinder.global_variable_end(); I != E; ++I)
Devang Patel13e16b62009-06-26 01:49:18 +00001320 ConstructGlobalVariableDIE(*I);
1321
1322 // Create DIEs for each of the externally visible subprograms.
Devang Patel78ab9e22009-07-30 18:56:46 +00001323 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1324 E = DbgFinder.subprogram_end(); I != E; ++I)
Devang Patel13e16b62009-06-26 01:49:18 +00001325 ConstructSubprogram(*I);
1326
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001327 MMI = mmi;
1328 shouldEmit = true;
1329 MMI->setDebugInfoAvailability(true);
1330
1331 // Prime section data.
Chris Lattnerf0144122009-07-28 03:13:23 +00001332 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001333
1334 // Print out .file directives to specify files for .loc directives. These are
1335 // printed out early so that they precede any .loc directives.
1336 if (TAI->hasDotLocAndDotFile()) {
1337 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1338 // Remember source id starts at 1.
1339 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1340 sys::Path FullPath(getSourceDirectoryName(Id.first));
1341 bool AppendOk =
1342 FullPath.appendComponent(getSourceFileName(Id.second));
1343 assert(AppendOk && "Could not append filename to directory!");
1344 AppendOk = false;
1345 Asm->EmitFile(i, FullPath.toString());
1346 Asm->EOL();
1347 }
1348 }
1349
1350 // Emit initial sections
1351 EmitInitial();
1352
1353 if (TimePassesIsEnabled)
1354 DebugTimer->stopTimer();
1355}
1356
1357/// EndModule - Emit all Dwarf sections that should come after the content.
1358///
1359void DwarfDebug::EndModule() {
1360 if (!ShouldEmitDwarfDebug())
1361 return;
1362
1363 if (TimePassesIsEnabled)
1364 DebugTimer->startTimer();
1365
1366 // Standard sections final addresses.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001367 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001368 EmitLabel("text_end", 0);
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001369 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001370 EmitLabel("data_end", 0);
1371
1372 // End text sections.
1373 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001374 Asm->OutStreamer.SwitchSection(SectionMap[i]);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001375 EmitLabel("section_end", i);
1376 }
1377
1378 // Emit common frame information.
1379 EmitCommonDebugFrame();
1380
1381 // Emit function debug frame information
1382 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1383 E = DebugFrames.end(); I != E; ++I)
1384 EmitFunctionDebugFrame(*I);
1385
1386 // Compute DIE offsets and sizes.
1387 SizeAndOffsets();
1388
1389 // Emit all the DIEs into a debug info section
1390 EmitDebugInfo();
1391
1392 // Corresponding abbreviations into a abbrev section.
1393 EmitAbbreviations();
1394
1395 // Emit source line correspondence into a debug line section.
1396 EmitDebugLines();
1397
1398 // Emit info into a debug pubnames section.
1399 EmitDebugPubNames();
1400
1401 // Emit info into a debug str section.
1402 EmitDebugStr();
1403
1404 // Emit info into a debug loc section.
1405 EmitDebugLoc();
1406
1407 // Emit info into a debug aranges section.
1408 EmitDebugARanges();
1409
1410 // Emit info into a debug ranges section.
1411 EmitDebugRanges();
1412
1413 // Emit info into a debug macinfo section.
1414 EmitDebugMacInfo();
1415
1416 // Emit inline info.
1417 EmitDebugInlineInfo();
1418
1419 if (TimePassesIsEnabled)
1420 DebugTimer->stopTimer();
1421}
1422
1423/// BeginFunction - Gather pre-function debug information. Assumes being
1424/// emitted immediately after the function entry point.
1425void DwarfDebug::BeginFunction(MachineFunction *MF) {
1426 this->MF = MF;
1427
1428 if (!ShouldEmitDwarfDebug()) return;
1429
1430 if (TimePassesIsEnabled)
1431 DebugTimer->startTimer();
1432
1433 // Begin accumulating function debug information.
1434 MMI->BeginFunction(MF);
1435
1436 // Assumes in correct section after the entry point.
1437 EmitLabel("func_begin", ++SubprogramCount);
1438
1439 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1440 // function.
1441 DebugLoc FDL = MF->getDefaultDebugLoc();
1442 if (!FDL.isUnknown()) {
1443 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1444 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
1445 DICompileUnit(DLT.CompileUnit));
1446 Asm->printLabel(LabelID);
1447 }
1448
1449 if (TimePassesIsEnabled)
1450 DebugTimer->stopTimer();
1451}
1452
1453/// EndFunction - Gather and emit post-function debug information.
1454///
1455void DwarfDebug::EndFunction(MachineFunction *MF) {
1456 if (!ShouldEmitDwarfDebug()) return;
1457
1458 if (TimePassesIsEnabled)
1459 DebugTimer->startTimer();
1460
1461 // Define end label for subprogram.
1462 EmitLabel("func_end", SubprogramCount);
1463
1464 // Get function line info.
1465 if (!Lines.empty()) {
1466 // Get section line info.
Chris Lattner290c2f52009-08-03 23:20:21 +00001467 unsigned ID = SectionMap.insert(Asm->getCurrentSection());
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001468 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
1469 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
1470 // Append the function info to section info.
1471 SectionLineInfos.insert(SectionLineInfos.end(),
1472 Lines.begin(), Lines.end());
1473 }
1474
1475 // Construct the DbgScope for abstract instances.
1476 for (SmallVector<DbgScope *, 32>::iterator
1477 I = AbstractInstanceRootList.begin(),
1478 E = AbstractInstanceRootList.end(); I != E; ++I)
Bill Wendling17956162009-05-20 23:28:48 +00001479 ConstructFunctionDbgScope(*I);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001480
1481 // Construct scopes for subprogram.
1482 if (FunctionDbgScope)
1483 ConstructFunctionDbgScope(FunctionDbgScope);
1484 else
1485 // FIXME: This is wrong. We are essentially getting past a problem with
1486 // debug information not being able to handle unreachable blocks that have
1487 // debug information in them. In particular, those unreachable blocks that
1488 // have "region end" info in them. That situation results in the "root
1489 // scope" not being created. If that's the case, then emit a "default"
1490 // scope, i.e., one that encompasses the whole function. This isn't
1491 // desirable. And a better way of handling this (and all of the debugging
1492 // information) needs to be explored.
1493 ConstructDefaultDbgScope(MF);
1494
1495 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
1496 MMI->getFrameMoves()));
1497
1498 // Clear debug info
1499 if (FunctionDbgScope) {
1500 delete FunctionDbgScope;
1501 DbgScopeMap.clear();
1502 DbgAbstractScopeMap.clear();
1503 DbgConcreteScopeMap.clear();
1504 InlinedVariableScopes.clear();
1505 FunctionDbgScope = NULL;
1506 LexicalScopeStack.clear();
1507 AbstractInstanceRootList.clear();
Devang Patel9217f792009-06-12 19:24:05 +00001508 AbstractInstanceRootMap.clear();
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001509 }
1510
1511 Lines.clear();
1512
1513 if (TimePassesIsEnabled)
1514 DebugTimer->stopTimer();
1515}
1516
1517/// RecordSourceLine - Records location information and associates it with a
1518/// label. Returns a unique label ID used to generate a label and provide
1519/// correspondence to the source line list.
1520unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
1521 if (TimePassesIsEnabled)
1522 DebugTimer->startTimer();
1523
1524 CompileUnit *Unit = CompileUnitMap[V];
1525 assert(Unit && "Unable to find CompileUnit");
1526 unsigned ID = MMI->NextLabelID();
1527 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
1528
1529 if (TimePassesIsEnabled)
1530 DebugTimer->stopTimer();
1531
1532 return ID;
1533}
1534
1535/// RecordSourceLine - Records location information and associates it with a
1536/// label. Returns a unique label ID used to generate a label and provide
1537/// correspondence to the source line list.
1538unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
1539 DICompileUnit CU) {
1540 if (TimePassesIsEnabled)
1541 DebugTimer->startTimer();
1542
1543 std::string Dir, Fn;
1544 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
1545 CU.getFilename(Fn));
1546 unsigned ID = MMI->NextLabelID();
1547 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
1548
1549 if (TimePassesIsEnabled)
1550 DebugTimer->stopTimer();
1551
1552 return ID;
1553}
1554
1555/// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
1556/// timed. Look up the source id with the given directory and source file
1557/// names. If none currently exists, create a new id and insert it in the
1558/// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
1559/// well.
1560unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
1561 const std::string &FileName) {
1562 if (TimePassesIsEnabled)
1563 DebugTimer->startTimer();
1564
1565 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
1566
1567 if (TimePassesIsEnabled)
1568 DebugTimer->stopTimer();
1569
1570 return SrcId;
1571}
1572
1573/// RecordRegionStart - Indicate the start of a region.
1574unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
1575 if (TimePassesIsEnabled)
1576 DebugTimer->startTimer();
1577
1578 DbgScope *Scope = getOrCreateScope(V);
1579 unsigned ID = MMI->NextLabelID();
1580 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1581 LexicalScopeStack.push_back(Scope);
1582
1583 if (TimePassesIsEnabled)
1584 DebugTimer->stopTimer();
1585
1586 return ID;
1587}
1588
1589/// RecordRegionEnd - Indicate the end of a region.
1590unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
1591 if (TimePassesIsEnabled)
1592 DebugTimer->startTimer();
1593
1594 DbgScope *Scope = getOrCreateScope(V);
1595 unsigned ID = MMI->NextLabelID();
1596 Scope->setEndLabelID(ID);
Devang Pateldaf9e022009-06-13 02:16:18 +00001597 // FIXME : region.end() may not be in the last basic block.
1598 // For now, do not pop last lexical scope because next basic
1599 // block may start new inlined function's body.
1600 unsigned LSSize = LexicalScopeStack.size();
1601 if (LSSize != 0 && LSSize != 1)
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001602 LexicalScopeStack.pop_back();
1603
1604 if (TimePassesIsEnabled)
1605 DebugTimer->stopTimer();
1606
1607 return ID;
1608}
1609
1610/// RecordVariable - Indicate the declaration of a local variable.
1611void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
1612 const MachineInstr *MI) {
1613 if (TimePassesIsEnabled)
1614 DebugTimer->startTimer();
1615
1616 DIDescriptor Desc(GV);
1617 DbgScope *Scope = NULL;
1618 bool InlinedFnVar = false;
1619
1620 if (Desc.getTag() == dwarf::DW_TAG_variable) {
1621 // GV is a global variable.
1622 DIGlobalVariable DG(GV);
1623 Scope = getOrCreateScope(DG.getContext().getGV());
1624 } else {
1625 DenseMap<const MachineInstr *, DbgScope *>::iterator
1626 SI = InlinedVariableScopes.find(MI);
1627
1628 if (SI != InlinedVariableScopes.end()) {
1629 // or GV is an inlined local variable.
1630 Scope = SI->second;
Devang Patel261cc192009-07-07 21:55:14 +00001631 InlinedFnVar = true;
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001632 } else {
1633 DIVariable DV(GV);
1634 GlobalVariable *V = DV.getContext().getGV();
1635
Devang Patel0a4afb62009-07-07 21:12:32 +00001636 // or GV is a local variable.
1637 Scope = getOrCreateScope(V);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001638 }
1639 }
1640
1641 assert(Scope && "Unable to find the variable's scope");
1642 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex, InlinedFnVar);
1643 Scope->AddVariable(DV);
1644
1645 if (TimePassesIsEnabled)
1646 DebugTimer->stopTimer();
1647}
1648
1649//// RecordInlinedFnStart - Indicate the start of inlined subroutine.
1650unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
1651 unsigned Line, unsigned Col) {
1652 unsigned LabelID = MMI->NextLabelID();
1653
1654 if (!TAI->doesDwarfUsesInlineInfoSection())
1655 return LabelID;
1656
1657 if (TimePassesIsEnabled)
1658 DebugTimer->startTimer();
1659
1660 GlobalVariable *GV = SP.getGV();
1661 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1662 II = AbstractInstanceRootMap.find(GV);
1663
1664 if (II == AbstractInstanceRootMap.end()) {
1665 // Create an abstract instance entry for this inlined function if it doesn't
1666 // already exist.
1667 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
1668
1669 // Get the compile unit context.
Devang Patel1dbc7712009-06-29 20:45:18 +00001670 DIE *SPDie = ModuleCU->getDieMapSlotFor(GV);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001671 if (!SPDie)
Devang Patel1dbc7712009-06-29 20:45:18 +00001672 SPDie = CreateSubprogramDIE(ModuleCU, SP, false, true);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001673
1674 // Mark as being inlined. This makes this subprogram entry an abstract
1675 // instance root.
1676 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
1677 // that it's defined. That probably won't change in the future. However,
1678 // this could be more elegant.
1679 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
1680
1681 // Keep track of the abstract scope for this function.
1682 DbgAbstractScopeMap[GV] = Scope;
1683
1684 AbstractInstanceRootMap[GV] = Scope;
1685 AbstractInstanceRootList.push_back(Scope);
1686 }
1687
1688 // Create a concrete inlined instance for this inlined function.
1689 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
1690 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
Devang Patel1dbc7712009-06-29 20:45:18 +00001691 ScopeDie->setAbstractCompileUnit(ModuleCU);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001692
Devang Patel1dbc7712009-06-29 20:45:18 +00001693 DIE *Origin = ModuleCU->getDieMapSlotFor(GV);
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001694 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
1695 dwarf::DW_FORM_ref4, Origin);
Devang Patel1dbc7712009-06-29 20:45:18 +00001696 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001697 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
1698 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
1699
1700 ConcreteScope->setDie(ScopeDie);
1701 ConcreteScope->setStartLabelID(LabelID);
1702 MMI->RecordUsedDbgLabel(LabelID);
1703
1704 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
1705
1706 // Keep track of the concrete scope that's inlined into this function.
1707 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1708 SI = DbgConcreteScopeMap.find(GV);
1709
1710 if (SI == DbgConcreteScopeMap.end())
1711 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
1712 else
1713 SI->second.push_back(ConcreteScope);
1714
1715 // Track the start label for this inlined function.
1716 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1717 I = InlineInfo.find(GV);
1718
1719 if (I == InlineInfo.end())
1720 InlineInfo[GV].push_back(LabelID);
1721 else
1722 I->second.push_back(LabelID);
1723
1724 if (TimePassesIsEnabled)
1725 DebugTimer->stopTimer();
1726
1727 return LabelID;
1728}
1729
1730/// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
1731unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
1732 if (!TAI->doesDwarfUsesInlineInfoSection())
1733 return 0;
1734
1735 if (TimePassesIsEnabled)
1736 DebugTimer->startTimer();
1737
1738 GlobalVariable *GV = SP.getGV();
1739 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1740 I = DbgConcreteScopeMap.find(GV);
1741
1742 if (I == DbgConcreteScopeMap.end()) {
1743 // FIXME: Can this situation actually happen? And if so, should it?
1744 if (TimePassesIsEnabled)
1745 DebugTimer->stopTimer();
1746
1747 return 0;
1748 }
1749
1750 SmallVector<DbgScope *, 8> &Scopes = I->second;
Devang Patel11a407f2009-06-15 21:45:50 +00001751 if (Scopes.empty()) {
1752 // Returned ID is 0 if this is unbalanced "end of inlined
1753 // scope". This could happen if optimizer eats dbg intrinsics
1754 // or "beginning of inlined scope" is not recoginized due to
1755 // missing location info. In such cases, ignore this region.end.
1756 return 0;
1757 }
1758
Bill Wendlingf0fb9872009-05-20 23:19:06 +00001759 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
1760 unsigned ID = MMI->NextLabelID();
1761 MMI->RecordUsedDbgLabel(ID);
1762 Scope->setEndLabelID(ID);
1763
1764 if (TimePassesIsEnabled)
1765 DebugTimer->stopTimer();
1766
1767 return ID;
1768}
1769
1770/// RecordVariableScope - Record scope for the variable declared by
1771/// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
1772/// for only inlined subroutine variables. Other variables's scopes are
1773/// determined during RecordVariable().
1774void DwarfDebug::RecordVariableScope(DIVariable &DV,
1775 const MachineInstr *DeclareMI) {
1776 if (TimePassesIsEnabled)
1777 DebugTimer->startTimer();
1778
1779 DISubprogram SP(DV.getContext().getGV());
1780
1781 if (SP.isNull()) {
1782 if (TimePassesIsEnabled)
1783 DebugTimer->stopTimer();
1784
1785 return;
1786 }
1787
1788 DenseMap<GlobalVariable *, DbgScope *>::iterator
1789 I = DbgAbstractScopeMap.find(SP.getGV());
1790 if (I != DbgAbstractScopeMap.end())
1791 InlinedVariableScopes[DeclareMI] = I->second;
1792
1793 if (TimePassesIsEnabled)
1794 DebugTimer->stopTimer();
1795}
Bill Wendling94d04b82009-05-20 23:21:38 +00001796
Bill Wendling829e67b2009-05-20 23:22:40 +00001797//===----------------------------------------------------------------------===//
1798// Emit Methods
1799//===----------------------------------------------------------------------===//
1800
Bill Wendling94d04b82009-05-20 23:21:38 +00001801/// SizeAndOffsetDie - Compute the size and offset of a DIE.
1802///
1803unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1804 // Get the children.
1805 const std::vector<DIE *> &Children = Die->getChildren();
1806
1807 // If not last sibling and has children then add sibling offset attribute.
1808 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1809
1810 // Record the abbreviation.
1811 AssignAbbrevNumber(Die->getAbbrev());
1812
1813 // Get the abbreviation for this DIE.
1814 unsigned AbbrevNumber = Die->getAbbrevNumber();
1815 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1816
1817 // Set DIE offset
1818 Die->setOffset(Offset);
1819
1820 // Start the size with the size of abbreviation code.
1821 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1822
1823 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1824 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1825
1826 // Size the DIE attribute values.
1827 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1828 // Size attribute value.
1829 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1830
1831 // Size the DIE children if any.
1832 if (!Children.empty()) {
1833 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1834 "Children flag not set");
1835
1836 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1837 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1838
1839 // End of children marker.
1840 Offset += sizeof(int8_t);
1841 }
1842
1843 Die->setSize(Offset - Die->getOffset());
1844 return Offset;
1845}
1846
1847/// SizeAndOffsets - Compute the size and offset of all the DIEs.
1848///
1849void DwarfDebug::SizeAndOffsets() {
1850 // Compute size of compile unit header.
1851 static unsigned Offset =
1852 sizeof(int32_t) + // Length of Compilation Unit Info
1853 sizeof(int16_t) + // DWARF version number
1854 sizeof(int32_t) + // Offset Into Abbrev. Section
1855 sizeof(int8_t); // Pointer Size (in bytes)
1856
Devang Patel1dbc7712009-06-29 20:45:18 +00001857 SizeAndOffsetDie(ModuleCU->getDie(), Offset, true);
1858 CompileUnitOffsets[ModuleCU] = 0;
Bill Wendling94d04b82009-05-20 23:21:38 +00001859}
1860
1861/// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1862/// tools to recognize the object file contains Dwarf information.
1863void DwarfDebug::EmitInitial() {
1864 // Check to see if we already emitted intial headers.
1865 if (didInitial) return;
1866 didInitial = true;
1867
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001868 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1869
Bill Wendling94d04b82009-05-20 23:21:38 +00001870 // Dwarf sections base addresses.
1871 if (TAI->doesDwarfRequireFrameSection()) {
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001872 Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001873 EmitLabel("section_debug_frame", 0);
1874 }
1875
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001876 Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001877 EmitLabel("section_info", 0);
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001878 Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001879 EmitLabel("section_abbrev", 0);
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001880 Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001881 EmitLabel("section_aranges", 0);
1882
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001883 if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
1884 Asm->OutStreamer.SwitchSection(LineInfoDirective);
Bill Wendling94d04b82009-05-20 23:21:38 +00001885 EmitLabel("section_macinfo", 0);
1886 }
1887
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001888 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001889 EmitLabel("section_line", 0);
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001890 Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001891 EmitLabel("section_loc", 0);
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001892 Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001893 EmitLabel("section_pubnames", 0);
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001894 Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001895 EmitLabel("section_str", 0);
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001896 Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001897 EmitLabel("section_ranges", 0);
1898
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001899 Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001900 EmitLabel("text_begin", 0);
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001901 Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00001902 EmitLabel("data_begin", 0);
1903}
1904
1905/// EmitDIE - Recusively Emits a debug information entry.
1906///
1907void DwarfDebug::EmitDIE(DIE *Die) {
1908 // Get the abbreviation for this DIE.
1909 unsigned AbbrevNumber = Die->getAbbrevNumber();
1910 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1911
1912 Asm->EOL();
1913
1914 // Emit the code (index) for the abbreviation.
1915 Asm->EmitULEB128Bytes(AbbrevNumber);
1916
1917 if (Asm->isVerbose())
1918 Asm->EOL(std::string("Abbrev [" +
1919 utostr(AbbrevNumber) +
1920 "] 0x" + utohexstr(Die->getOffset()) +
1921 ":0x" + utohexstr(Die->getSize()) + " " +
1922 dwarf::TagString(Abbrev->getTag())));
1923 else
1924 Asm->EOL();
1925
1926 SmallVector<DIEValue*, 32> &Values = Die->getValues();
1927 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1928
1929 // Emit the DIE attribute values.
1930 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1931 unsigned Attr = AbbrevData[i].getAttribute();
1932 unsigned Form = AbbrevData[i].getForm();
1933 assert(Form && "Too many attributes for DIE (check abbreviation)");
1934
1935 switch (Attr) {
1936 case dwarf::DW_AT_sibling:
1937 Asm->EmitInt32(Die->SiblingOffset());
1938 break;
1939 case dwarf::DW_AT_abstract_origin: {
1940 DIEEntry *E = cast<DIEEntry>(Values[i]);
1941 DIE *Origin = E->getEntry();
1942 unsigned Addr =
1943 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
1944 Origin->getOffset();
1945
1946 Asm->EmitInt32(Addr);
1947 break;
1948 }
1949 default:
1950 // Emit an attribute using the defined form.
1951 Values[i]->EmitValue(this, Form);
1952 break;
1953 }
1954
1955 Asm->EOL(dwarf::AttributeString(Attr));
1956 }
1957
1958 // Emit the DIE children if any.
1959 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1960 const std::vector<DIE *> &Children = Die->getChildren();
1961
1962 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1963 EmitDIE(Children[j]);
1964
1965 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1966 }
1967}
1968
1969/// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
1970///
1971void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
1972 DIE *Die = Unit->getDie();
1973
1974 // Emit the compile units header.
1975 EmitLabel("info_begin", Unit->getID());
1976
1977 // Emit size of content not including length itself
1978 unsigned ContentSize = Die->getSize() +
1979 sizeof(int16_t) + // DWARF version number
1980 sizeof(int32_t) + // Offset Into Abbrev. Section
1981 sizeof(int8_t) + // Pointer Size (in bytes)
1982 sizeof(int32_t); // FIXME - extra pad for gdb bug.
1983
1984 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
1985 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1986 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
1987 Asm->EOL("Offset Into Abbrev. Section");
1988 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1989
1990 EmitDIE(Die);
1991 // FIXME - extra padding for gdb bug.
1992 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1993 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1994 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1995 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1996 EmitLabel("info_end", Unit->getID());
1997
1998 Asm->EOL();
1999}
2000
2001void DwarfDebug::EmitDebugInfo() {
2002 // Start debug info section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002003 Asm->OutStreamer.SwitchSection(
2004 Asm->getObjFileLowering().getDwarfInfoSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002005
Devang Patel1dbc7712009-06-29 20:45:18 +00002006 EmitDebugInfoPerCU(ModuleCU);
Bill Wendling94d04b82009-05-20 23:21:38 +00002007}
2008
2009/// EmitAbbreviations - Emit the abbreviation section.
2010///
2011void DwarfDebug::EmitAbbreviations() const {
2012 // Check to see if it is worth the effort.
2013 if (!Abbreviations.empty()) {
2014 // Start the debug abbrev section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002015 Asm->OutStreamer.SwitchSection(
2016 Asm->getObjFileLowering().getDwarfAbbrevSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002017
2018 EmitLabel("abbrev_begin", 0);
2019
2020 // For each abbrevation.
2021 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2022 // Get abbreviation data
2023 const DIEAbbrev *Abbrev = Abbreviations[i];
2024
2025 // Emit the abbrevations code (base 1 index.)
2026 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2027 Asm->EOL("Abbreviation Code");
2028
2029 // Emit the abbreviations data.
2030 Abbrev->Emit(Asm);
2031
2032 Asm->EOL();
2033 }
2034
2035 // Mark end of abbreviations.
2036 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2037
2038 EmitLabel("abbrev_end", 0);
2039 Asm->EOL();
2040 }
2041}
2042
2043/// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2044/// the line matrix.
2045///
2046void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2047 // Define last address of section.
2048 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2049 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2050 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2051 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2052
2053 // Mark end of matrix.
2054 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2055 Asm->EmitULEB128Bytes(1); Asm->EOL();
2056 Asm->EmitInt8(1); Asm->EOL();
2057}
2058
2059/// EmitDebugLines - Emit source line information.
2060///
2061void DwarfDebug::EmitDebugLines() {
2062 // If the target is using .loc/.file, the assembler will be emitting the
2063 // .debug_line table automatically.
2064 if (TAI->hasDotLocAndDotFile())
2065 return;
2066
2067 // Minimum line delta, thus ranging from -10..(255-10).
2068 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2069 // Maximum line delta, thus ranging from -10..(255-10).
2070 const int MaxLineDelta = 255 + MinLineDelta;
2071
2072 // Start the dwarf line section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002073 Asm->OutStreamer.SwitchSection(
2074 Asm->getObjFileLowering().getDwarfLineSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002075
2076 // Construct the section header.
2077 EmitDifference("line_end", 0, "line_begin", 0, true);
2078 Asm->EOL("Length of Source Line Info");
2079 EmitLabel("line_begin", 0);
2080
2081 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2082
2083 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2084 Asm->EOL("Prolog Length");
2085 EmitLabel("line_prolog_begin", 0);
2086
2087 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2088
2089 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2090
2091 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2092
2093 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2094
2095 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2096
2097 // Line number standard opcode encodings argument count
2098 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2099 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2100 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2101 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2102 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2103 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2104 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2105 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2106 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2107
2108 // Emit directories.
2109 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2110 Asm->EmitString(getSourceDirectoryName(DI));
2111 Asm->EOL("Directory");
2112 }
2113
2114 Asm->EmitInt8(0); Asm->EOL("End of directories");
2115
2116 // Emit files.
2117 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2118 // Remember source id starts at 1.
2119 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2120 Asm->EmitString(getSourceFileName(Id.second));
2121 Asm->EOL("Source");
2122 Asm->EmitULEB128Bytes(Id.first);
2123 Asm->EOL("Directory #");
2124 Asm->EmitULEB128Bytes(0);
2125 Asm->EOL("Mod date");
2126 Asm->EmitULEB128Bytes(0);
2127 Asm->EOL("File size");
2128 }
2129
2130 Asm->EmitInt8(0); Asm->EOL("End of files");
2131
2132 EmitLabel("line_prolog_end", 0);
2133
2134 // A sequence for each text section.
2135 unsigned SecSrcLinesSize = SectionSourceLines.size();
2136
2137 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2138 // Isolate current sections line info.
2139 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2140
Chris Lattner93b6db32009-08-08 23:39:42 +00002141 /*if (Asm->isVerbose()) {
Chris Lattnera87dea42009-07-31 18:48:30 +00002142 const MCSection *S = SectionMap[j + 1];
Bill Wendling94d04b82009-05-20 23:21:38 +00002143 O << '\t' << TAI->getCommentString() << " Section"
2144 << S->getName() << '\n';
Chris Lattner93b6db32009-08-08 23:39:42 +00002145 }*/
2146 Asm->EOL();
Bill Wendling94d04b82009-05-20 23:21:38 +00002147
2148 // Dwarf assumes we start with first line of first source file.
2149 unsigned Source = 1;
2150 unsigned Line = 1;
2151
2152 // Construct rows of the address, source, line, column matrix.
2153 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2154 const SrcLineInfo &LineInfo = LineInfos[i];
2155 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2156 if (!LabelID) continue;
2157
2158 if (!Asm->isVerbose())
2159 Asm->EOL();
2160 else {
2161 std::pair<unsigned, unsigned> SourceID =
2162 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2163 O << '\t' << TAI->getCommentString() << ' '
2164 << getSourceDirectoryName(SourceID.first) << ' '
2165 << getSourceFileName(SourceID.second)
2166 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2167 }
2168
2169 // Define the line address.
2170 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2171 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2172 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2173 EmitReference("label", LabelID); Asm->EOL("Location label");
2174
2175 // If change of source, then switch to the new source.
2176 if (Source != LineInfo.getSourceID()) {
2177 Source = LineInfo.getSourceID();
2178 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2179 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2180 }
2181
2182 // If change of line.
2183 if (Line != LineInfo.getLine()) {
2184 // Determine offset.
2185 int Offset = LineInfo.getLine() - Line;
2186 int Delta = Offset - MinLineDelta;
2187
2188 // Update line.
2189 Line = LineInfo.getLine();
2190
2191 // If delta is small enough and in range...
2192 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2193 // ... then use fast opcode.
2194 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2195 } else {
2196 // ... otherwise use long hand.
2197 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2198 Asm->EOL("DW_LNS_advance_line");
2199 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2200 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2201 }
2202 } else {
2203 // Copy the previous row (different address or source)
2204 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2205 }
2206 }
2207
2208 EmitEndOfLineMatrix(j + 1);
2209 }
2210
2211 if (SecSrcLinesSize == 0)
2212 // Because we're emitting a debug_line section, we still need a line
2213 // table. The linker and friends expect it to exist. If there's nothing to
2214 // put into it, emit an empty table.
2215 EmitEndOfLineMatrix(1);
2216
2217 EmitLabel("line_end", 0);
2218 Asm->EOL();
2219}
2220
2221/// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2222///
2223void DwarfDebug::EmitCommonDebugFrame() {
2224 if (!TAI->doesDwarfRequireFrameSection())
2225 return;
2226
2227 int stackGrowth =
2228 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2229 TargetFrameInfo::StackGrowsUp ?
2230 TD->getPointerSize() : -TD->getPointerSize();
2231
2232 // Start the dwarf frame section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002233 Asm->OutStreamer.SwitchSection(
2234 Asm->getObjFileLowering().getDwarfFrameSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002235
2236 EmitLabel("debug_frame_common", 0);
2237 EmitDifference("debug_frame_common_end", 0,
2238 "debug_frame_common_begin", 0, true);
2239 Asm->EOL("Length of Common Information Entry");
2240
2241 EmitLabel("debug_frame_common_begin", 0);
2242 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2243 Asm->EOL("CIE Identifier Tag");
2244 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2245 Asm->EOL("CIE Version");
2246 Asm->EmitString("");
2247 Asm->EOL("CIE Augmentation");
2248 Asm->EmitULEB128Bytes(1);
2249 Asm->EOL("CIE Code Alignment Factor");
2250 Asm->EmitSLEB128Bytes(stackGrowth);
2251 Asm->EOL("CIE Data Alignment Factor");
2252 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2253 Asm->EOL("CIE RA Column");
2254
2255 std::vector<MachineMove> Moves;
2256 RI->getInitialFrameState(Moves);
2257
2258 EmitFrameMoves(NULL, 0, Moves, false);
2259
2260 Asm->EmitAlignment(2, 0, 0, false);
2261 EmitLabel("debug_frame_common_end", 0);
2262
2263 Asm->EOL();
2264}
2265
2266/// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2267/// section.
2268void
2269DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2270 if (!TAI->doesDwarfRequireFrameSection())
2271 return;
2272
2273 // Start the dwarf frame section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002274 Asm->OutStreamer.SwitchSection(
2275 Asm->getObjFileLowering().getDwarfFrameSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002276
2277 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2278 "debug_frame_begin", DebugFrameInfo.Number, true);
2279 Asm->EOL("Length of Frame Information Entry");
2280
2281 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2282
2283 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2284 0, 0, true, false);
2285 Asm->EOL("FDE CIE offset");
2286
2287 EmitReference("func_begin", DebugFrameInfo.Number);
2288 Asm->EOL("FDE initial location");
2289 EmitDifference("func_end", DebugFrameInfo.Number,
2290 "func_begin", DebugFrameInfo.Number);
2291 Asm->EOL("FDE address range");
2292
2293 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2294 false);
2295
2296 Asm->EmitAlignment(2, 0, 0, false);
2297 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2298
2299 Asm->EOL();
2300}
2301
2302void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2303 EmitDifference("pubnames_end", Unit->getID(),
2304 "pubnames_begin", Unit->getID(), true);
2305 Asm->EOL("Length of Public Names Info");
2306
2307 EmitLabel("pubnames_begin", Unit->getID());
2308
2309 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2310
2311 EmitSectionOffset("info_begin", "section_info",
2312 Unit->getID(), 0, true, false);
2313 Asm->EOL("Offset of Compilation Unit Info");
2314
2315 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2316 true);
2317 Asm->EOL("Compilation Unit Length");
2318
2319 StringMap<DIE*> &Globals = Unit->getGlobals();
2320 for (StringMap<DIE*>::const_iterator
2321 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2322 const char *Name = GI->getKeyData();
2323 DIE * Entity = GI->second;
2324
2325 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2326 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2327 }
2328
2329 Asm->EmitInt32(0); Asm->EOL("End Mark");
2330 EmitLabel("pubnames_end", Unit->getID());
2331
2332 Asm->EOL();
2333}
2334
2335/// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2336///
2337void DwarfDebug::EmitDebugPubNames() {
2338 // Start the dwarf pubnames section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002339 Asm->OutStreamer.SwitchSection(
2340 Asm->getObjFileLowering().getDwarfPubNamesSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002341
Devang Patel1dbc7712009-06-29 20:45:18 +00002342 EmitDebugPubNamesPerCU(ModuleCU);
Bill Wendling94d04b82009-05-20 23:21:38 +00002343}
2344
2345/// EmitDebugStr - Emit visible names into a debug str section.
2346///
2347void DwarfDebug::EmitDebugStr() {
2348 // Check to see if it is worth the effort.
2349 if (!StringPool.empty()) {
2350 // Start the dwarf str section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002351 Asm->OutStreamer.SwitchSection(
2352 Asm->getObjFileLowering().getDwarfStrSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002353
2354 // For each of strings in the string pool.
2355 for (unsigned StringID = 1, N = StringPool.size();
2356 StringID <= N; ++StringID) {
2357 // Emit a label for reference from debug information entries.
2358 EmitLabel("string", StringID);
2359
2360 // Emit the string itself.
2361 const std::string &String = StringPool[StringID];
2362 Asm->EmitString(String); Asm->EOL();
2363 }
2364
2365 Asm->EOL();
2366 }
2367}
2368
2369/// EmitDebugLoc - Emit visible names into a debug loc section.
2370///
2371void DwarfDebug::EmitDebugLoc() {
2372 // Start the dwarf loc section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002373 Asm->OutStreamer.SwitchSection(
2374 Asm->getObjFileLowering().getDwarfLocSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002375 Asm->EOL();
2376}
2377
2378/// EmitDebugARanges - Emit visible names into a debug aranges section.
2379///
2380void DwarfDebug::EmitDebugARanges() {
2381 // Start the dwarf aranges section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002382 Asm->OutStreamer.SwitchSection(
2383 Asm->getObjFileLowering().getDwarfARangesSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002384
2385 // FIXME - Mock up
2386#if 0
2387 CompileUnit *Unit = GetBaseCompileUnit();
2388
2389 // Don't include size of length
2390 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2391
2392 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2393
2394 EmitReference("info_begin", Unit->getID());
2395 Asm->EOL("Offset of Compilation Unit Info");
2396
2397 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2398
2399 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2400
2401 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2402 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2403
2404 // Range 1
2405 EmitReference("text_begin", 0); Asm->EOL("Address");
2406 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2407
2408 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2409 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2410#endif
2411
2412 Asm->EOL();
2413}
2414
2415/// EmitDebugRanges - Emit visible names into a debug ranges section.
2416///
2417void DwarfDebug::EmitDebugRanges() {
2418 // Start the dwarf ranges section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002419 Asm->OutStreamer.SwitchSection(
2420 Asm->getObjFileLowering().getDwarfRangesSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002421 Asm->EOL();
2422}
2423
2424/// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2425///
2426void DwarfDebug::EmitDebugMacInfo() {
Chris Lattner18a4c162009-08-02 07:24:22 +00002427 if (const MCSection *LineInfo =
2428 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
Bill Wendling94d04b82009-05-20 23:21:38 +00002429 // Start the dwarf macinfo section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002430 Asm->OutStreamer.SwitchSection(LineInfo);
Bill Wendling94d04b82009-05-20 23:21:38 +00002431 Asm->EOL();
2432 }
2433}
2434
2435/// EmitDebugInlineInfo - Emit inline info using following format.
2436/// Section Header:
2437/// 1. length of section
2438/// 2. Dwarf version number
2439/// 3. address size.
2440///
2441/// Entries (one "entry" for each function that was inlined):
2442///
2443/// 1. offset into __debug_str section for MIPS linkage name, if exists;
2444/// otherwise offset into __debug_str for regular function name.
2445/// 2. offset into __debug_str section for regular function name.
2446/// 3. an unsigned LEB128 number indicating the number of distinct inlining
2447/// instances for the function.
2448///
2449/// The rest of the entry consists of a {die_offset, low_pc} pair for each
2450/// inlined instance; the die_offset points to the inlined_subroutine die in the
2451/// __debug_info section, and the low_pc is the starting address for the
2452/// inlining instance.
2453void DwarfDebug::EmitDebugInlineInfo() {
2454 if (!TAI->doesDwarfUsesInlineInfoSection())
2455 return;
2456
Devang Patel1dbc7712009-06-29 20:45:18 +00002457 if (!ModuleCU)
Bill Wendling94d04b82009-05-20 23:21:38 +00002458 return;
2459
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002460 Asm->OutStreamer.SwitchSection(
2461 Asm->getObjFileLowering().getDwarfDebugInlineSection());
Bill Wendling94d04b82009-05-20 23:21:38 +00002462 Asm->EOL();
2463 EmitDifference("debug_inlined_end", 1,
2464 "debug_inlined_begin", 1, true);
2465 Asm->EOL("Length of Debug Inlined Information Entry");
2466
2467 EmitLabel("debug_inlined_begin", 1);
2468
2469 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2470 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2471
2472 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2473 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2474 GlobalVariable *GV = I->first;
2475 SmallVector<unsigned, 4> &Labels = I->second;
2476 DISubprogram SP(GV);
2477 std::string Name;
2478 std::string LName;
2479
2480 SP.getLinkageName(LName);
2481 SP.getName(Name);
2482
Devang Patel53cb17d2009-07-16 01:01:22 +00002483 if (LName.empty())
2484 Asm->EmitString(Name);
2485 else {
Chris Lattner6c2f9e12009-08-19 05:49:37 +00002486 // Skip special LLVM prefix that is used to inform the asm printer to not
2487 // emit usual symbol prefix before the symbol name. This happens for
2488 // Objective-C symbol names and symbol whose name is replaced using GCC's
2489 // __asm__ attribute.
Devang Patel53cb17d2009-07-16 01:01:22 +00002490 if (LName[0] == 1)
2491 LName = &LName[1];
2492 Asm->EmitString(LName);
2493 }
Bill Wendling94d04b82009-05-20 23:21:38 +00002494 Asm->EOL("MIPS linkage name");
2495
2496 Asm->EmitString(Name); Asm->EOL("Function name");
2497
2498 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2499
2500 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2501 LE = Labels.end(); LI != LE; ++LI) {
Devang Patel1dbc7712009-06-29 20:45:18 +00002502 DIE *SP = ModuleCU->getDieMapSlotFor(GV);
Bill Wendling94d04b82009-05-20 23:21:38 +00002503 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2504
2505 if (TD->getPointerSize() == sizeof(int32_t))
2506 O << TAI->getData32bitsDirective();
2507 else
2508 O << TAI->getData64bitsDirective();
2509
2510 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2511 }
2512 }
2513
2514 EmitLabel("debug_inlined_end", 1);
2515 Asm->EOL();
2516}