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