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