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