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