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