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