RecordVariable is called each time a DECLARE node is encountered. For an inlined
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfDebug.cpp
1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DwarfDebug.h"
15 #include "llvm/Module.h"
16 #include "llvm/CodeGen/MachineModuleInfo.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/System/Path.h"
19 #include "llvm/Target/TargetAsmInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetFrameInfo.h"
23 #include <ostream>
24 using namespace llvm;
25
26 static TimerGroup &getDwarfTimerGroup() {
27   static TimerGroup DwarfTimerGroup("Dwarf Debugging");
28   return DwarfTimerGroup;
29 }
30
31 //===----------------------------------------------------------------------===//
32
33 /// Configuration values for initial hash set sizes (log2).
34 ///
35 static const unsigned InitDiesSetSize          = 9; // log2(512)
36 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
37 static const unsigned InitValuesSetSize        = 9; // log2(512)
38
39 namespace llvm {
40
41 //===----------------------------------------------------------------------===//
42 /// CompileUnit - This dwarf writer support class manages information associate
43 /// with a source file.
44 class VISIBILITY_HIDDEN CompileUnit {
45   /// ID - File identifier for source.
46   ///
47   unsigned ID;
48
49   /// Die - Compile unit debug information entry.
50   ///
51   DIE *Die;
52
53   /// GVToDieMap - Tracks the mapping of unit level debug informaton
54   /// variables to debug information entries.
55   std::map<GlobalVariable *, DIE *> GVToDieMap;
56
57   /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
58   /// descriptors to debug information entries using a DIEEntry proxy.
59   std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
60
61   /// Globals - A map of globally visible named entities for this unit.
62   ///
63   StringMap<DIE*> Globals;
64
65   /// DiesSet - Used to uniquely define dies within the compile unit.
66   ///
67   FoldingSet<DIE> DiesSet;
68 public:
69   CompileUnit(unsigned I, DIE *D)
70     : ID(I), Die(D), GVToDieMap(),
71       GVToDIEEntryMap(), Globals(), DiesSet(InitDiesSetSize)
72   {}
73
74   ~CompileUnit() {
75     delete Die;
76   }
77
78   // Accessors.
79   unsigned getID()           const { return ID; }
80   DIE* getDie()              const { return Die; }
81   StringMap<DIE*> &getGlobals() { return Globals; }
82
83   /// hasContent - Return true if this compile unit has something to write out.
84   ///
85   bool hasContent() const {
86     return !Die->getChildren().empty();
87   }
88
89   /// AddGlobal - Add a new global entity to the compile unit.
90   ///
91   void AddGlobal(const std::string &Name, DIE *Die) {
92     Globals[Name] = Die;
93   }
94
95   /// getDieMapSlotFor - Returns the debug information entry map slot for the
96   /// specified debug variable.
97   DIE *&getDieMapSlotFor(GlobalVariable *GV) {
98     return GVToDieMap[GV];
99   }
100
101   /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for the
102   /// specified debug variable.
103   DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
104     return GVToDIEEntryMap[GV];
105   }
106
107   /// AddDie - Adds or interns the DIE to the compile unit.
108   ///
109   DIE *AddDie(DIE &Buffer) {
110     FoldingSetNodeID ID;
111     Buffer.Profile(ID);
112     void *Where;
113     DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
114
115     if (!Die) {
116       Die = new DIE(Buffer);
117       DiesSet.InsertNode(Die, Where);
118       this->Die->AddChild(Die);
119       Buffer.Detach();
120     }
121
122     return Die;
123   }
124 };
125
126 //===----------------------------------------------------------------------===//
127 /// DbgVariable - This class is used to track local variable information.
128 ///
129 class VISIBILITY_HIDDEN DbgVariable {
130   DIVariable Var;                    // Variable Descriptor.
131   unsigned FrameIndex;               // Variable frame index.
132 public:
133   DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I)  {}
134
135   // Accessors.
136   DIVariable getVariable()  const { return Var; }
137   unsigned getFrameIndex() const { return FrameIndex; }
138 };
139
140 //===----------------------------------------------------------------------===//
141 /// DbgScope - This class is used to track scope information.
142 ///
143 class DbgConcreteScope;
144 class VISIBILITY_HIDDEN DbgScope {
145   DbgScope *Parent;                   // Parent to this scope.
146   DIDescriptor Desc;                  // Debug info descriptor for scope.
147                                       // Either subprogram or block.
148   unsigned StartLabelID;              // Label ID of the beginning of scope.
149   unsigned EndLabelID;                // Label ID of the end of scope.
150   SmallVector<DbgScope *, 4> Scopes;  // Scopes defined in scope.
151   SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
152   SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
153 public:
154   DbgScope(DbgScope *P, DIDescriptor D)
155     : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0) {}
156   virtual ~DbgScope();
157
158   // Accessors.
159   DbgScope *getParent()          const { return Parent; }
160   DIDescriptor getDesc()         const { return Desc; }
161   unsigned getStartLabelID()     const { return StartLabelID; }
162   unsigned getEndLabelID()       const { return EndLabelID; }
163   SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
164   SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
165   SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
166   void setStartLabelID(unsigned S) { StartLabelID = S; }
167   void setEndLabelID(unsigned E)   { EndLabelID = E; }
168
169   /// AddScope - Add a scope to the scope.
170   ///
171   void AddScope(DbgScope *S) { Scopes.push_back(S); }
172
173   /// AddVariable - Add a variable to the scope.
174   ///
175   void AddVariable(DbgVariable *V) { Variables.push_back(V); }
176
177   /// AddConcreteInst - Add a concrete instance to the scope.
178   ///
179   void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
180
181 #ifndef NDEBUG
182   void dump() const;
183 #endif
184 };
185
186 #ifndef NDEBUG
187 void DbgScope::dump() const {
188   static unsigned IndentLevel = 0;
189   std::string Indent(IndentLevel, ' ');
190
191   cerr << Indent; Desc.dump();
192   cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
193
194   IndentLevel += 2;
195
196   for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
197     if (Scopes[i] != this)
198       Scopes[i]->dump();
199
200   IndentLevel -= 2;
201 }
202 #endif
203
204 //===----------------------------------------------------------------------===//
205 /// DbgConcreteScope - This class is used to track a scope that holds concrete
206 /// instance information.
207 ///
208 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
209   CompileUnit *Unit;
210   DIE *Die;                           // Debug info for this concrete scope.
211 public:
212   DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
213
214   // Accessors.
215   DIE *getDie() const { return Die; }
216   void setDie(DIE *D) { Die = D; }
217 };
218
219 DbgScope::~DbgScope() {
220   for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
221     delete Scopes[i];
222   for (unsigned j = 0, M = Variables.size(); j < M; ++j)
223     delete Variables[j];
224   for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
225     delete ConcreteInsts[k];
226 }
227
228 } // end llvm namespace
229
230 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
231   : Dwarf(OS, A, T, "dbg"), MainCU(0),
232     AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
233     ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
234     SectionSourceLines(), didInitial(false), shouldEmit(false),
235     FunctionDbgScope(0), DebugTimer(0) {
236   if (TimePassesIsEnabled)
237     DebugTimer = new Timer("Dwarf Debug Writer",
238                            getDwarfTimerGroup());
239 }
240 DwarfDebug::~DwarfDebug() {
241   for (unsigned j = 0, M = Values.size(); j < M; ++j)
242     delete Values[j];
243
244   for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
245          I = AbstractInstanceRootMap.begin(),
246          E = AbstractInstanceRootMap.end(); I != E;++I)
247     delete I->second;
248
249   delete DebugTimer;
250 }
251
252 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
253 ///
254 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
255   // Profile the node so that we can make it unique.
256   FoldingSetNodeID ID;
257   Abbrev.Profile(ID);
258
259   // Check the set for priors.
260   DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
261
262   // If it's newly added.
263   if (InSet == &Abbrev) {
264     // Add to abbreviation list.
265     Abbreviations.push_back(&Abbrev);
266
267     // Assign the vector position + 1 as its number.
268     Abbrev.setNumber(Abbreviations.size());
269   } else {
270     // Assign existing abbreviation number.
271     Abbrev.setNumber(InSet->getNumber());
272   }
273 }
274
275 /// NewDIEEntry - Creates a new DIEEntry to be a proxy for a debug information
276 /// entry.
277 DIEEntry *DwarfDebug::NewDIEEntry(DIE *Entry) {
278   DIEEntry *Value;
279
280   if (Entry) {
281     FoldingSetNodeID ID;
282     DIEEntry::Profile(ID, Entry);
283     void *Where;
284     Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
285
286     if (Value) return Value;
287
288     Value = new DIEEntry(Entry);
289     ValuesSet.InsertNode(Value, Where);
290   } else {
291     Value = new DIEEntry(Entry);
292   }
293
294   Values.push_back(Value);
295   return Value;
296 }
297
298 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
299 ///
300 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
301   Value->setEntry(Entry);
302
303   // Add to values set if not already there.  If it is, we merely have a
304   // duplicate in the values list (no harm.)
305   ValuesSet.GetOrInsertNode(Value);
306 }
307
308 /// AddUInt - Add an unsigned integer attribute data and value.
309 ///
310 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
311                          unsigned Form, uint64_t Integer) {
312   if (!Form) Form = DIEInteger::BestForm(false, Integer);
313
314   FoldingSetNodeID ID;
315   DIEInteger::Profile(ID, Integer);
316   void *Where;
317   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
318
319   if (!Value) {
320     Value = new DIEInteger(Integer);
321     ValuesSet.InsertNode(Value, Where);
322     Values.push_back(Value);
323   }
324
325   Die->AddValue(Attribute, Form, Value);
326 }
327
328 /// AddSInt - Add an signed integer attribute data and value.
329 ///
330 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
331                          unsigned Form, int64_t Integer) {
332   if (!Form) Form = DIEInteger::BestForm(true, Integer);
333
334   FoldingSetNodeID ID;
335   DIEInteger::Profile(ID, (uint64_t)Integer);
336   void *Where;
337   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
338
339   if (!Value) {
340     Value = new DIEInteger(Integer);
341     ValuesSet.InsertNode(Value, Where);
342     Values.push_back(Value);
343   }
344
345   Die->AddValue(Attribute, Form, Value);
346 }
347
348 /// AddString - Add a string attribute data and value.
349 ///
350 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
351                            const std::string &String) {
352   FoldingSetNodeID ID;
353   DIEString::Profile(ID, String);
354   void *Where;
355   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
356
357   if (!Value) {
358     Value = new DIEString(String);
359     ValuesSet.InsertNode(Value, Where);
360     Values.push_back(Value);
361   }
362
363   Die->AddValue(Attribute, Form, Value);
364 }
365
366 /// AddLabel - Add a Dwarf label attribute data and value.
367 ///
368 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
369                           const DWLabel &Label) {
370   FoldingSetNodeID ID;
371   DIEDwarfLabel::Profile(ID, Label);
372   void *Where;
373   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
374
375   if (!Value) {
376     Value = new DIEDwarfLabel(Label);
377     ValuesSet.InsertNode(Value, Where);
378     Values.push_back(Value);
379   }
380
381   Die->AddValue(Attribute, Form, Value);
382 }
383
384 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
385 ///
386 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
387                                 const std::string &Label) {
388   FoldingSetNodeID ID;
389   DIEObjectLabel::Profile(ID, Label);
390   void *Where;
391   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
392
393   if (!Value) {
394     Value = new DIEObjectLabel(Label);
395     ValuesSet.InsertNode(Value, Where);
396     Values.push_back(Value);
397   }
398
399   Die->AddValue(Attribute, Form, Value);
400 }
401
402 /// AddSectionOffset - Add a section offset label attribute data and value.
403 ///
404 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
405                                   const DWLabel &Label, const DWLabel &Section,
406                                   bool isEH, bool useSet) {
407   FoldingSetNodeID ID;
408   DIESectionOffset::Profile(ID, Label, Section);
409   void *Where;
410   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
411
412   if (!Value) {
413     Value = new DIESectionOffset(Label, Section, isEH, useSet);
414     ValuesSet.InsertNode(Value, Where);
415     Values.push_back(Value);
416   }
417
418   Die->AddValue(Attribute, Form, Value);
419 }
420
421 /// AddDelta - Add a label delta attribute data and value.
422 ///
423 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
424                           const DWLabel &Hi, const DWLabel &Lo) {
425   FoldingSetNodeID ID;
426   DIEDelta::Profile(ID, Hi, Lo);
427   void *Where;
428   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
429
430   if (!Value) {
431     Value = new DIEDelta(Hi, Lo);
432     ValuesSet.InsertNode(Value, Where);
433     Values.push_back(Value);
434   }
435
436   Die->AddValue(Attribute, Form, Value);
437 }
438
439 /// AddBlock - Add block data.
440 ///
441 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
442                           DIEBlock *Block) {
443   Block->ComputeSize(TD);
444   FoldingSetNodeID ID;
445   Block->Profile(ID);
446   void *Where;
447   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
448
449   if (!Value) {
450     Value = Block;
451     ValuesSet.InsertNode(Value, Where);
452     Values.push_back(Value);
453   } else {
454     // Already exists, reuse the previous one.
455     delete Block;
456     Block = cast<DIEBlock>(Value);
457   }
458
459   Die->AddValue(Attribute, Block->BestForm(), Value);
460 }
461
462 /// AddSourceLine - Add location information to specified debug information
463 /// entry.
464 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
465   // If there is no compile unit specified, don't add a line #.
466   if (V->getCompileUnit().isNull())
467     return;
468
469   unsigned Line = V->getLineNumber();
470   unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
471   assert(FileID && "Invalid file id");
472   AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
473   AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
474 }
475
476 /// AddSourceLine - Add location information to specified debug information
477 /// entry.
478 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
479   // If there is no compile unit specified, don't add a line #.
480   if (G->getCompileUnit().isNull())
481     return;
482
483   unsigned Line = G->getLineNumber();
484   unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
485   assert(FileID && "Invalid file id");
486   AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
487   AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
488 }
489 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
490   // If there is no compile unit specified, don't add a line #.
491   DICompileUnit CU = Ty->getCompileUnit();
492   if (CU.isNull())
493     return;
494
495   unsigned Line = Ty->getLineNumber();
496   unsigned FileID = FindCompileUnit(CU).getID();
497   assert(FileID && "Invalid file id");
498   AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
499   AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
500 }
501
502 /// AddAddress - Add an address attribute to a die based on the location
503 /// provided.
504 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
505                             const MachineLocation &Location) {
506   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
507   DIEBlock *Block = new DIEBlock();
508
509   if (Location.isReg()) {
510     if (Reg < 32) {
511       AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
512     } else {
513       AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
514       AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
515     }
516   } else {
517     if (Reg < 32) {
518       AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
519     } else {
520       AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
521       AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
522     }
523
524     AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
525   }
526
527   AddBlock(Die, Attribute, 0, Block);
528 }
529
530 /// AddType - Add a new type attribute to the specified entity.
531 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
532   if (Ty.isNull())
533     return;
534
535   // Check for pre-existence.
536   DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
537
538   // If it exists then use the existing value.
539   if (Slot) {
540     Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
541     return;
542   }
543
544   // Set up proxy.
545   Slot = NewDIEEntry();
546
547   // Construct type.
548   DIE Buffer(dwarf::DW_TAG_base_type);
549   if (Ty.isBasicType(Ty.getTag()))
550     ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
551   else if (Ty.isDerivedType(Ty.getTag()))
552     ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
553   else {
554     assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
555     ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
556   }
557
558   // Add debug information entry to entity and appropriate context.
559   DIE *Die = NULL;
560   DIDescriptor Context = Ty.getContext();
561   if (!Context.isNull())
562     Die = DW_Unit->getDieMapSlotFor(Context.getGV());
563
564   if (Die) {
565     DIE *Child = new DIE(Buffer);
566     Die->AddChild(Child);
567     Buffer.Detach();
568     SetDIEEntry(Slot, Child);
569   } else {
570     Die = DW_Unit->AddDie(Buffer);
571     SetDIEEntry(Slot, Die);
572   }
573
574   Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
575 }
576
577 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
578 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
579                                   DIBasicType BTy) {
580   // Get core information.
581   std::string Name;
582   BTy.getName(Name);
583   Buffer.setTag(dwarf::DW_TAG_base_type);
584   AddUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
585           BTy.getEncoding());
586
587   // Add name if not anonymous or intermediate type.
588   if (!Name.empty())
589     AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
590   uint64_t Size = BTy.getSizeInBits() >> 3;
591   AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
592 }
593
594 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
595 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
596                                   DIDerivedType DTy) {
597   // Get core information.
598   std::string Name;
599   DTy.getName(Name);
600   uint64_t Size = DTy.getSizeInBits() >> 3;
601   unsigned Tag = DTy.getTag();
602
603   // FIXME - Workaround for templates.
604   if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
605
606   Buffer.setTag(Tag);
607
608   // Map to main type, void will not have a type.
609   DIType FromTy = DTy.getTypeDerivedFrom();
610   AddType(DW_Unit, &Buffer, FromTy);
611
612   // Add name if not anonymous or intermediate type.
613   if (!Name.empty())
614     AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
615
616   // Add size if non-zero (derived types might be zero-sized.)
617   if (Size)
618     AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
619
620   // Add source line info if available and TyDesc is not a forward declaration.
621   if (!DTy.isForwardDecl())
622     AddSourceLine(&Buffer, &DTy);
623 }
624
625 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
626 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
627                                   DICompositeType CTy) {
628   // Get core information.
629   std::string Name;
630   CTy.getName(Name);
631
632   uint64_t Size = CTy.getSizeInBits() >> 3;
633   unsigned Tag = CTy.getTag();
634   Buffer.setTag(Tag);
635
636   switch (Tag) {
637   case dwarf::DW_TAG_vector_type:
638   case dwarf::DW_TAG_array_type:
639     ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
640     break;
641   case dwarf::DW_TAG_enumeration_type: {
642     DIArray Elements = CTy.getTypeArray();
643
644     // Add enumerators to enumeration type.
645     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
646       DIE *ElemDie = NULL;
647       DIEnumerator Enum(Elements.getElement(i).getGV());
648       ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
649       Buffer.AddChild(ElemDie);
650     }
651   }
652     break;
653   case dwarf::DW_TAG_subroutine_type: {
654     // Add return type.
655     DIArray Elements = CTy.getTypeArray();
656     DIDescriptor RTy = Elements.getElement(0);
657     AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
658
659     // Add prototype flag.
660     AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
661
662     // Add arguments.
663     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
664       DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
665       DIDescriptor Ty = Elements.getElement(i);
666       AddType(DW_Unit, Arg, DIType(Ty.getGV()));
667       Buffer.AddChild(Arg);
668     }
669   }
670     break;
671   case dwarf::DW_TAG_structure_type:
672   case dwarf::DW_TAG_union_type:
673   case dwarf::DW_TAG_class_type: {
674     // Add elements to structure type.
675     DIArray Elements = CTy.getTypeArray();
676
677     // A forward struct declared type may not have elements available.
678     if (Elements.isNull())
679       break;
680
681     // Add elements to structure type.
682     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
683       DIDescriptor Element = Elements.getElement(i);
684       DIE *ElemDie = NULL;
685       if (Element.getTag() == dwarf::DW_TAG_subprogram)
686         ElemDie = CreateSubprogramDIE(DW_Unit,
687                                       DISubprogram(Element.getGV()));
688       else if (Element.getTag() == dwarf::DW_TAG_variable) // ??
689         ElemDie = CreateGlobalVariableDIE(DW_Unit,
690                                           DIGlobalVariable(Element.getGV()));
691       else
692         ElemDie = CreateMemberDIE(DW_Unit,
693                                   DIDerivedType(Element.getGV()));
694       Buffer.AddChild(ElemDie);
695     }
696
697     // FIXME: We'd like an API to register additional attributes for the
698     // frontend to use while synthesizing, and then we'd use that api in clang
699     // instead of this.
700     if (Name == "__block_literal_generic")
701       AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
702
703     unsigned RLang = CTy.getRunTimeLang();
704     if (RLang)
705       AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
706               dwarf::DW_FORM_data1, RLang);
707     break;
708   }
709   default:
710     break;
711   }
712
713   // Add name if not anonymous or intermediate type.
714   if (!Name.empty())
715     AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
716
717   if (Tag == dwarf::DW_TAG_enumeration_type ||
718       Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
719     // Add size if non-zero (derived types might be zero-sized.)
720     if (Size)
721       AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
722     else {
723       // Add zero size if it is not a forward declaration.
724       if (CTy.isForwardDecl())
725         AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
726       else
727         AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
728     }
729
730     // Add source line info if available.
731     if (!CTy.isForwardDecl())
732       AddSourceLine(&Buffer, &CTy);
733   }
734 }
735
736 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
737 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
738   int64_t L = SR.getLo();
739   int64_t H = SR.getHi();
740   DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
741
742   if (L != H) {
743     AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
744     if (L)
745       AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
746     AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
747   }
748
749   Buffer.AddChild(DW_Subrange);
750 }
751
752 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
753 void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
754                                        DICompositeType *CTy) {
755   Buffer.setTag(dwarf::DW_TAG_array_type);
756   if (CTy->getTag() == dwarf::DW_TAG_vector_type)
757     AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
758
759   // Emit derived type.
760   AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
761   DIArray Elements = CTy->getTypeArray();
762
763   // Construct an anonymous type for index type.
764   DIE IdxBuffer(dwarf::DW_TAG_base_type);
765   AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
766   AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
767           dwarf::DW_ATE_signed);
768   DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
769
770   // Add subranges to array type.
771   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
772     DIDescriptor Element = Elements.getElement(i);
773     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
774       ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
775   }
776 }
777
778 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
779 DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
780   DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
781   std::string Name;
782   ETy->getName(Name);
783   AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
784   int64_t Value = ETy->getEnumValue();
785   AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
786   return Enumerator;
787 }
788
789 /// CreateGlobalVariableDIE - Create new DIE using GV.
790 DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
791                                          const DIGlobalVariable &GV) {
792   DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
793   std::string Name;
794   GV.getDisplayName(Name);
795   AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
796   std::string LinkageName;
797   GV.getLinkageName(LinkageName);
798   if (!LinkageName.empty())
799     AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
800               LinkageName);
801   AddType(DW_Unit, GVDie, GV.getType());
802   if (!GV.isLocalToUnit())
803     AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
804   AddSourceLine(GVDie, &GV);
805   return GVDie;
806 }
807
808 /// CreateMemberDIE - Create new member DIE.
809 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
810   DIE *MemberDie = new DIE(DT.getTag());
811   std::string Name;
812   DT.getName(Name);
813   if (!Name.empty())
814     AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
815
816   AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
817
818   AddSourceLine(MemberDie, &DT);
819
820   uint64_t Size = DT.getSizeInBits();
821   uint64_t FieldSize = DT.getOriginalTypeSize();
822
823   if (Size != FieldSize) {
824     // Handle bitfield.
825     AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
826     AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
827
828     uint64_t Offset = DT.getOffsetInBits();
829     uint64_t FieldOffset = Offset;
830     uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
831     uint64_t HiMark = (Offset + FieldSize) & AlignMask;
832     FieldOffset = (HiMark - FieldSize);
833     Offset -= FieldOffset;
834
835     // Maybe we need to work from the other end.
836     if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
837     AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
838   }
839
840   DIEBlock *Block = new DIEBlock();
841   AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
842   AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
843   AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
844
845   if (DT.isProtected())
846     AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
847             dwarf::DW_ACCESS_protected);
848   else if (DT.isPrivate())
849     AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
850             dwarf::DW_ACCESS_private);
851
852   return MemberDie;
853 }
854
855 /// CreateSubprogramDIE - Create new DIE using SP.
856 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
857                                      const DISubprogram &SP,
858                                      bool IsConstructor,
859                                      bool IsInlined) {
860   DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
861
862   std::string Name;
863   SP.getName(Name);
864   AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
865
866   std::string LinkageName;
867   SP.getLinkageName(LinkageName);
868
869   if (!LinkageName.empty())
870     AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
871               LinkageName);
872
873   AddSourceLine(SPDie, &SP);
874
875   DICompositeType SPTy = SP.getType();
876   DIArray Args = SPTy.getTypeArray();
877
878   // Add prototyped tag, if C or ObjC.
879   unsigned Lang = SP.getCompileUnit().getLanguage();
880   if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
881       Lang == dwarf::DW_LANG_ObjC)
882     AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
883
884   // Add Return Type.
885   unsigned SPTag = SPTy.getTag();
886   if (!IsConstructor) {
887     if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
888       AddType(DW_Unit, SPDie, SPTy);
889     else
890       AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
891   }
892
893   if (!SP.isDefinition()) {
894     AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
895
896     // Add arguments. Do not add arguments for subprogram definition. They will
897     // be handled through RecordVariable.
898     if (SPTag == dwarf::DW_TAG_subroutine_type)
899       for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
900         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
901         AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
902         AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
903         SPDie->AddChild(Arg);
904       }
905   }
906
907   if (!SP.isLocalToUnit() && !IsInlined)
908     AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
909
910   // DW_TAG_inlined_subroutine may refer to this DIE.
911   DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
912   Slot = SPDie;
913   return SPDie;
914 }
915
916 /// FindCompileUnit - Get the compile unit for the given descriptor.
917 ///
918 CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
919   DenseMap<Value *, CompileUnit *>::const_iterator I =
920     CompileUnitMap.find(Unit.getGV());
921   assert(I != CompileUnitMap.end() && "Missing compile unit.");
922   return *I->second;
923 }
924
925 /// NewDbgScopeVariable - Create a new scope variable.
926 ///
927 DIE *DwarfDebug::NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
928   // Get the descriptor.
929   const DIVariable &VD = DV->getVariable();
930
931   // Translate tag to proper Dwarf tag.  The result variable is dropped for
932   // now.
933   unsigned Tag;
934   switch (VD.getTag()) {
935   case dwarf::DW_TAG_return_variable:
936     return NULL;
937   case dwarf::DW_TAG_arg_variable:
938     Tag = dwarf::DW_TAG_formal_parameter;
939     break;
940   case dwarf::DW_TAG_auto_variable:    // fall thru
941   default:
942     Tag = dwarf::DW_TAG_variable;
943     break;
944   }
945
946   // Define variable debug information entry.
947   DIE *VariableDie = new DIE(Tag);
948   std::string Name;
949   VD.getName(Name);
950   AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
951
952   // Add source line info if available.
953   AddSourceLine(VariableDie, &VD);
954
955   // Add variable type.
956   AddType(Unit, VariableDie, VD.getType());
957
958   // Add variable address.
959   MachineLocation Location;
960   Location.set(RI->getFrameRegister(*MF),
961                RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
962   AddAddress(VariableDie, dwarf::DW_AT_location, Location);
963
964   return VariableDie;
965 }
966
967 /// getOrCreateScope - Returns the scope associated with the given descriptor.
968 ///
969 DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
970   DbgScope *&Slot = DbgScopeMap[V];
971   if (Slot) return Slot;
972
973   DbgScope *Parent = NULL;
974   DIBlock Block(V);
975
976   // Don't create a new scope if we already created one for an inlined function.
977   DenseMap<const GlobalVariable *, DbgScope *>::iterator
978     II = AbstractInstanceRootMap.find(V);
979   if (II != AbstractInstanceRootMap.end())
980     return LexicalScopeStack.back();
981
982   if (!Block.isNull()) {
983     DIDescriptor ParentDesc = Block.getContext();
984     Parent =
985       ParentDesc.isNull() ?  NULL : getOrCreateScope(ParentDesc.getGV());
986   }
987
988   Slot = new DbgScope(Parent, DIDescriptor(V));
989
990   if (Parent)
991     Parent->AddScope(Slot);
992   else
993     // First function is top level function.
994     FunctionDbgScope = Slot;
995
996   return Slot;
997 }
998
999 /// ConstructDbgScope - Construct the components of a scope.
1000 ///
1001 void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1002                                    unsigned ParentStartID,
1003                                    unsigned ParentEndID,
1004                                    DIE *ParentDie, CompileUnit *Unit) {
1005   // Add variables to scope.
1006   SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1007   for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1008     DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
1009     if (VariableDie) ParentDie->AddChild(VariableDie);
1010   }
1011
1012   // Add concrete instances to scope.
1013   SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1014     ParentScope->getConcreteInsts();
1015   for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1016     DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1017     DIE *Die = ConcreteInst->getDie();
1018
1019     unsigned StartID = ConcreteInst->getStartLabelID();
1020     unsigned EndID = ConcreteInst->getEndLabelID();
1021
1022     // Add the scope bounds.
1023     if (StartID)
1024       AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1025                DWLabel("label", StartID));
1026     else
1027       AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1028                DWLabel("func_begin", SubprogramCount));
1029
1030     if (EndID)
1031       AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1032                DWLabel("label", EndID));
1033     else
1034       AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1035                DWLabel("func_end", SubprogramCount));
1036
1037     ParentDie->AddChild(Die);
1038   }
1039
1040   // Add nested scopes.
1041   SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1042   for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1043     // Define the Scope debug information entry.
1044     DbgScope *Scope = Scopes[j];
1045
1046     unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1047     unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1048
1049     // Ignore empty scopes.
1050     if (StartID == EndID && StartID != 0) continue;
1051
1052     // Do not ignore inlined scopes even if they don't have any variables or
1053     // scopes.
1054     if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1055         Scope->getConcreteInsts().empty())
1056       continue;
1057
1058     if (StartID == ParentStartID && EndID == ParentEndID) {
1059       // Just add stuff to the parent scope.
1060       ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1061     } else {
1062       DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1063
1064       // Add the scope bounds.
1065       if (StartID)
1066         AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1067                  DWLabel("label", StartID));
1068       else
1069         AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1070                  DWLabel("func_begin", SubprogramCount));
1071
1072       if (EndID)
1073         AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1074                  DWLabel("label", EndID));
1075       else
1076         AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1077                  DWLabel("func_end", SubprogramCount));
1078
1079       // Add the scope's contents.
1080       ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1081       ParentDie->AddChild(ScopeDie);
1082     }
1083   }
1084 }
1085
1086 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1087 ///
1088 void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope) {
1089   // Exit if there is no root scope.
1090   if (!RootScope) return;
1091   DIDescriptor Desc = RootScope->getDesc();
1092   if (Desc.isNull())
1093     return;
1094
1095   // Get the subprogram debug information entry.
1096   DISubprogram SPD(Desc.getGV());
1097
1098   // Get the compile unit context.
1099   CompileUnit *Unit = MainCU;
1100   if (!Unit)
1101     Unit = &FindCompileUnit(SPD.getCompileUnit());
1102
1103   // Get the subprogram die.
1104   DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1105   assert(SPDie && "Missing subprogram descriptor");
1106
1107   // Add the function bounds.
1108   AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1109            DWLabel("func_begin", SubprogramCount));
1110   AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1111            DWLabel("func_end", SubprogramCount));
1112   MachineLocation Location(RI->getFrameRegister(*MF));
1113   AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1114
1115   ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
1116 }
1117
1118 /// ConstructFunctionDbgScope - Construct the scope for the abstract debug
1119 /// scope.
1120 ///
1121 void DwarfDebug::ConstructAbstractDbgScope(DbgScope *AbsScope) {
1122   // Exit if there is no root scope.
1123   if (!AbsScope) return;
1124
1125   DIDescriptor Desc = AbsScope->getDesc();
1126   if (Desc.isNull())
1127     return;
1128
1129   // Get the subprogram debug information entry.
1130   DISubprogram SPD(Desc.getGV());
1131
1132   // Get the compile unit context.
1133   CompileUnit *Unit = MainCU;
1134   if (!Unit)
1135     Unit = &FindCompileUnit(SPD.getCompileUnit());
1136
1137   // Get the subprogram die.
1138   DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1139   assert(SPDie && "Missing subprogram descriptor");
1140
1141   ConstructDbgScope(AbsScope, 0, 0, SPDie, Unit);
1142 }
1143
1144 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1145 ///
1146 void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1147   const char *FnName = MF->getFunction()->getNameStart();
1148   if (MainCU) {
1149     StringMap<DIE*> &Globals = MainCU->getGlobals();
1150     StringMap<DIE*>::iterator GI = Globals.find(FnName);
1151     if (GI != Globals.end()) {
1152       DIE *SPDie = GI->second;
1153
1154       // Add the function bounds.
1155       AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1156                DWLabel("func_begin", SubprogramCount));
1157       AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1158                DWLabel("func_end", SubprogramCount));
1159
1160       MachineLocation Location(RI->getFrameRegister(*MF));
1161       AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1162       return;
1163     }
1164   } else {
1165     for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1166       CompileUnit *Unit = CompileUnits[i];
1167       StringMap<DIE*> &Globals = Unit->getGlobals();
1168       StringMap<DIE*>::iterator GI = Globals.find(FnName);
1169       if (GI != Globals.end()) {
1170         DIE *SPDie = GI->second;
1171
1172         // Add the function bounds.
1173         AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1174                  DWLabel("func_begin", SubprogramCount));
1175         AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1176                  DWLabel("func_end", SubprogramCount));
1177
1178         MachineLocation Location(RI->getFrameRegister(*MF));
1179         AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1180         return;
1181       }
1182     }
1183   }
1184
1185 #if 0
1186   // FIXME: This is causing an abort because C++ mangled names are compared with
1187   // their unmangled counterparts. See PR2885. Don't do this assert.
1188   assert(0 && "Couldn't find DIE for machine function!");
1189 #endif
1190 }
1191
1192 /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1193 /// tools to recognize the object file contains Dwarf information.
1194 void DwarfDebug::EmitInitial() {
1195   // Check to see if we already emitted intial headers.
1196   if (didInitial) return;
1197   didInitial = true;
1198
1199   // Dwarf sections base addresses.
1200   if (TAI->doesDwarfRequireFrameSection()) {
1201     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1202     EmitLabel("section_debug_frame", 0);
1203   }
1204
1205   Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1206   EmitLabel("section_info", 0);
1207   Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1208   EmitLabel("section_abbrev", 0);
1209   Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1210   EmitLabel("section_aranges", 0);
1211
1212   if (TAI->doesSupportMacInfoSection()) {
1213     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1214     EmitLabel("section_macinfo", 0);
1215   }
1216
1217   Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1218   EmitLabel("section_line", 0);
1219   Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1220   EmitLabel("section_loc", 0);
1221   Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1222   EmitLabel("section_pubnames", 0);
1223   Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1224   EmitLabel("section_str", 0);
1225   Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1226   EmitLabel("section_ranges", 0);
1227
1228   Asm->SwitchToSection(TAI->getTextSection());
1229   EmitLabel("text_begin", 0);
1230   Asm->SwitchToSection(TAI->getDataSection());
1231   EmitLabel("data_begin", 0);
1232 }
1233
1234 /// EmitDIE - Recusively Emits a debug information entry.
1235 ///
1236 void DwarfDebug::EmitDIE(DIE *Die) {
1237   // Get the abbreviation for this DIE.
1238   unsigned AbbrevNumber = Die->getAbbrevNumber();
1239   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1240
1241   Asm->EOL();
1242
1243   // Emit the code (index) for the abbreviation.
1244   Asm->EmitULEB128Bytes(AbbrevNumber);
1245
1246   if (Asm->isVerbose())
1247     Asm->EOL(std::string("Abbrev [" +
1248                          utostr(AbbrevNumber) +
1249                          "] 0x" + utohexstr(Die->getOffset()) +
1250                          ":0x" + utohexstr(Die->getSize()) + " " +
1251                          dwarf::TagString(Abbrev->getTag())));
1252   else
1253     Asm->EOL();
1254
1255   SmallVector<DIEValue*, 32> &Values = Die->getValues();
1256   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1257
1258   // Emit the DIE attribute values.
1259   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1260     unsigned Attr = AbbrevData[i].getAttribute();
1261     unsigned Form = AbbrevData[i].getForm();
1262     assert(Form && "Too many attributes for DIE (check abbreviation)");
1263
1264     switch (Attr) {
1265     case dwarf::DW_AT_sibling:
1266       Asm->EmitInt32(Die->SiblingOffset());
1267       break;
1268     case dwarf::DW_AT_abstract_origin: {
1269       DIEEntry *E = cast<DIEEntry>(Values[i]);
1270       DIE *Origin = E->getEntry();
1271       unsigned Addr =
1272         CompileUnitOffsets[Die->getAbstractCompileUnit()] +
1273         Origin->getOffset();
1274
1275       Asm->EmitInt32(Addr);
1276       break;
1277     }
1278     default:
1279       // Emit an attribute using the defined form.
1280       Values[i]->EmitValue(this, Form);
1281       break;
1282     }
1283
1284     Asm->EOL(dwarf::AttributeString(Attr));
1285   }
1286
1287   // Emit the DIE children if any.
1288   if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1289     const std::vector<DIE *> &Children = Die->getChildren();
1290
1291     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1292       EmitDIE(Children[j]);
1293
1294     Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1295   }
1296 }
1297
1298 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1299 ///
1300 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1301   // Get the children.
1302   const std::vector<DIE *> &Children = Die->getChildren();
1303
1304   // If not last sibling and has children then add sibling offset attribute.
1305   if (!Last && !Children.empty()) Die->AddSiblingOffset();
1306
1307   // Record the abbreviation.
1308   AssignAbbrevNumber(Die->getAbbrev());
1309
1310   // Get the abbreviation for this DIE.
1311   unsigned AbbrevNumber = Die->getAbbrevNumber();
1312   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1313
1314   // Set DIE offset
1315   Die->setOffset(Offset);
1316
1317   // Start the size with the size of abbreviation code.
1318   Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1319
1320   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1321   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1322
1323   // Size the DIE attribute values.
1324   for (unsigned i = 0, N = Values.size(); i < N; ++i)
1325     // Size attribute value.
1326     Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1327
1328   // Size the DIE children if any.
1329   if (!Children.empty()) {
1330     assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1331            "Children flag not set");
1332
1333     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1334       Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1335
1336     // End of children marker.
1337     Offset += sizeof(int8_t);
1338   }
1339
1340   Die->setSize(Offset - Die->getOffset());
1341   return Offset;
1342 }
1343
1344 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1345 ///
1346 void DwarfDebug::SizeAndOffsets() {
1347   // Compute size of compile unit header.
1348   static unsigned Offset =
1349     sizeof(int32_t) + // Length of Compilation Unit Info
1350     sizeof(int16_t) + // DWARF version number
1351     sizeof(int32_t) + // Offset Into Abbrev. Section
1352     sizeof(int8_t);   // Pointer Size (in bytes)
1353
1354   // Process base compile unit.
1355   if (MainCU) {
1356     SizeAndOffsetDie(MainCU->getDie(), Offset, true);
1357     CompileUnitOffsets[MainCU] = 0;
1358     return;
1359   }
1360
1361   // Process all compile units.
1362   unsigned PrevOffset = 0;
1363
1364   for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1365     CompileUnit *Unit = CompileUnits[i];
1366     CompileUnitOffsets[Unit] = PrevOffset;
1367     PrevOffset += SizeAndOffsetDie(Unit->getDie(), Offset, true)
1368       + sizeof(int32_t);  // FIXME - extra pad for gdb bug.
1369   }
1370 }
1371
1372 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
1373 ///
1374 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
1375   DIE *Die = Unit->getDie();
1376
1377   // Emit the compile units header.
1378   EmitLabel("info_begin", Unit->getID());
1379
1380   // Emit size of content not including length itself
1381   unsigned ContentSize = Die->getSize() +
1382     sizeof(int16_t) + // DWARF version number
1383     sizeof(int32_t) + // Offset Into Abbrev. Section
1384     sizeof(int8_t) +  // Pointer Size (in bytes)
1385     sizeof(int32_t);  // FIXME - extra pad for gdb bug.
1386
1387   Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
1388   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1389   EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
1390   Asm->EOL("Offset Into Abbrev. Section");
1391   Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1392
1393   EmitDIE(Die);
1394   // FIXME - extra padding for gdb bug.
1395   Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1396   Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1397   Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1398   Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1399   EmitLabel("info_end", Unit->getID());
1400
1401   Asm->EOL();
1402 }
1403
1404 void DwarfDebug::EmitDebugInfo() {
1405   // Start debug info section.
1406   Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1407
1408   if (MainCU) {
1409     EmitDebugInfoPerCU(MainCU);
1410     return;
1411   }
1412
1413   for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1414     EmitDebugInfoPerCU(CompileUnits[i]);
1415 }
1416
1417 /// EmitAbbreviations - Emit the abbreviation section.
1418 ///
1419 void DwarfDebug::EmitAbbreviations() const {
1420   // Check to see if it is worth the effort.
1421   if (!Abbreviations.empty()) {
1422     // Start the debug abbrev section.
1423     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1424
1425     EmitLabel("abbrev_begin", 0);
1426
1427     // For each abbrevation.
1428     for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1429       // Get abbreviation data
1430       const DIEAbbrev *Abbrev = Abbreviations[i];
1431
1432       // Emit the abbrevations code (base 1 index.)
1433       Asm->EmitULEB128Bytes(Abbrev->getNumber());
1434       Asm->EOL("Abbreviation Code");
1435
1436       // Emit the abbreviations data.
1437       Abbrev->Emit(Asm);
1438
1439       Asm->EOL();
1440     }
1441
1442     // Mark end of abbreviations.
1443     Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
1444
1445     EmitLabel("abbrev_end", 0);
1446     Asm->EOL();
1447   }
1448 }
1449
1450 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
1451 /// the line matrix.
1452 ///
1453 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
1454   // Define last address of section.
1455   Asm->EmitInt8(0); Asm->EOL("Extended Op");
1456   Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1457   Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1458   EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
1459
1460   // Mark end of matrix.
1461   Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
1462   Asm->EmitULEB128Bytes(1); Asm->EOL();
1463   Asm->EmitInt8(1); Asm->EOL();
1464 }
1465
1466 /// EmitDebugLines - Emit source line information.
1467 ///
1468 void DwarfDebug::EmitDebugLines() {
1469   // If the target is using .loc/.file, the assembler will be emitting the
1470   // .debug_line table automatically.
1471   if (TAI->hasDotLocAndDotFile())
1472     return;
1473
1474   // Minimum line delta, thus ranging from -10..(255-10).
1475   const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
1476   // Maximum line delta, thus ranging from -10..(255-10).
1477   const int MaxLineDelta = 255 + MinLineDelta;
1478
1479   // Start the dwarf line section.
1480   Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1481
1482   // Construct the section header.
1483   EmitDifference("line_end", 0, "line_begin", 0, true);
1484   Asm->EOL("Length of Source Line Info");
1485   EmitLabel("line_begin", 0);
1486
1487   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1488
1489   EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
1490   Asm->EOL("Prolog Length");
1491   EmitLabel("line_prolog_begin", 0);
1492
1493   Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
1494
1495   Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
1496
1497   Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
1498
1499   Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
1500
1501   Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
1502
1503   // Line number standard opcode encodings argument count
1504   Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
1505   Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
1506   Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
1507   Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
1508   Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
1509   Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
1510   Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
1511   Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
1512   Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
1513
1514   // Emit directories.
1515   for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
1516     Asm->EmitString(getSourceDirectoryName(DI));
1517     Asm->EOL("Directory");
1518   }
1519
1520   Asm->EmitInt8(0); Asm->EOL("End of directories");
1521
1522   // Emit files.
1523   for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
1524     // Remember source id starts at 1.
1525     std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
1526     Asm->EmitString(getSourceFileName(Id.second));
1527     Asm->EOL("Source");
1528     Asm->EmitULEB128Bytes(Id.first);
1529     Asm->EOL("Directory #");
1530     Asm->EmitULEB128Bytes(0);
1531     Asm->EOL("Mod date");
1532     Asm->EmitULEB128Bytes(0);
1533     Asm->EOL("File size");
1534   }
1535
1536   Asm->EmitInt8(0); Asm->EOL("End of files");
1537
1538   EmitLabel("line_prolog_end", 0);
1539
1540   // A sequence for each text section.
1541   unsigned SecSrcLinesSize = SectionSourceLines.size();
1542
1543   for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
1544     // Isolate current sections line info.
1545     const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
1546
1547     if (Asm->isVerbose()) {
1548       const Section* S = SectionMap[j + 1];
1549       O << '\t' << TAI->getCommentString() << " Section"
1550         << S->getName() << '\n';
1551     } else {
1552       Asm->EOL();
1553     }
1554
1555     // Dwarf assumes we start with first line of first source file.
1556     unsigned Source = 1;
1557     unsigned Line = 1;
1558
1559     // Construct rows of the address, source, line, column matrix.
1560     for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
1561       const SrcLineInfo &LineInfo = LineInfos[i];
1562       unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
1563       if (!LabelID) continue;
1564
1565       if (!Asm->isVerbose())
1566         Asm->EOL();
1567       else {
1568         std::pair<unsigned, unsigned> SourceID =
1569           getSourceDirectoryAndFileIds(LineInfo.getSourceID());
1570         O << '\t' << TAI->getCommentString() << ' '
1571           << getSourceDirectoryName(SourceID.first) << ' '
1572           << getSourceFileName(SourceID.second)
1573           <<" :" << utostr_32(LineInfo.getLine()) << '\n';
1574       }
1575
1576       // Define the line address.
1577       Asm->EmitInt8(0); Asm->EOL("Extended Op");
1578       Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1579       Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1580       EmitReference("label",  LabelID); Asm->EOL("Location label");
1581
1582       // If change of source, then switch to the new source.
1583       if (Source != LineInfo.getSourceID()) {
1584         Source = LineInfo.getSourceID();
1585         Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
1586         Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
1587       }
1588
1589       // If change of line.
1590       if (Line != LineInfo.getLine()) {
1591         // Determine offset.
1592         int Offset = LineInfo.getLine() - Line;
1593         int Delta = Offset - MinLineDelta;
1594
1595         // Update line.
1596         Line = LineInfo.getLine();
1597
1598         // If delta is small enough and in range...
1599         if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
1600           // ... then use fast opcode.
1601           Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
1602         } else {
1603           // ... otherwise use long hand.
1604           Asm->EmitInt8(dwarf::DW_LNS_advance_line);
1605           Asm->EOL("DW_LNS_advance_line");
1606           Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
1607           Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1608         }
1609       } else {
1610         // Copy the previous row (different address or source)
1611         Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1612       }
1613     }
1614
1615     EmitEndOfLineMatrix(j + 1);
1616   }
1617
1618   if (SecSrcLinesSize == 0)
1619     // Because we're emitting a debug_line section, we still need a line
1620     // table. The linker and friends expect it to exist. If there's nothing to
1621     // put into it, emit an empty table.
1622     EmitEndOfLineMatrix(1);
1623
1624   EmitLabel("line_end", 0);
1625   Asm->EOL();
1626 }
1627
1628 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
1629 ///
1630 void DwarfDebug::EmitCommonDebugFrame() {
1631   if (!TAI->doesDwarfRequireFrameSection())
1632     return;
1633
1634   int stackGrowth =
1635     Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1636       TargetFrameInfo::StackGrowsUp ?
1637     TD->getPointerSize() : -TD->getPointerSize();
1638
1639   // Start the dwarf frame section.
1640   Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1641
1642   EmitLabel("debug_frame_common", 0);
1643   EmitDifference("debug_frame_common_end", 0,
1644                  "debug_frame_common_begin", 0, true);
1645   Asm->EOL("Length of Common Information Entry");
1646
1647   EmitLabel("debug_frame_common_begin", 0);
1648   Asm->EmitInt32((int)dwarf::DW_CIE_ID);
1649   Asm->EOL("CIE Identifier Tag");
1650   Asm->EmitInt8(dwarf::DW_CIE_VERSION);
1651   Asm->EOL("CIE Version");
1652   Asm->EmitString("");
1653   Asm->EOL("CIE Augmentation");
1654   Asm->EmitULEB128Bytes(1);
1655   Asm->EOL("CIE Code Alignment Factor");
1656   Asm->EmitSLEB128Bytes(stackGrowth);
1657   Asm->EOL("CIE Data Alignment Factor");
1658   Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
1659   Asm->EOL("CIE RA Column");
1660
1661   std::vector<MachineMove> Moves;
1662   RI->getInitialFrameState(Moves);
1663
1664   EmitFrameMoves(NULL, 0, Moves, false);
1665
1666   Asm->EmitAlignment(2, 0, 0, false);
1667   EmitLabel("debug_frame_common_end", 0);
1668
1669   Asm->EOL();
1670 }
1671
1672 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
1673 /// section.
1674 void
1675 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
1676   if (!TAI->doesDwarfRequireFrameSection())
1677     return;
1678
1679   // Start the dwarf frame section.
1680   Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1681
1682   EmitDifference("debug_frame_end", DebugFrameInfo.Number,
1683                  "debug_frame_begin", DebugFrameInfo.Number, true);
1684   Asm->EOL("Length of Frame Information Entry");
1685
1686   EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
1687
1688   EmitSectionOffset("debug_frame_common", "section_debug_frame",
1689                     0, 0, true, false);
1690   Asm->EOL("FDE CIE offset");
1691
1692   EmitReference("func_begin", DebugFrameInfo.Number);
1693   Asm->EOL("FDE initial location");
1694   EmitDifference("func_end", DebugFrameInfo.Number,
1695                  "func_begin", DebugFrameInfo.Number);
1696   Asm->EOL("FDE address range");
1697
1698   EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
1699                  false);
1700
1701   Asm->EmitAlignment(2, 0, 0, false);
1702   EmitLabel("debug_frame_end", DebugFrameInfo.Number);
1703
1704   Asm->EOL();
1705 }
1706
1707 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
1708   EmitDifference("pubnames_end", Unit->getID(),
1709                  "pubnames_begin", Unit->getID(), true);
1710   Asm->EOL("Length of Public Names Info");
1711
1712   EmitLabel("pubnames_begin", Unit->getID());
1713
1714   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
1715
1716   EmitSectionOffset("info_begin", "section_info",
1717                     Unit->getID(), 0, true, false);
1718   Asm->EOL("Offset of Compilation Unit Info");
1719
1720   EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
1721                  true);
1722   Asm->EOL("Compilation Unit Length");
1723
1724   StringMap<DIE*> &Globals = Unit->getGlobals();
1725   for (StringMap<DIE*>::const_iterator
1726          GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1727     const char *Name = GI->getKeyData();
1728     DIE * Entity = GI->second;
1729
1730     Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
1731     Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
1732   }
1733
1734   Asm->EmitInt32(0); Asm->EOL("End Mark");
1735   EmitLabel("pubnames_end", Unit->getID());
1736
1737   Asm->EOL();
1738 }
1739
1740 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
1741 ///
1742 void DwarfDebug::EmitDebugPubNames() {
1743   // Start the dwarf pubnames section.
1744   Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1745
1746   if (MainCU) {
1747     EmitDebugPubNamesPerCU(MainCU);
1748     return;
1749   }
1750
1751   for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1752     EmitDebugPubNamesPerCU(CompileUnits[i]);
1753 }
1754
1755 /// EmitDebugStr - Emit visible names into a debug str section.
1756 ///
1757 void DwarfDebug::EmitDebugStr() {
1758   // Check to see if it is worth the effort.
1759   if (!StringPool.empty()) {
1760     // Start the dwarf str section.
1761     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1762
1763     // For each of strings in the string pool.
1764     for (unsigned StringID = 1, N = StringPool.size();
1765          StringID <= N; ++StringID) {
1766       // Emit a label for reference from debug information entries.
1767       EmitLabel("string", StringID);
1768
1769       // Emit the string itself.
1770       const std::string &String = StringPool[StringID];
1771       Asm->EmitString(String); Asm->EOL();
1772     }
1773
1774     Asm->EOL();
1775   }
1776 }
1777
1778 /// EmitDebugLoc - Emit visible names into a debug loc section.
1779 ///
1780 void DwarfDebug::EmitDebugLoc() {
1781   // Start the dwarf loc section.
1782   Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1783   Asm->EOL();
1784 }
1785
1786 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1787 ///
1788 void DwarfDebug::EmitDebugARanges() {
1789   // Start the dwarf aranges section.
1790   Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1791
1792   // FIXME - Mock up
1793 #if 0
1794   CompileUnit *Unit = GetBaseCompileUnit();
1795
1796   // Don't include size of length
1797   Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
1798
1799   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
1800
1801   EmitReference("info_begin", Unit->getID());
1802   Asm->EOL("Offset of Compilation Unit Info");
1803
1804   Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
1805
1806   Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
1807
1808   Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
1809   Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
1810
1811   // Range 1
1812   EmitReference("text_begin", 0); Asm->EOL("Address");
1813   EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
1814
1815   Asm->EmitInt32(0); Asm->EOL("EOM (1)");
1816   Asm->EmitInt32(0); Asm->EOL("EOM (2)");
1817 #endif
1818
1819   Asm->EOL();
1820 }
1821
1822 /// EmitDebugRanges - Emit visible names into a debug ranges section.
1823 ///
1824 void DwarfDebug::EmitDebugRanges() {
1825   // Start the dwarf ranges section.
1826   Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1827   Asm->EOL();
1828 }
1829
1830 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
1831 ///
1832 void DwarfDebug::EmitDebugMacInfo() {
1833   if (TAI->doesSupportMacInfoSection()) {
1834     // Start the dwarf macinfo section.
1835     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1836     Asm->EOL();
1837   }
1838 }
1839
1840 /// EmitDebugInlineInfo - Emit inline info using following format.
1841 /// Section Header:
1842 /// 1. length of section
1843 /// 2. Dwarf version number
1844 /// 3. address size.
1845 ///
1846 /// Entries (one "entry" for each function that was inlined):
1847 ///
1848 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1849 ///   otherwise offset into __debug_str for regular function name.
1850 /// 2. offset into __debug_str section for regular function name.
1851 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1852 /// instances for the function.
1853 ///
1854 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1855 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1856 /// __debug_info section, and the low_pc is the starting address for the
1857 /// inlining instance.
1858 void DwarfDebug::EmitDebugInlineInfo() {
1859   if (!TAI->doesDwarfUsesInlineInfoSection())
1860     return;
1861
1862   if (!MainCU)
1863     return;
1864
1865   Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
1866   Asm->EOL();
1867   EmitDifference("debug_inlined_end", 1,
1868                  "debug_inlined_begin", 1, true);
1869   Asm->EOL("Length of Debug Inlined Information Entry");
1870
1871   EmitLabel("debug_inlined_begin", 1);
1872
1873   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
1874   Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1875
1876   for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1877          I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
1878     GlobalVariable *GV = I->first;
1879     SmallVector<unsigned, 4> &Labels = I->second;
1880     DISubprogram SP(GV);
1881     std::string Name;
1882     std::string LName;
1883
1884     SP.getLinkageName(LName);
1885     SP.getName(Name);
1886
1887     Asm->EmitString(LName.empty() ? Name : LName);
1888     Asm->EOL("MIPS linkage name");
1889
1890     Asm->EmitString(Name); Asm->EOL("Function name");
1891
1892     Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
1893
1894     for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
1895            LE = Labels.end(); LI != LE; ++LI) {
1896       DIE *SP = MainCU->getDieMapSlotFor(GV);
1897       Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
1898
1899       if (TD->getPointerSize() == sizeof(int32_t))
1900         O << TAI->getData32bitsDirective();
1901       else
1902         O << TAI->getData64bitsDirective();
1903
1904       PrintLabelName("label", *LI); Asm->EOL("low_pc");
1905     }
1906   }
1907
1908   EmitLabel("debug_inlined_end", 1);
1909   Asm->EOL();
1910 }
1911
1912 /// GetOrCreateSourceID - Look up the source id with the given directory and
1913 /// source file names. If none currently exists, create a new id and insert it
1914 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1915 /// maps as well.
1916 unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1917                                          const std::string &FileName) {
1918   unsigned DId;
1919   StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1920   if (DI != DirectoryIdMap.end()) {
1921     DId = DI->getValue();
1922   } else {
1923     DId = DirectoryNames.size() + 1;
1924     DirectoryIdMap[DirName] = DId;
1925     DirectoryNames.push_back(DirName);
1926   }
1927
1928   unsigned FId;
1929   StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1930   if (FI != SourceFileIdMap.end()) {
1931     FId = FI->getValue();
1932   } else {
1933     FId = SourceFileNames.size() + 1;
1934     SourceFileIdMap[FileName] = FId;
1935     SourceFileNames.push_back(FileName);
1936   }
1937
1938   DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1939     SourceIdMap.find(std::make_pair(DId, FId));
1940   if (SI != SourceIdMap.end())
1941     return SI->second;
1942
1943   unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
1944   SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1945   SourceIds.push_back(std::make_pair(DId, FId));
1946
1947   return SrcId;
1948 }
1949
1950 void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1951   DICompileUnit DIUnit(GV);
1952   std::string Dir, FN, Prod;
1953   unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1954                                     DIUnit.getFilename(FN));
1955
1956   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1957   AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1958                    DWLabel("section_line", 0), DWLabel("section_line", 0),
1959                    false);
1960   AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1961             DIUnit.getProducer(Prod));
1962   AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1963           DIUnit.getLanguage());
1964   AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1965
1966   if (!Dir.empty())
1967     AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1968   if (DIUnit.isOptimized())
1969     AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1970
1971   std::string Flags;
1972   DIUnit.getFlags(Flags);
1973   if (!Flags.empty())
1974     AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1975
1976   unsigned RVer = DIUnit.getRunTimeVersion();
1977   if (RVer)
1978     AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1979             dwarf::DW_FORM_data1, RVer);
1980
1981   CompileUnit *Unit = new CompileUnit(ID, Die);
1982   if (DIUnit.isMain()) {
1983     assert(!MainCU && "Multiple main compile units are found!");
1984     MainCU = Unit;
1985     }
1986
1987   CompileUnitMap[DIUnit.getGV()] = Unit;
1988   CompileUnits.push_back(Unit);
1989 }
1990
1991 /// ConstructCompileUnits - Create a compile unit DIEs.
1992 void DwarfDebug::ConstructCompileUnits() {
1993   GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
1994   if (!Root)
1995     return;
1996   assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1997          "Malformed compile unit descriptor anchor type");
1998   Constant *RootC = cast<Constant>(*Root->use_begin());
1999   assert(RootC->hasNUsesOrMore(1) &&
2000          "Malformed compile unit descriptor anchor type");
2001
2002   for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2003        UI != UE; ++UI)
2004     for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2005          UUI != UUE; ++UUI) {
2006       GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2007       ConstructCompileUnit(GV);
2008     }
2009 }
2010
2011 bool DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
2012   DIGlobalVariable DI_GV(GV);
2013   CompileUnit *DW_Unit = MainCU;
2014   if (!DW_Unit)
2015     DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
2016
2017   // Check for pre-existence.
2018   DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2019   if (Slot)
2020     return false;
2021
2022   DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2023
2024   // Add address.
2025   DIEBlock *Block = new DIEBlock();
2026   AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
2027   std::string GLN;
2028   AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
2029                  Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
2030   AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
2031
2032   // Add to map.
2033   Slot = VariableDie;
2034
2035   // Add to context owner.
2036   DW_Unit->getDie()->AddChild(VariableDie);
2037
2038   // Expose as global. FIXME - need to check external flag.
2039   std::string Name;
2040   DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2041   return true;
2042 }
2043
2044 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally visible
2045 /// global variables. Return true if at least one global DIE is created.
2046 bool DwarfDebug::ConstructGlobalVariableDIEs() {
2047   GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2048   if (!Root)
2049     return false;
2050
2051   assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2052          "Malformed global variable descriptor anchor type");
2053   Constant *RootC = cast<Constant>(*Root->use_begin());
2054   assert(RootC->hasNUsesOrMore(1) &&
2055          "Malformed global variable descriptor anchor type");
2056
2057   bool Result = false;
2058   for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2059        UI != UE; ++UI)
2060     for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2061          UUI != UUE; ++UUI)
2062       Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
2063
2064   return Result;
2065 }
2066
2067 bool DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
2068   DISubprogram SP(GV);
2069   CompileUnit *Unit = MainCU;
2070   if (!Unit)
2071     Unit = &FindCompileUnit(SP.getCompileUnit());
2072
2073   // Check for pre-existence.
2074   DIE *&Slot = Unit->getDieMapSlotFor(GV);
2075   if (Slot)
2076     return false;
2077
2078   if (!SP.isDefinition())
2079     // This is a method declaration which will be handled while constructing
2080     // class type.
2081     return false;
2082
2083   DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2084
2085   // Add to map.
2086   Slot = SubprogramDie;
2087
2088   // Add to context owner.
2089   Unit->getDie()->AddChild(SubprogramDie);
2090
2091   // Expose as global.
2092   std::string Name;
2093   Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2094   return true;
2095 }
2096
2097 /// ConstructSubprograms - Create DIEs for each of the externally visible
2098 /// subprograms. Return true if at least one subprogram DIE is created.
2099 bool DwarfDebug::ConstructSubprograms() {
2100   GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2101   if (!Root)
2102     return false;
2103
2104   assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2105          "Malformed subprogram descriptor anchor type");
2106   Constant *RootC = cast<Constant>(*Root->use_begin());
2107   assert(RootC->hasNUsesOrMore(1) &&
2108          "Malformed subprogram descriptor anchor type");
2109
2110   bool Result = false;
2111   for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2112        UI != UE; ++UI)
2113     for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2114          UUI != UUE; ++UUI)
2115       Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
2116
2117   return Result;
2118 }
2119
2120 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2121 /// This is inovked by the target AsmPrinter.
2122 void DwarfDebug::SetDebugInfo(MachineModuleInfo *mmi) {
2123   if (TimePassesIsEnabled)
2124     DebugTimer->startTimer();
2125
2126   // Create all the compile unit DIEs.
2127   ConstructCompileUnits();
2128
2129   if (CompileUnits.empty()) {
2130     if (TimePassesIsEnabled)
2131       DebugTimer->stopTimer();
2132
2133     return;
2134   }
2135
2136   // Create DIEs for each of the externally visible global variables.
2137   bool globalDIEs = ConstructGlobalVariableDIEs();
2138
2139   // Create DIEs for each of the externally visible subprograms.
2140   bool subprogramDIEs = ConstructSubprograms();
2141
2142   // If there is not any debug info available for any global variables and any
2143   // subprograms then there is not any debug info to emit.
2144   if (!globalDIEs && !subprogramDIEs) {
2145     if (TimePassesIsEnabled)
2146       DebugTimer->stopTimer();
2147
2148     return;
2149   }
2150
2151   MMI = mmi;
2152   shouldEmit = true;
2153   MMI->setDebugInfoAvailability(true);
2154
2155   // Prime section data.
2156   SectionMap.insert(TAI->getTextSection());
2157
2158   // Print out .file directives to specify files for .loc directives. These are
2159   // printed out early so that they precede any .loc directives.
2160   if (TAI->hasDotLocAndDotFile()) {
2161     for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2162       // Remember source id starts at 1.
2163       std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2164       sys::Path FullPath(getSourceDirectoryName(Id.first));
2165       bool AppendOk =
2166         FullPath.appendComponent(getSourceFileName(Id.second));
2167       assert(AppendOk && "Could not append filename to directory!");
2168       AppendOk = false;
2169       Asm->EmitFile(i, FullPath.toString());
2170       Asm->EOL();
2171     }
2172   }
2173
2174   // Emit initial sections
2175   EmitInitial();
2176
2177   if (TimePassesIsEnabled)
2178     DebugTimer->stopTimer();
2179 }
2180
2181 /// EndModule - Emit all Dwarf sections that should come after the content.
2182 ///
2183 void DwarfDebug::EndModule() {
2184   if (!ShouldEmitDwarfDebug())
2185     return;
2186
2187   if (TimePassesIsEnabled)
2188     DebugTimer->startTimer();
2189
2190   // Standard sections final addresses.
2191   Asm->SwitchToSection(TAI->getTextSection());
2192   EmitLabel("text_end", 0);
2193   Asm->SwitchToSection(TAI->getDataSection());
2194   EmitLabel("data_end", 0);
2195
2196   // End text sections.
2197   for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2198     Asm->SwitchToSection(SectionMap[i]);
2199     EmitLabel("section_end", i);
2200   }
2201
2202   // Emit common frame information.
2203   EmitCommonDebugFrame();
2204
2205   // Emit function debug frame information
2206   for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2207          E = DebugFrames.end(); I != E; ++I)
2208     EmitFunctionDebugFrame(*I);
2209
2210   // Compute DIE offsets and sizes.
2211   SizeAndOffsets();
2212
2213   // Emit all the DIEs into a debug info section
2214   EmitDebugInfo();
2215
2216   // Corresponding abbreviations into a abbrev section.
2217   EmitAbbreviations();
2218
2219   // Emit source line correspondence into a debug line section.
2220   EmitDebugLines();
2221
2222   // Emit info into a debug pubnames section.
2223   EmitDebugPubNames();
2224
2225   // Emit info into a debug str section.
2226   EmitDebugStr();
2227
2228   // Emit info into a debug loc section.
2229   EmitDebugLoc();
2230
2231   // Emit info into a debug aranges section.
2232   EmitDebugARanges();
2233
2234   // Emit info into a debug ranges section.
2235   EmitDebugRanges();
2236
2237   // Emit info into a debug macinfo section.
2238   EmitDebugMacInfo();
2239
2240   // Emit inline info.
2241   EmitDebugInlineInfo();
2242
2243   if (TimePassesIsEnabled)
2244     DebugTimer->stopTimer();
2245 }
2246
2247 /// BeginFunction - Gather pre-function debug information.  Assumes being
2248 /// emitted immediately after the function entry point.
2249 void DwarfDebug::BeginFunction(MachineFunction *MF) {
2250   this->MF = MF;
2251
2252   if (!ShouldEmitDwarfDebug()) return;
2253
2254   if (TimePassesIsEnabled)
2255     DebugTimer->startTimer();
2256
2257   // Begin accumulating function debug information.
2258   MMI->BeginFunction(MF);
2259
2260   // Assumes in correct section after the entry point.
2261   EmitLabel("func_begin", ++SubprogramCount);
2262
2263   // Emit label for the implicitly defined dbg.stoppoint at the start of the
2264   // function.
2265   DebugLoc FDL = MF->getDefaultDebugLoc();
2266   if (!FDL.isUnknown()) {
2267     DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2268     unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
2269                                         DICompileUnit(DLT.CompileUnit));
2270     Asm->printLabel(LabelID);
2271   }
2272
2273   if (TimePassesIsEnabled)
2274     DebugTimer->stopTimer();
2275 }
2276
2277 /// EndFunction - Gather and emit post-function debug information.
2278 ///
2279 void DwarfDebug::EndFunction(MachineFunction *MF) {
2280   if (!ShouldEmitDwarfDebug()) return;
2281
2282   if (TimePassesIsEnabled)
2283     DebugTimer->startTimer();
2284
2285   // Define end label for subprogram.
2286   EmitLabel("func_end", SubprogramCount);
2287
2288   // Get function line info.
2289   if (!Lines.empty()) {
2290     // Get section line info.
2291     unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2292     if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2293     std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2294     // Append the function info to section info.
2295     SectionLineInfos.insert(SectionLineInfos.end(),
2296                             Lines.begin(), Lines.end());
2297   }
2298
2299   // Construct the DbgScope for abstract instances.
2300   for (SmallVector<DbgScope *, 32>::iterator
2301          I = AbstractInstanceRootList.begin(),
2302          E = AbstractInstanceRootList.end(); I != E; ++I)
2303     ConstructAbstractDbgScope(*I);
2304
2305   // Construct scopes for subprogram.
2306   if (FunctionDbgScope)
2307     ConstructFunctionDbgScope(FunctionDbgScope);
2308   else
2309     // FIXME: This is wrong. We are essentially getting past a problem with
2310     // debug information not being able to handle unreachable blocks that have
2311     // debug information in them. In particular, those unreachable blocks that
2312     // have "region end" info in them. That situation results in the "root
2313     // scope" not being created. If that's the case, then emit a "default"
2314     // scope, i.e., one that encompasses the whole function. This isn't
2315     // desirable. And a better way of handling this (and all of the debugging
2316     // information) needs to be explored.
2317     ConstructDefaultDbgScope(MF);
2318
2319   DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2320                                                MMI->getFrameMoves()));
2321
2322   // Clear debug info
2323   if (FunctionDbgScope) {
2324     delete FunctionDbgScope;
2325     DbgScopeMap.clear();
2326     DbgAbstractScopeMap.clear();
2327     DbgConcreteScopeMap.clear();
2328     InlinedVariableScopes.clear();
2329     FunctionDbgScope = NULL;
2330     LexicalScopeStack.clear();
2331     AbstractInstanceRootList.clear();
2332   }
2333
2334   Lines.clear();
2335
2336   if (TimePassesIsEnabled)
2337     DebugTimer->stopTimer();
2338 }
2339
2340 /// RecordSourceLine - Records location information and associates it with a
2341 /// label. Returns a unique label ID used to generate a label and provide
2342 /// correspondence to the source line list.
2343 unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2344   if (TimePassesIsEnabled)
2345     DebugTimer->startTimer();
2346
2347   CompileUnit *Unit = CompileUnitMap[V];
2348   assert(Unit && "Unable to find CompileUnit");
2349   unsigned ID = MMI->NextLabelID();
2350   Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2351
2352   if (TimePassesIsEnabled)
2353     DebugTimer->stopTimer();
2354
2355   return ID;
2356 }
2357
2358 /// RecordSourceLine - Records location information and associates it with a
2359 /// label. Returns a unique label ID used to generate a label and provide
2360 /// correspondence to the source line list.
2361 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
2362                                       DICompileUnit CU) {
2363   if (TimePassesIsEnabled)
2364     DebugTimer->startTimer();
2365
2366   std::string Dir, Fn;
2367   unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
2368                                      CU.getFilename(Fn));
2369   unsigned ID = MMI->NextLabelID();
2370   Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2371
2372   if (TimePassesIsEnabled)
2373     DebugTimer->stopTimer();
2374
2375   return ID;
2376 }
2377
2378 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2379 /// timed. Look up the source id with the given directory and source file
2380 /// names. If none currently exists, create a new id and insert it in the
2381 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2382 /// well.
2383 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2384                                          const std::string &FileName) {
2385   if (TimePassesIsEnabled)
2386     DebugTimer->startTimer();
2387
2388   unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
2389
2390   if (TimePassesIsEnabled)
2391     DebugTimer->stopTimer();
2392
2393   return SrcId;
2394 }
2395
2396 /// RecordRegionStart - Indicate the start of a region.
2397 unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
2398   if (TimePassesIsEnabled)
2399     DebugTimer->startTimer();
2400
2401   DbgScope *Scope = getOrCreateScope(V);
2402   unsigned ID = MMI->NextLabelID();
2403   if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2404   LexicalScopeStack.push_back(Scope);
2405
2406   if (TimePassesIsEnabled)
2407     DebugTimer->stopTimer();
2408
2409   return ID;
2410 }
2411
2412 /// RecordRegionEnd - Indicate the end of a region.
2413 unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
2414   if (TimePassesIsEnabled)
2415     DebugTimer->startTimer();
2416
2417   DbgScope *Scope = getOrCreateScope(V);
2418   unsigned ID = MMI->NextLabelID();
2419   Scope->setEndLabelID(ID);
2420   if (LexicalScopeStack.size() != 0)
2421     LexicalScopeStack.pop_back();
2422
2423   if (TimePassesIsEnabled)
2424     DebugTimer->stopTimer();
2425
2426   return ID;
2427 }
2428
2429 /// RecordVariable - Indicate the declaration of a local variable.
2430 void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
2431                                 const MachineInstr *MI) {
2432   if (TimePassesIsEnabled)
2433     DebugTimer->startTimer();
2434
2435   DIDescriptor Desc(GV);
2436   DbgScope *Scope = NULL;
2437
2438   if (Desc.getTag() == dwarf::DW_TAG_variable) {
2439     // GV is a global variable.
2440     DIGlobalVariable DG(GV);
2441     Scope = getOrCreateScope(DG.getContext().getGV());
2442   } else {
2443     DenseMap<const MachineInstr *, DbgScope *>::iterator
2444       SI = InlinedVariableScopes.find(MI);
2445
2446     if (SI != InlinedVariableScopes.end()) {
2447       // or GV is an inlined local variable.
2448       Scope = SI->second;
2449     } else {
2450       DIVariable DV(GV);
2451       GlobalVariable *V = DV.getContext().getGV();
2452
2453       // FIXME: The code that checks for the inlined local variable is a hack!
2454       DenseMap<const GlobalVariable *, DbgScope *>::iterator
2455         AI = AbstractInstanceRootMap.find(V);
2456
2457       if (AI != AbstractInstanceRootMap.end()) {
2458         // This method is called each time a DECLARE node is encountered. For an
2459         // inlined function, this could be many, many times. We don't want to
2460         // re-add variables to that DIE for each time. We just want to add them
2461         // once. Check to make sure that we haven't added them already.
2462         DenseMap<const GlobalVariable *,
2463           SmallSet<const GlobalVariable *, 32> >::iterator
2464           IP = InlinedParamMap.find(V);
2465
2466         if (IP != InlinedParamMap.end()) {
2467           SmallSet<const GlobalVariable*, 32> &S = IP->second;
2468
2469           if (S.count(GV) > 0) {
2470             if (TimePassesIsEnabled)
2471               DebugTimer->stopTimer();
2472             return;
2473           }
2474
2475         }
2476
2477         // or GV is an inlined local variable.
2478         Scope = AI->second;
2479         InlinedParamMap[V].insert(GV);
2480       } else {
2481         // or GV is a local variable.
2482         Scope = getOrCreateScope(V);
2483       }
2484     }
2485   }
2486
2487   assert(Scope && "Unable to find the variable's scope");
2488   DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
2489   Scope->AddVariable(DV);
2490
2491   if (TimePassesIsEnabled)
2492     DebugTimer->stopTimer();
2493 }
2494
2495 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
2496 unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
2497                                           unsigned Line, unsigned Col) {
2498   unsigned LabelID = MMI->NextLabelID();
2499
2500   if (!TAI->doesDwarfUsesInlineInfoSection())
2501     return LabelID;
2502
2503   if (TimePassesIsEnabled)
2504     DebugTimer->startTimer();
2505
2506   GlobalVariable *GV = SP.getGV();
2507   DenseMap<const GlobalVariable *, DbgScope *>::iterator
2508     II = AbstractInstanceRootMap.find(GV);
2509
2510   if (II == AbstractInstanceRootMap.end()) {
2511     // Create an abstract instance entry for this inlined function if it doesn't
2512     // already exist.
2513     DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
2514
2515     // Get the compile unit context.
2516     CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2517     DIE *SPDie = Unit->getDieMapSlotFor(GV);
2518     if (!SPDie)
2519       SPDie = CreateSubprogramDIE(Unit, SP, false, true);
2520
2521     // Mark as being inlined. This makes this subprogram entry an abstract
2522     // instance root.
2523     // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
2524     // that it's defined. That probably won't change in the future. However,
2525     // this could be more elegant.
2526     AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
2527
2528     // Keep track of the abstract scope for this function.
2529     DbgAbstractScopeMap[GV] = Scope;
2530
2531     AbstractInstanceRootMap[GV] = Scope;
2532     AbstractInstanceRootList.push_back(Scope);
2533   }
2534
2535   // Create a concrete inlined instance for this inlined function.
2536   DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
2537   DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
2538   CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2539   ScopeDie->setAbstractCompileUnit(Unit);
2540
2541   DIE *Origin = Unit->getDieMapSlotFor(GV);
2542   AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
2543               dwarf::DW_FORM_ref4, Origin);
2544   AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, Unit->getID());
2545   AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
2546   AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
2547
2548   ConcreteScope->setDie(ScopeDie);
2549   ConcreteScope->setStartLabelID(LabelID);
2550   MMI->RecordUsedDbgLabel(LabelID);
2551
2552   LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
2553
2554   // Keep track of the concrete scope that's inlined into this function.
2555   DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2556     SI = DbgConcreteScopeMap.find(GV);
2557
2558   if (SI == DbgConcreteScopeMap.end())
2559     DbgConcreteScopeMap[GV].push_back(ConcreteScope);
2560   else
2561     SI->second.push_back(ConcreteScope);
2562
2563   // Track the start label for this inlined function.
2564   DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2565     I = InlineInfo.find(GV);
2566
2567   if (I == InlineInfo.end())
2568     InlineInfo[GV].push_back(LabelID);
2569   else
2570     I->second.push_back(LabelID);
2571
2572   if (TimePassesIsEnabled)
2573     DebugTimer->stopTimer();
2574
2575   return LabelID;
2576 }
2577
2578 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2579 unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
2580   if (!TAI->doesDwarfUsesInlineInfoSection())
2581     return 0;
2582
2583   if (TimePassesIsEnabled)
2584     DebugTimer->startTimer();
2585
2586   GlobalVariable *GV = SP.getGV();
2587   DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2588     I = DbgConcreteScopeMap.find(GV);
2589
2590   if (I == DbgConcreteScopeMap.end()) {
2591     // FIXME: Can this situation actually happen? And if so, should it?
2592     if (TimePassesIsEnabled)
2593       DebugTimer->stopTimer();
2594
2595     return 0;
2596   }
2597
2598   SmallVector<DbgScope *, 8> &Scopes = I->second;
2599   assert(!Scopes.empty() && "We should have at least one debug scope!");
2600   DbgScope *Scope = Scopes.back(); Scopes.pop_back();
2601   unsigned ID = MMI->NextLabelID();
2602   MMI->RecordUsedDbgLabel(ID);
2603   Scope->setEndLabelID(ID);
2604
2605   if (TimePassesIsEnabled)
2606     DebugTimer->stopTimer();
2607
2608   return ID;
2609 }
2610
2611 /// RecordVariableScope - Record scope for the variable declared by
2612 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
2613 /// for only inlined subroutine variables. Other variables's scopes are
2614 /// determined during RecordVariable().
2615 void DwarfDebug::RecordVariableScope(DIVariable &DV,
2616                                      const MachineInstr *DeclareMI) {
2617   if (TimePassesIsEnabled)
2618     DebugTimer->startTimer();
2619
2620   DISubprogram SP(DV.getContext().getGV());
2621
2622   if (SP.isNull()) {
2623     if (TimePassesIsEnabled)
2624       DebugTimer->stopTimer();
2625
2626     return;
2627   }
2628
2629   DenseMap<GlobalVariable *, DbgScope *>::iterator
2630     I = DbgAbstractScopeMap.find(SP.getGV());
2631   if (I != DbgAbstractScopeMap.end())
2632     InlinedVariableScopes[DeclareMI] = I->second;
2633
2634   if (TimePassesIsEnabled)
2635     DebugTimer->stopTimer();
2636 }