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