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