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