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