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