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