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