LLVM API Documentation

DwarfDebug.cpp

Go to the documentation of this file.
00001 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains support for writing dwarf debug info into asm files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "DwarfDebug.h"
00015 #include "llvm/Module.h"
00016 #include "llvm/CodeGen/MachineFunction.h"
00017 #include "llvm/CodeGen/MachineModuleInfo.h"
00018 #include "llvm/MC/MCSection.h"
00019 #include "llvm/MC/MCStreamer.h"
00020 #include "llvm/Target/TargetAsmInfo.h"
00021 #include "llvm/Target/TargetData.h"
00022 #include "llvm/Target/TargetFrameInfo.h"
00023 #include "llvm/Target/TargetLoweringObjectFile.h"
00024 #include "llvm/Target/TargetRegisterInfo.h"
00025 #include "llvm/Support/Timer.h"
00026 #include "llvm/System/Path.h"
00027 using namespace llvm;
00028 
00029 static TimerGroup &getDwarfTimerGroup() {
00030   static TimerGroup DwarfTimerGroup("Dwarf Debugging");
00031   return DwarfTimerGroup;
00032 }
00033 
00034 //===----------------------------------------------------------------------===//
00035 
00036 /// Configuration values for initial hash set sizes (log2).
00037 ///
00038 static const unsigned InitDiesSetSize          = 9; // log2(512)
00039 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
00040 static const unsigned InitValuesSetSize        = 9; // log2(512)
00041 
00042 namespace llvm {
00043 
00044 //===----------------------------------------------------------------------===//
00045 /// CompileUnit - This dwarf writer support class manages information associate
00046 /// with a source file.
00047 class VISIBILITY_HIDDEN CompileUnit {
00048   /// ID - File identifier for source.
00049   ///
00050   unsigned ID;
00051 
00052   /// Die - Compile unit debug information entry.
00053   ///
00054   DIE *Die;
00055 
00056   /// GVToDieMap - Tracks the mapping of unit level debug informaton
00057   /// variables to debug information entries.
00058   std::map<GlobalVariable *, DIE *> GVToDieMap;
00059 
00060   /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
00061   /// descriptors to debug information entries using a DIEEntry proxy.
00062   std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
00063 
00064   /// Globals - A map of globally visible named entities for this unit.
00065   ///
00066   StringMap<DIE*> Globals;
00067 
00068   /// DiesSet - Used to uniquely define dies within the compile unit.
00069   ///
00070   FoldingSet<DIE> DiesSet;
00071 public:
00072   CompileUnit(unsigned I, DIE *D)
00073     : ID(I), Die(D), DiesSet(InitDiesSetSize) {}
00074   ~CompileUnit() { delete Die; }
00075 
00076   // Accessors.
00077   unsigned getID() const { return ID; }
00078   DIE* getDie() const { return Die; }
00079   StringMap<DIE*> &getGlobals() { return Globals; }
00080 
00081   /// hasContent - Return true if this compile unit has something to write out.
00082   ///
00083   bool hasContent() const { return !Die->getChildren().empty(); }
00084 
00085   /// AddGlobal - Add a new global entity to the compile unit.
00086   ///
00087   void AddGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
00088 
00089   /// getDieMapSlotFor - Returns the debug information entry map slot for the
00090   /// specified debug variable.
00091   DIE *&getDieMapSlotFor(GlobalVariable *GV) { return GVToDieMap[GV]; }
00092 
00093   /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for
00094   /// the specified debug variable.
00095   DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
00096     return GVToDIEEntryMap[GV];
00097   }
00098 
00099   /// AddDie - Adds or interns the DIE to the compile unit.
00100   ///
00101   DIE *AddDie(DIE &Buffer) {
00102     FoldingSetNodeID ID;
00103     Buffer.Profile(ID);
00104     void *Where;
00105     DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
00106 
00107     if (!Die) {
00108       Die = new DIE(Buffer);
00109       DiesSet.InsertNode(Die, Where);
00110       this->Die->AddChild(Die);
00111       Buffer.Detach();
00112     }
00113 
00114     return Die;
00115   }
00116 };
00117 
00118 //===----------------------------------------------------------------------===//
00119 /// DbgVariable - This class is used to track local variable information.
00120 ///
00121 class VISIBILITY_HIDDEN DbgVariable {
00122   DIVariable Var;                    // Variable Descriptor.
00123   unsigned FrameIndex;               // Variable frame index.
00124   bool InlinedFnVar;                 // Variable for an inlined function.
00125 public:
00126   DbgVariable(DIVariable V, unsigned I, bool IFV)
00127     : Var(V), FrameIndex(I), InlinedFnVar(IFV)  {}
00128 
00129   // Accessors.
00130   DIVariable getVariable() const { return Var; }
00131   unsigned getFrameIndex() const { return FrameIndex; }
00132   bool isInlinedFnVar() const { return InlinedFnVar; }
00133 };
00134 
00135 //===----------------------------------------------------------------------===//
00136 /// DbgScope - This class is used to track scope information.
00137 ///
00138 class DbgConcreteScope;
00139 class VISIBILITY_HIDDEN DbgScope {
00140   DbgScope *Parent;                   // Parent to this scope.
00141   DIDescriptor Desc;                  // Debug info descriptor for scope.
00142                                       // Either subprogram or block.
00143   unsigned StartLabelID;              // Label ID of the beginning of scope.
00144   unsigned EndLabelID;                // Label ID of the end of scope.
00145   SmallVector<DbgScope *, 4> Scopes;  // Scopes defined in scope.
00146   SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
00147   SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
00148   
00149   // Private state for dump()
00150   mutable unsigned IndentLevel;
00151 public:
00152   DbgScope(DbgScope *P, DIDescriptor D)
00153     : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), IndentLevel(0) {}
00154   virtual ~DbgScope();
00155 
00156   // Accessors.
00157   DbgScope *getParent()          const { return Parent; }
00158   DIDescriptor getDesc()         const { return Desc; }
00159   unsigned getStartLabelID()     const { return StartLabelID; }
00160   unsigned getEndLabelID()       const { return EndLabelID; }
00161   SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
00162   SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
00163   SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
00164   void setStartLabelID(unsigned S) { StartLabelID = S; }
00165   void setEndLabelID(unsigned E)   { EndLabelID = E; }
00166 
00167   /// AddScope - Add a scope to the scope.
00168   ///
00169   void AddScope(DbgScope *S) { Scopes.push_back(S); }
00170 
00171   /// AddVariable - Add a variable to the scope.
00172   ///
00173   void AddVariable(DbgVariable *V) { Variables.push_back(V); }
00174 
00175   /// AddConcreteInst - Add a concrete instance to the scope.
00176   ///
00177   void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
00178 
00179 #ifndef NDEBUG
00180   void dump() const;
00181 #endif
00182 };
00183 
00184 #ifndef NDEBUG
00185 void DbgScope::dump() const {
00186   std::string Indent(IndentLevel, ' ');
00187 
00188   cerr << Indent; Desc.dump();
00189   cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
00190 
00191   IndentLevel += 2;
00192 
00193   for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
00194     if (Scopes[i] != this)
00195       Scopes[i]->dump();
00196 
00197   IndentLevel -= 2;
00198 }
00199 #endif
00200 
00201 //===----------------------------------------------------------------------===//
00202 /// DbgConcreteScope - This class is used to track a scope that holds concrete
00203 /// instance information.
00204 ///
00205 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
00206   CompileUnit *Unit;
00207   DIE *Die;                           // Debug info for this concrete scope.
00208 public:
00209   DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
00210 
00211   // Accessors.
00212   DIE *getDie() const { return Die; }
00213   void setDie(DIE *D) { Die = D; }
00214 };
00215 
00216 DbgScope::~DbgScope() {
00217   for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
00218     delete Scopes[i];
00219   for (unsigned j = 0, M = Variables.size(); j < M; ++j)
00220     delete Variables[j];
00221   for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
00222     delete ConcreteInsts[k];
00223 }
00224 
00225 } // end llvm namespace
00226 
00227 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
00228   : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
00229     AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
00230     ValuesSet(InitValuesSetSize), Values(), StringPool(), 
00231     SectionSourceLines(), didInitial(false), shouldEmit(false),
00232     FunctionDbgScope(0), DebugTimer(0) {
00233   if (TimePassesIsEnabled)
00234     DebugTimer = new Timer("Dwarf Debug Writer",
00235                            getDwarfTimerGroup());
00236 }
00237 DwarfDebug::~DwarfDebug() {
00238   for (unsigned j = 0, M = Values.size(); j < M; ++j)
00239     delete Values[j];
00240 
00241   for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
00242          I = AbstractInstanceRootMap.begin(),
00243          E = AbstractInstanceRootMap.end(); I != E;++I)
00244     delete I->second;
00245 
00246   delete DebugTimer;
00247 }
00248 
00249 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
00250 ///
00251 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
00252   // Profile the node so that we can make it unique.
00253   FoldingSetNodeID ID;
00254   Abbrev.Profile(ID);
00255 
00256   // Check the set for priors.
00257   DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
00258 
00259   // If it's newly added.
00260   if (InSet == &Abbrev) {
00261     // Add to abbreviation list.
00262     Abbreviations.push_back(&Abbrev);
00263 
00264     // Assign the vector position + 1 as its number.
00265     Abbrev.setNumber(Abbreviations.size());
00266   } else {
00267     // Assign existing abbreviation number.
00268     Abbrev.setNumber(InSet->getNumber());
00269   }
00270 }
00271 
00272 /// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
00273 /// information entry.
00274 DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
00275   DIEEntry *Value;
00276 
00277   if (Entry) {
00278     FoldingSetNodeID ID;
00279     DIEEntry::Profile(ID, Entry);
00280     void *Where;
00281     Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
00282 
00283     if (Value) return Value;
00284 
00285     Value = new DIEEntry(Entry);
00286     ValuesSet.InsertNode(Value, Where);
00287   } else {
00288     Value = new DIEEntry(Entry);
00289   }
00290 
00291   Values.push_back(Value);
00292   return Value;
00293 }
00294 
00295 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
00296 ///
00297 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
00298   Value->setEntry(Entry);
00299 
00300   // Add to values set if not already there.  If it is, we merely have a
00301   // duplicate in the values list (no harm.)
00302   ValuesSet.GetOrInsertNode(Value);
00303 }
00304 
00305 /// AddUInt - Add an unsigned integer attribute data and value.
00306 ///
00307 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
00308                          unsigned Form, uint64_t Integer) {
00309   if (!Form) Form = DIEInteger::BestForm(false, Integer);
00310 
00311   FoldingSetNodeID ID;
00312   DIEInteger::Profile(ID, Integer);
00313   void *Where;
00314   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
00315 
00316   if (!Value) {
00317     Value = new DIEInteger(Integer);
00318     ValuesSet.InsertNode(Value, Where);
00319     Values.push_back(Value);
00320   }
00321 
00322   Die->AddValue(Attribute, Form, Value);
00323 }
00324 
00325 /// AddSInt - Add an signed integer attribute data and value.
00326 ///
00327 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
00328                          unsigned Form, int64_t Integer) {
00329   if (!Form) Form = DIEInteger::BestForm(true, Integer);
00330 
00331   FoldingSetNodeID ID;
00332   DIEInteger::Profile(ID, (uint64_t)Integer);
00333   void *Where;
00334   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
00335 
00336   if (!Value) {
00337     Value = new DIEInteger(Integer);
00338     ValuesSet.InsertNode(Value, Where);
00339     Values.push_back(Value);
00340   }
00341 
00342   Die->AddValue(Attribute, Form, Value);
00343 }
00344 
00345 /// AddString - Add a string attribute data and value.
00346 ///
00347 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
00348                            const std::string &String) {
00349   FoldingSetNodeID ID;
00350   DIEString::Profile(ID, String);
00351   void *Where;
00352   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
00353 
00354   if (!Value) {
00355     Value = new DIEString(String);
00356     ValuesSet.InsertNode(Value, Where);
00357     Values.push_back(Value);
00358   }
00359 
00360   Die->AddValue(Attribute, Form, Value);
00361 }
00362 
00363 /// AddLabel - Add a Dwarf label attribute data and value.
00364 ///
00365 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
00366                           const DWLabel &Label) {
00367   FoldingSetNodeID ID;
00368   DIEDwarfLabel::Profile(ID, Label);
00369   void *Where;
00370   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
00371 
00372   if (!Value) {
00373     Value = new DIEDwarfLabel(Label);
00374     ValuesSet.InsertNode(Value, Where);
00375     Values.push_back(Value);
00376   }
00377 
00378   Die->AddValue(Attribute, Form, Value);
00379 }
00380 
00381 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
00382 ///
00383 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
00384                                 const std::string &Label) {
00385   FoldingSetNodeID ID;
00386   DIEObjectLabel::Profile(ID, Label);
00387   void *Where;
00388   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
00389 
00390   if (!Value) {
00391     Value = new DIEObjectLabel(Label);
00392     ValuesSet.InsertNode(Value, Where);
00393     Values.push_back(Value);
00394   }
00395 
00396   Die->AddValue(Attribute, Form, Value);
00397 }
00398 
00399 /// AddSectionOffset - Add a section offset label attribute data and value.
00400 ///
00401 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
00402                                   const DWLabel &Label, const DWLabel &Section,
00403                                   bool isEH, bool useSet) {
00404   FoldingSetNodeID ID;
00405   DIESectionOffset::Profile(ID, Label, Section);
00406   void *Where;
00407   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
00408 
00409   if (!Value) {
00410     Value = new DIESectionOffset(Label, Section, isEH, useSet);
00411     ValuesSet.InsertNode(Value, Where);
00412     Values.push_back(Value);
00413   }
00414 
00415   Die->AddValue(Attribute, Form, Value);
00416 }
00417 
00418 /// AddDelta - Add a label delta attribute data and value.
00419 ///
00420 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
00421                           const DWLabel &Hi, const DWLabel &Lo) {
00422   FoldingSetNodeID ID;
00423   DIEDelta::Profile(ID, Hi, Lo);
00424   void *Where;
00425   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
00426 
00427   if (!Value) {
00428     Value = new DIEDelta(Hi, Lo);
00429     ValuesSet.InsertNode(Value, Where);
00430     Values.push_back(Value);
00431   }
00432 
00433   Die->AddValue(Attribute, Form, Value);
00434 }
00435 
00436 /// AddBlock - Add block data.
00437 ///
00438 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
00439                           DIEBlock *Block) {
00440   Block->ComputeSize(TD);
00441   FoldingSetNodeID ID;
00442   Block->Profile(ID);
00443   void *Where;
00444   DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
00445 
00446   if (!Value) {
00447     Value = Block;
00448     ValuesSet.InsertNode(Value, Where);
00449     Values.push_back(Value);
00450   } else {
00451     // Already exists, reuse the previous one.
00452     delete Block;
00453     Block = cast<DIEBlock>(Value);
00454   }
00455 
00456   Die->AddValue(Attribute, Block->BestForm(), Value);
00457 }
00458 
00459 /// AddSourceLine - Add location information to specified debug information
00460 /// entry.
00461 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
00462   // If there is no compile unit specified, don't add a line #.
00463   if (V->getCompileUnit().isNull())
00464     return;
00465 
00466   unsigned Line = V->getLineNumber();
00467   unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
00468   assert(FileID && "Invalid file id");
00469   AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
00470   AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
00471 }
00472 
00473 /// AddSourceLine - Add location information to specified debug information
00474 /// entry.
00475 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
00476   // If there is no compile unit specified, don't add a line #.
00477   if (G->getCompileUnit().isNull())
00478     return;
00479 
00480   unsigned Line = G->getLineNumber();
00481   unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
00482   assert(FileID && "Invalid file id");
00483   AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
00484   AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
00485 }
00486 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
00487   // If there is no compile unit specified, don't add a line #.
00488   DICompileUnit CU = Ty->getCompileUnit();
00489   if (CU.isNull())
00490     return;
00491 
00492   unsigned Line = Ty->getLineNumber();
00493   unsigned FileID = FindCompileUnit(CU).getID();
00494   assert(FileID && "Invalid file id");
00495   AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
00496   AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
00497 }
00498 
00499 /// AddAddress - Add an address attribute to a die based on the location
00500 /// provided.
00501 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
00502                             const MachineLocation &Location) {
00503   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
00504   DIEBlock *Block = new DIEBlock();
00505 
00506   if (Location.isReg()) {
00507     if (Reg < 32) {
00508       AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
00509     } else {
00510       AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
00511       AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
00512     }
00513   } else {
00514     if (Reg < 32) {
00515       AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
00516     } else {
00517       AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
00518       AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
00519     }
00520 
00521     AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
00522   }
00523 
00524   AddBlock(Die, Attribute, 0, Block);
00525 }
00526 
00527 /// AddType - Add a new type attribute to the specified entity.
00528 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
00529   if (Ty.isNull())
00530     return;
00531 
00532   // Check for pre-existence.
00533   DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
00534 
00535   // If it exists then use the existing value.
00536   if (Slot) {
00537     Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
00538     return;
00539   }
00540 
00541   // Set up proxy.
00542   Slot = CreateDIEEntry();
00543 
00544   // Construct type.
00545   DIE Buffer(dwarf::DW_TAG_base_type);
00546   if (Ty.isBasicType(Ty.getTag()))
00547     ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
00548   else if (Ty.isDerivedType(Ty.getTag()))
00549     ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
00550   else {
00551     assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
00552     ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
00553   }
00554 
00555   // Add debug information entry to entity and appropriate context.
00556   DIE *Die = NULL;
00557   DIDescriptor Context = Ty.getContext();
00558   if (!Context.isNull())
00559     Die = DW_Unit->getDieMapSlotFor(Context.getGV());
00560 
00561   if (Die) {
00562     DIE *Child = new DIE(Buffer);
00563     Die->AddChild(Child);
00564     Buffer.Detach();
00565     SetDIEEntry(Slot, Child);
00566   } else {
00567     Die = DW_Unit->AddDie(Buffer);
00568     SetDIEEntry(Slot, Die);
00569   }
00570 
00571   Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
00572 }
00573 
00574 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
00575 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
00576                                   DIBasicType BTy) {
00577   // Get core information.
00578   std::string Name;
00579   BTy.getName(Name);
00580   Buffer.setTag(dwarf::DW_TAG_base_type);
00581   AddUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
00582           BTy.getEncoding());
00583 
00584   // Add name if not anonymous or intermediate type.
00585   if (!Name.empty())
00586     AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
00587   uint64_t Size = BTy.getSizeInBits() >> 3;
00588   AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
00589 }
00590 
00591 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
00592 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
00593                                   DIDerivedType DTy) {
00594   // Get core information.
00595   std::string Name;
00596   DTy.getName(Name);
00597   uint64_t Size = DTy.getSizeInBits() >> 3;
00598   unsigned Tag = DTy.getTag();
00599 
00600   // FIXME - Workaround for templates.
00601   if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
00602 
00603   Buffer.setTag(Tag);
00604 
00605   // Map to main type, void will not have a type.
00606   DIType FromTy = DTy.getTypeDerivedFrom();
00607   AddType(DW_Unit, &Buffer, FromTy);
00608 
00609   // Add name if not anonymous or intermediate type.
00610   if (!Name.empty())
00611     AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
00612 
00613   // Add size if non-zero (derived types might be zero-sized.)
00614   if (Size)
00615     AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
00616 
00617   // Add source line info if available and TyDesc is not a forward declaration.
00618   if (!DTy.isForwardDecl())
00619     AddSourceLine(&Buffer, &DTy);
00620 }
00621 
00622 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
00623 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
00624                                   DICompositeType CTy) {
00625   // Get core information.
00626   std::string Name;
00627   CTy.getName(Name);
00628 
00629   uint64_t Size = CTy.getSizeInBits() >> 3;
00630   unsigned Tag = CTy.getTag();
00631   Buffer.setTag(Tag);
00632 
00633   switch (Tag) {
00634   case dwarf::DW_TAG_vector_type:
00635   case dwarf::DW_TAG_array_type:
00636     ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
00637     break;
00638   case dwarf::DW_TAG_enumeration_type: {
00639     DIArray Elements = CTy.getTypeArray();
00640 
00641     // Add enumerators to enumeration type.
00642     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
00643       DIE *ElemDie = NULL;
00644       DIEnumerator Enum(Elements.getElement(i).getGV());
00645       ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
00646       Buffer.AddChild(ElemDie);
00647     }
00648   }
00649     break;
00650   case dwarf::DW_TAG_subroutine_type: {
00651     // Add return type.
00652     DIArray Elements = CTy.getTypeArray();
00653     DIDescriptor RTy = Elements.getElement(0);
00654     AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
00655 
00656     // Add prototype flag.
00657     AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
00658 
00659     // Add arguments.
00660     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
00661       DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
00662       DIDescriptor Ty = Elements.getElement(i);
00663       AddType(DW_Unit, Arg, DIType(Ty.getGV()));
00664       Buffer.AddChild(Arg);
00665     }
00666   }
00667     break;
00668   case dwarf::DW_TAG_structure_type:
00669   case dwarf::DW_TAG_union_type:
00670   case dwarf::DW_TAG_class_type: {
00671     // Add elements to structure type.
00672     DIArray Elements = CTy.getTypeArray();
00673 
00674     // A forward struct declared type may not have elements available.
00675     if (Elements.isNull())
00676       break;
00677 
00678     // Add elements to structure type.
00679     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
00680       DIDescriptor Element = Elements.getElement(i);
00681       DIE *ElemDie = NULL;
00682       if (Element.getTag() == dwarf::DW_TAG_subprogram)
00683         ElemDie = CreateSubprogramDIE(DW_Unit,
00684                                       DISubprogram(Element.getGV()));
00685       else
00686         ElemDie = CreateMemberDIE(DW_Unit,
00687                                   DIDerivedType(Element.getGV()));
00688       Buffer.AddChild(ElemDie);
00689     }
00690 
00691     // FIXME: We'd like an API to register additional attributes for the
00692     // frontend to use while synthesizing, and then we'd use that api in clang
00693     // instead of this.
00694     if (Name == "__block_literal_generic")
00695       AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
00696 
00697     unsigned RLang = CTy.getRunTimeLang();
00698     if (RLang)
00699       AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
00700               dwarf::DW_FORM_data1, RLang);
00701     break;
00702   }
00703   default:
00704     break;
00705   }
00706 
00707   // Add name if not anonymous or intermediate type.
00708   if (!Name.empty())
00709     AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
00710 
00711   if (Tag == dwarf::DW_TAG_enumeration_type ||
00712       Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
00713     // Add size if non-zero (derived types might be zero-sized.)
00714     if (Size)
00715       AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
00716     else {
00717       // Add zero size if it is not a forward declaration.
00718       if (CTy.isForwardDecl())
00719         AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
00720       else
00721         AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
00722     }
00723 
00724     // Add source line info if available.
00725     if (!CTy.isForwardDecl())
00726       AddSourceLine(&Buffer, &CTy);
00727   }
00728 }
00729 
00730 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
00731 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
00732   int64_t L = SR.getLo();
00733   int64_t H = SR.getHi();
00734   DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
00735 
00736   AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
00737   if (L)
00738     AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
00739   if (H)
00740   AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
00741 
00742   Buffer.AddChild(DW_Subrange);
00743 }
00744 
00745 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
00746 void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
00747                                        DICompositeType *CTy) {
00748   Buffer.setTag(dwarf::DW_TAG_array_type);
00749   if (CTy->getTag() == dwarf::DW_TAG_vector_type)
00750     AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
00751 
00752   // Emit derived type.
00753   AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
00754   DIArray Elements = CTy->getTypeArray();
00755 
00756   // Construct an anonymous type for index type.
00757   DIE IdxBuffer(dwarf::DW_TAG_base_type);
00758   AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
00759   AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
00760           dwarf::DW_ATE_signed);
00761   DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
00762 
00763   // Add subranges to array type.
00764   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
00765     DIDescriptor Element = Elements.getElement(i);
00766     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
00767       ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
00768   }
00769 }
00770 
00771 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
00772 DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
00773   DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
00774   std::string Name;
00775   ETy->getName(Name);
00776   AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
00777   int64_t Value = ETy->getEnumValue();
00778   AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
00779   return Enumerator;
00780 }
00781 
00782 /// CreateGlobalVariableDIE - Create new DIE using GV.
00783 DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
00784                                          const DIGlobalVariable &GV) {
00785   DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
00786   std::string Name;
00787   GV.getDisplayName(Name);
00788   AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
00789   std::string LinkageName;
00790   GV.getLinkageName(LinkageName);
00791   if (!LinkageName.empty()) {
00792     // Skip special LLVM prefix that is used to inform the asm printer to not
00793     // emit usual symbol prefix before the symbol name. This happens for
00794     // Objective-C symbol names and symbol whose name is replaced using GCC's
00795     // __asm__ attribute.
00796     if (LinkageName[0] == 1)
00797       LinkageName = &LinkageName[1];
00798     AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
00799               LinkageName);
00800   }
00801     AddType(DW_Unit, GVDie, GV.getType());
00802   if (!GV.isLocalToUnit())
00803     AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
00804   AddSourceLine(GVDie, &GV);
00805   return GVDie;
00806 }
00807 
00808 /// CreateMemberDIE - Create new member DIE.
00809 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
00810   DIE *MemberDie = new DIE(DT.getTag());
00811   std::string Name;
00812   DT.getName(Name);
00813   if (!Name.empty())
00814     AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
00815 
00816   AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
00817 
00818   AddSourceLine(MemberDie, &DT);
00819 
00820   uint64_t Size = DT.getSizeInBits();
00821   uint64_t FieldSize = DT.getOriginalTypeSize();
00822 
00823   if (Size != FieldSize) {
00824     // Handle bitfield.
00825     AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
00826     AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
00827 
00828     uint64_t Offset = DT.getOffsetInBits();
00829     uint64_t FieldOffset = Offset;
00830     uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
00831     uint64_t HiMark = (Offset + FieldSize) & AlignMask;
00832     FieldOffset = (HiMark - FieldSize);
00833     Offset -= FieldOffset;
00834 
00835     // Maybe we need to work from the other end.
00836     if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
00837     AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
00838   }
00839 
00840   DIEBlock *Block = new DIEBlock();
00841   AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
00842   AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
00843   AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
00844 
00845   if (DT.isProtected())
00846     AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
00847             dwarf::DW_ACCESS_protected);
00848   else if (DT.isPrivate())
00849     AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
00850             dwarf::DW_ACCESS_private);
00851 
00852   return MemberDie;
00853 }
00854 
00855 /// CreateSubprogramDIE - Create new DIE using SP.
00856 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
00857                                      const DISubprogram &SP,
00858                                      bool IsConstructor,
00859                                      bool IsInlined) {
00860   DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
00861 
00862   std::string Name;
00863   SP.getName(Name);
00864   AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
00865 
00866   std::string LinkageName;
00867   SP.getLinkageName(LinkageName);
00868   if (!LinkageName.empty()) {
00869     // Skip special LLVM prefix that is used to inform the asm printer to not emit
00870     // usual symbol prefix before the symbol name. This happens for Objective-C
00871     // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
00872     if (LinkageName[0] == 1)
00873       LinkageName = &LinkageName[1];
00874     AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
00875               LinkageName);
00876   }
00877   AddSourceLine(SPDie, &SP);
00878 
00879   DICompositeType SPTy = SP.getType();
00880   DIArray Args = SPTy.getTypeArray();
00881 
00882   // Add prototyped tag, if C or ObjC.
00883   unsigned Lang = SP.getCompileUnit().getLanguage();
00884   if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
00885       Lang == dwarf::DW_LANG_ObjC)
00886     AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
00887 
00888   // Add Return Type.
00889   unsigned SPTag = SPTy.getTag();
00890   if (!IsConstructor) {
00891     if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
00892       AddType(DW_Unit, SPDie, SPTy);
00893     else
00894       AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
00895   }
00896 
00897   if (!SP.isDefinition()) {
00898     AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
00899 
00900     // Add arguments. Do not add arguments for subprogram definition. They will
00901     // be handled through RecordVariable.
00902     if (SPTag == dwarf::DW_TAG_subroutine_type)
00903       for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
00904         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
00905         AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
00906         AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
00907         SPDie->AddChild(Arg);
00908       }
00909   }
00910 
00911   if (!SP.isLocalToUnit() && !IsInlined)
00912     AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
00913 
00914   // DW_TAG_inlined_subroutine may refer to this DIE.
00915   DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
00916   Slot = SPDie;
00917   return SPDie;
00918 }
00919 
00920 /// FindCompileUnit - Get the compile unit for the given descriptor.
00921 ///
00922 CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
00923   DenseMap<Value *, CompileUnit *>::const_iterator I =
00924     CompileUnitMap.find(Unit.getGV());
00925   assert(I != CompileUnitMap.end() && "Missing compile unit.");
00926   return *I->second;
00927 }
00928 
00929 /// CreateDbgScopeVariable - Create a new scope variable.
00930 ///
00931 DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
00932   // Get the descriptor.
00933   const DIVariable &VD = DV->getVariable();
00934 
00935   // Translate tag to proper Dwarf tag.  The result variable is dropped for
00936   // now.
00937   unsigned Tag;
00938   switch (VD.getTag()) {
00939   case dwarf::DW_TAG_return_variable:
00940     return NULL;
00941   case dwarf::DW_TAG_arg_variable:
00942     Tag = dwarf::DW_TAG_formal_parameter;
00943     break;
00944   case dwarf::DW_TAG_auto_variable:    // fall thru
00945   default:
00946     Tag = dwarf::DW_TAG_variable;
00947     break;
00948   }
00949 
00950   // Define variable debug information entry.
00951   DIE *VariableDie = new DIE(Tag);
00952   std::string Name;
00953   VD.getName(Name);
00954   AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
00955 
00956   // Add source line info if available.
00957   AddSourceLine(VariableDie, &VD);
00958 
00959   // Add variable type.
00960   AddType(Unit, VariableDie, VD.getType());
00961 
00962   // Add variable address.
00963   if (!DV->isInlinedFnVar()) {
00964     // Variables for abstract instances of inlined functions don't get a
00965     // location.
00966     MachineLocation Location;
00967     Location.set(RI->getFrameRegister(*MF),
00968                  RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
00969     AddAddress(VariableDie, dwarf::DW_AT_location, Location);
00970   }
00971 
00972   return VariableDie;
00973 }
00974 
00975 /// getOrCreateScope - Returns the scope associated with the given descriptor.
00976 ///
00977 DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
00978   DbgScope *&Slot = DbgScopeMap[V];
00979   if (Slot) return Slot;
00980 
00981   DbgScope *Parent = NULL;
00982   DIBlock Block(V);
00983 
00984   // Don't create a new scope if we already created one for an inlined function.
00985   DenseMap<const GlobalVariable *, DbgScope *>::iterator
00986     II = AbstractInstanceRootMap.find(V);
00987   if (II != AbstractInstanceRootMap.end())
00988     return LexicalScopeStack.back();
00989 
00990   if (!Block.isNull()) {
00991     DIDescriptor ParentDesc = Block.getContext();
00992     Parent =
00993       ParentDesc.isNull() ?  NULL : getOrCreateScope(ParentDesc.getGV());
00994   }
00995 
00996   Slot = new DbgScope(Parent, DIDescriptor(V));
00997 
00998   if (Parent)
00999     Parent->AddScope(Slot);
01000   else
01001     // First function is top level function.
01002     FunctionDbgScope = Slot;
01003 
01004   return Slot;
01005 }
01006 
01007 /// ConstructDbgScope - Construct the components of a scope.
01008 ///
01009 void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
01010                                    unsigned ParentStartID,
01011                                    unsigned ParentEndID,
01012                                    DIE *ParentDie, CompileUnit *Unit) {
01013   // Add variables to scope.
01014   SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
01015   for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
01016     DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
01017     if (VariableDie) ParentDie->AddChild(VariableDie);
01018   }
01019 
01020   // Add concrete instances to scope.
01021   SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
01022     ParentScope->getConcreteInsts();
01023   for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
01024     DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
01025     DIE *Die = ConcreteInst->getDie();
01026 
01027     unsigned StartID = ConcreteInst->getStartLabelID();
01028     unsigned EndID = ConcreteInst->getEndLabelID();
01029 
01030     // Add the scope bounds.
01031     if (StartID)
01032       AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
01033                DWLabel("label", StartID));
01034     else
01035       AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
01036                DWLabel("func_begin", SubprogramCount));
01037 
01038     if (EndID)
01039       AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
01040                DWLabel("label", EndID));
01041     else
01042       AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
01043                DWLabel("func_end", SubprogramCount));
01044 
01045     ParentDie->AddChild(Die);
01046   }
01047 
01048   // Add nested scopes.
01049   SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
01050   for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
01051     // Define the Scope debug information entry.
01052     DbgScope *Scope = Scopes[j];
01053 
01054     unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
01055     unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
01056 
01057     // Ignore empty scopes.
01058     if (StartID == EndID && StartID != 0) continue;
01059 
01060     // Do not ignore inlined scopes even if they don't have any variables or
01061     // scopes.
01062     if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
01063         Scope->getConcreteInsts().empty())
01064       continue;
01065 
01066     if (StartID == ParentStartID && EndID == ParentEndID) {
01067       // Just add stuff to the parent scope.
01068       ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
01069     } else {
01070       DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
01071 
01072       // Add the scope bounds.
01073       if (StartID)
01074         AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
01075                  DWLabel("label", StartID));
01076       else
01077         AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
01078                  DWLabel("func_begin", SubprogramCount));
01079 
01080       if (EndID)
01081         AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
01082                  DWLabel("label", EndID));
01083       else
01084         AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
01085                  DWLabel("func_end", SubprogramCount));
01086 
01087       // Add the scope's contents.
01088       ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
01089       ParentDie->AddChild(ScopeDie);
01090     }
01091   }
01092 }
01093 
01094 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
01095 ///
01096 void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
01097                                            bool AbstractScope) {
01098   // Exit if there is no root scope.
01099   if (!RootScope) return;
01100   DIDescriptor Desc = RootScope->getDesc();
01101   if (Desc.isNull())
01102     return;
01103 
01104   // Get the subprogram debug information entry.
01105   DISubprogram SPD(Desc.getGV());
01106 
01107   // Get the subprogram die.
01108   DIE *SPDie = ModuleCU->getDieMapSlotFor(SPD.getGV());
01109   assert(SPDie && "Missing subprogram descriptor");
01110 
01111   if (!AbstractScope) {
01112     // Add the function bounds.
01113     AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
01114              DWLabel("func_begin", SubprogramCount));
01115     AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
01116              DWLabel("func_end", SubprogramCount));
01117     MachineLocation Location(RI->getFrameRegister(*MF));
01118     AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
01119   }
01120 
01121   ConstructDbgScope(RootScope, 0, 0, SPDie, ModuleCU);
01122 }
01123 
01124 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
01125 ///
01126 void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
01127   StringMap<DIE*> &Globals = ModuleCU->getGlobals();
01128   StringMap<DIE*>::iterator GI = Globals.find(MF->getFunction()->getName());
01129   if (GI != Globals.end()) {
01130     DIE *SPDie = GI->second;
01131     
01132     // Add the function bounds.
01133     AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
01134              DWLabel("func_begin", SubprogramCount));
01135     AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
01136              DWLabel("func_end", SubprogramCount));
01137     
01138     MachineLocation Location(RI->getFrameRegister(*MF));
01139     AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
01140   }
01141 }
01142 
01143 /// GetOrCreateSourceID - Look up the source id with the given directory and
01144 /// source file names. If none currently exists, create a new id and insert it
01145 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
01146 /// maps as well.
01147 unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
01148                                          const std::string &FileName) {
01149   unsigned DId;
01150   StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
01151   if (DI != DirectoryIdMap.end()) {
01152     DId = DI->getValue();
01153   } else {
01154     DId = DirectoryNames.size() + 1;
01155     DirectoryIdMap[DirName] = DId;
01156     DirectoryNames.push_back(DirName);
01157   }
01158 
01159   unsigned FId;
01160   StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
01161   if (FI != SourceFileIdMap.end()) {
01162     FId = FI->getValue();
01163   } else {
01164     FId = SourceFileNames.size() + 1;
01165     SourceFileIdMap[FileName] = FId;
01166     SourceFileNames.push_back(FileName);
01167   }
01168 
01169   DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
01170     SourceIdMap.find(std::make_pair(DId, FId));
01171   if (SI != SourceIdMap.end())
01172     return SI->second;
01173 
01174   unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
01175   SourceIdMap[std::make_pair(DId, FId)] = SrcId;
01176   SourceIds.push_back(std::make_pair(DId, FId));
01177 
01178   return SrcId;
01179 }
01180 
01181 void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
01182   DICompileUnit DIUnit(GV);
01183   std::string Dir, FN, Prod;
01184   unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
01185                                     DIUnit.getFilename(FN));
01186 
01187   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
01188   AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
01189                    DWLabel("section_line", 0), DWLabel("section_line", 0),
01190                    false);
01191   AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
01192             DIUnit.getProducer(Prod));
01193   AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
01194           DIUnit.getLanguage());
01195   AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
01196 
01197   if (!Dir.empty())
01198     AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
01199   if (DIUnit.isOptimized())
01200     AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
01201 
01202   std::string Flags;
01203   DIUnit.getFlags(Flags);
01204   if (!Flags.empty())
01205     AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
01206 
01207   unsigned RVer = DIUnit.getRunTimeVersion();
01208   if (RVer)
01209     AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
01210             dwarf::DW_FORM_data1, RVer);
01211 
01212   CompileUnit *Unit = new CompileUnit(ID, Die);
01213   if (!ModuleCU && DIUnit.isMain()) {
01214     // Use first compile unit marked as isMain as the compile unit
01215     // for this module.
01216     ModuleCU = Unit;
01217   }
01218 
01219   CompileUnitMap[DIUnit.getGV()] = Unit;
01220   CompileUnits.push_back(Unit);
01221 }
01222 
01223 void DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
01224   DIGlobalVariable DI_GV(GV);
01225 
01226   // Check for pre-existence.
01227   DIE *&Slot = ModuleCU->getDieMapSlotFor(DI_GV.getGV());
01228   if (Slot)
01229     return;
01230 
01231   DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
01232 
01233   // Add address.
01234   DIEBlock *Block = new DIEBlock();
01235   AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
01236   std::string GLN;
01237   AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
01238                  Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
01239   AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
01240 
01241   // Add to map.
01242   Slot = VariableDie;
01243 
01244   // Add to context owner.
01245   ModuleCU->getDie()->AddChild(VariableDie);
01246 
01247   // Expose as global. FIXME - need to check external flag.
01248   std::string Name;
01249   ModuleCU->AddGlobal(DI_GV.getName(Name), VariableDie);
01250   return;
01251 }
01252 
01253 void DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
01254   DISubprogram SP(GV);
01255 
01256   // Check for pre-existence.
01257   DIE *&Slot = ModuleCU->getDieMapSlotFor(GV);
01258   if (Slot)
01259     return;
01260 
01261   if (!SP.isDefinition())
01262     // This is a method declaration which will be handled while constructing
01263     // class type.
01264     return;
01265 
01266   DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
01267 
01268   // Add to map.
01269   Slot = SubprogramDie;
01270 
01271   // Add to context owner.
01272   ModuleCU->getDie()->AddChild(SubprogramDie);
01273 
01274   // Expose as global.
01275   std::string Name;
01276   ModuleCU->AddGlobal(SP.getName(Name), SubprogramDie);
01277   return;
01278 }
01279 
01280   /// BeginModule - Emit all Dwarf sections that should come prior to the
01281   /// content. Create global DIEs and emit initial debug info sections.
01282   /// This is inovked by the target AsmPrinter.
01283 void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
01284   this->M = M;
01285 
01286   if (TimePassesIsEnabled)
01287     DebugTimer->startTimer();
01288 
01289   DebugInfoFinder DbgFinder;
01290   DbgFinder.processModule(*M);
01291 
01292   // Create all the compile unit DIEs.
01293   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
01294          E = DbgFinder.compile_unit_end(); I != E; ++I)
01295     ConstructCompileUnit(*I);
01296 
01297   if (CompileUnits.empty()) {
01298     if (TimePassesIsEnabled)
01299       DebugTimer->stopTimer();
01300 
01301     return;
01302   }
01303 
01304   // If main compile unit for this module is not seen than randomly
01305   // select first compile unit.
01306   if (!ModuleCU)
01307     ModuleCU = CompileUnits[0];
01308 
01309   // If there is not any debug info available for any global variables and any
01310   // subprograms then there is not any debug info to emit.
01311   if (DbgFinder.global_variable_count() == 0
01312       && DbgFinder.subprogram_count() == 0) {
01313     if (TimePassesIsEnabled)
01314       DebugTimer->stopTimer();
01315     return;
01316   }
01317   
01318   // Create DIEs for each of the externally visible global variables.
01319   for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
01320          E = DbgFinder.global_variable_end(); I != E; ++I)
01321     ConstructGlobalVariableDIE(*I);
01322 
01323   // Create DIEs for each of the externally visible subprograms.
01324   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
01325          E = DbgFinder.subprogram_end(); I != E; ++I)
01326     ConstructSubprogram(*I);
01327 
01328   MMI = mmi;
01329   shouldEmit = true;
01330   MMI->setDebugInfoAvailability(true);
01331 
01332   // Prime section data.
01333   SectionMap.insert(Asm->getObjFileLowering().getTextSection());
01334 
01335   // Print out .file directives to specify files for .loc directives. These are
01336   // printed out early so that they precede any .loc directives.
01337   if (TAI->hasDotLocAndDotFile()) {
01338     for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
01339       // Remember source id starts at 1.
01340       std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
01341       sys::Path FullPath(getSourceDirectoryName(Id.first));
01342       bool AppendOk =
01343         FullPath.appendComponent(getSourceFileName(Id.second));
01344       assert(AppendOk && "Could not append filename to directory!");
01345       AppendOk = false;
01346       Asm->EmitFile(i, FullPath.toString());
01347       Asm->EOL();
01348     }
01349   }
01350 
01351   // Emit initial sections
01352   EmitInitial();
01353 
01354   if (TimePassesIsEnabled)
01355     DebugTimer->stopTimer();
01356 }
01357 
01358 /// EndModule - Emit all Dwarf sections that should come after the content.
01359 ///
01360 void DwarfDebug::EndModule() {
01361   if (!ShouldEmitDwarfDebug())
01362     return;
01363 
01364   if (TimePassesIsEnabled)
01365     DebugTimer->startTimer();
01366 
01367   // Standard sections final addresses.
01368   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
01369   EmitLabel("text_end", 0);
01370   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
01371   EmitLabel("data_end", 0);
01372 
01373   // End text sections.
01374   for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
01375     Asm->OutStreamer.SwitchSection(SectionMap[i]);
01376     EmitLabel("section_end", i);
01377   }
01378 
01379   // Emit common frame information.
01380   EmitCommonDebugFrame();
01381 
01382   // Emit function debug frame information
01383   for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
01384          E = DebugFrames.end(); I != E; ++I)
01385     EmitFunctionDebugFrame(*I);
01386 
01387   // Compute DIE offsets and sizes.
01388   SizeAndOffsets();
01389 
01390   // Emit all the DIEs into a debug info section
01391   EmitDebugInfo();
01392 
01393   // Corresponding abbreviations into a abbrev section.
01394   EmitAbbreviations();
01395 
01396   // Emit source line correspondence into a debug line section.
01397   EmitDebugLines();
01398 
01399   // Emit info into a debug pubnames section.
01400   EmitDebugPubNames();
01401 
01402   // Emit info into a debug str section.
01403   EmitDebugStr();
01404 
01405   // Emit info into a debug loc section.
01406   EmitDebugLoc();
01407 
01408   // Emit info into a debug aranges section.
01409   EmitDebugARanges();
01410 
01411   // Emit info into a debug ranges section.
01412   EmitDebugRanges();
01413 
01414   // Emit info into a debug macinfo section.
01415   EmitDebugMacInfo();
01416 
01417   // Emit inline info.
01418   EmitDebugInlineInfo();
01419 
01420   if (TimePassesIsEnabled)
01421     DebugTimer->stopTimer();
01422 }
01423 
01424 /// BeginFunction - Gather pre-function debug information.  Assumes being
01425 /// emitted immediately after the function entry point.
01426 void DwarfDebug::BeginFunction(MachineFunction *MF) {
01427   this->MF = MF;
01428 
01429   if (!ShouldEmitDwarfDebug()) return;
01430 
01431   if (TimePassesIsEnabled)
01432     DebugTimer->startTimer();
01433 
01434   // Begin accumulating function debug information.
01435   MMI->BeginFunction(MF);
01436 
01437   // Assumes in correct section after the entry point.
01438   EmitLabel("func_begin", ++SubprogramCount);
01439 
01440   // Emit label for the implicitly defined dbg.stoppoint at the start of the
01441   // function.
01442   DebugLoc FDL = MF->getDefaultDebugLoc();
01443   if (!FDL.isUnknown()) {
01444     DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
01445     unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
01446                                         DICompileUnit(DLT.CompileUnit));
01447     Asm->printLabel(LabelID);
01448   }
01449 
01450   if (TimePassesIsEnabled)
01451     DebugTimer->stopTimer();
01452 }
01453 
01454 /// EndFunction - Gather and emit post-function debug information.
01455 ///
01456 void DwarfDebug::EndFunction(MachineFunction *MF) {
01457   if (!ShouldEmitDwarfDebug()) return;
01458 
01459   if (TimePassesIsEnabled)
01460     DebugTimer->startTimer();
01461 
01462   // Define end label for subprogram.
01463   EmitLabel("func_end", SubprogramCount);
01464 
01465   // Get function line info.
01466   if (!Lines.empty()) {
01467     // Get section line info.
01468     unsigned ID = SectionMap.insert(Asm->getCurrentSection());
01469     if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
01470     std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
01471     // Append the function info to section info.
01472     SectionLineInfos.insert(SectionLineInfos.end(),
01473                             Lines.begin(), Lines.end());
01474   }
01475 
01476   // Construct the DbgScope for abstract instances.
01477   for (SmallVector<DbgScope *, 32>::iterator
01478          I = AbstractInstanceRootList.begin(),
01479          E = AbstractInstanceRootList.end(); I != E; ++I)
01480     ConstructFunctionDbgScope(*I);
01481 
01482   // Construct scopes for subprogram.
01483   if (FunctionDbgScope)
01484     ConstructFunctionDbgScope(FunctionDbgScope);
01485   else
01486     // FIXME: This is wrong. We are essentially getting past a problem with
01487     // debug information not being able to handle unreachable blocks that have
01488     // debug information in them. In particular, those unreachable blocks that
01489     // have "region end" info in them. That situation results in the "root
01490     // scope" not being created. If that's the case, then emit a "default"
01491     // scope, i.e., one that encompasses the whole function. This isn't
01492     // desirable. And a better way of handling this (and all of the debugging
01493     // information) needs to be explored.
01494     ConstructDefaultDbgScope(MF);
01495 
01496   DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
01497                                                MMI->getFrameMoves()));
01498 
01499   // Clear debug info
01500   if (FunctionDbgScope) {
01501     delete FunctionDbgScope;
01502     DbgScopeMap.clear();
01503     DbgAbstractScopeMap.clear();
01504     DbgConcreteScopeMap.clear();
01505     InlinedVariableScopes.clear();
01506     FunctionDbgScope = NULL;
01507     LexicalScopeStack.clear();
01508     AbstractInstanceRootList.clear();
01509     AbstractInstanceRootMap.clear();
01510   }
01511 
01512   Lines.clear();
01513 
01514   if (TimePassesIsEnabled)
01515     DebugTimer->stopTimer();
01516 }
01517 
01518 /// RecordSourceLine - Records location information and associates it with a
01519 /// label. Returns a unique label ID used to generate a label and provide
01520 /// correspondence to the source line list.
01521 unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
01522   if (TimePassesIsEnabled)
01523     DebugTimer->startTimer();
01524 
01525   CompileUnit *Unit = CompileUnitMap[V];
01526   assert(Unit && "Unable to find CompileUnit");
01527   unsigned ID = MMI->NextLabelID();
01528   Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
01529 
01530   if (TimePassesIsEnabled)
01531     DebugTimer->stopTimer();
01532 
01533   return ID;
01534 }
01535 
01536 /// RecordSourceLine - Records location information and associates it with a
01537 /// label. Returns a unique label ID used to generate a label and provide
01538 /// correspondence to the source line list.
01539 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
01540                                       DICompileUnit CU) {
01541   if (TimePassesIsEnabled)
01542     DebugTimer->startTimer();
01543 
01544   std::string Dir, Fn;
01545   unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
01546                                      CU.getFilename(Fn));
01547   unsigned ID = MMI->NextLabelID();
01548   Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
01549 
01550   if (TimePassesIsEnabled)
01551     DebugTimer->stopTimer();
01552 
01553   return ID;
01554 }
01555 
01556 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
01557 /// timed. Look up the source id with the given directory and source file
01558 /// names. If none currently exists, create a new id and insert it in the
01559 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
01560 /// well.
01561 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
01562                                          const std::string &FileName) {
01563   if (TimePassesIsEnabled)
01564     DebugTimer->startTimer();
01565 
01566   unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
01567 
01568   if (TimePassesIsEnabled)
01569     DebugTimer->stopTimer();
01570 
01571   return SrcId;
01572 }
01573 
01574 /// RecordRegionStart - Indicate the start of a region.
01575 unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
01576   if (TimePassesIsEnabled)
01577     DebugTimer->startTimer();
01578 
01579   DbgScope *Scope = getOrCreateScope(V);
01580   unsigned ID = MMI->NextLabelID();
01581   if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
01582   LexicalScopeStack.push_back(Scope);
01583 
01584   if (TimePassesIsEnabled)
01585     DebugTimer->stopTimer();
01586 
01587   return ID;
01588 }
01589 
01590 /// RecordRegionEnd - Indicate the end of a region.
01591 unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
01592   if (TimePassesIsEnabled)
01593     DebugTimer->startTimer();
01594 
01595   DbgScope *Scope = getOrCreateScope(V);
01596   unsigned ID = MMI->NextLabelID();
01597   Scope->setEndLabelID(ID);
01598   // FIXME : region.end() may not be in the last basic block.
01599   // For now, do not pop last lexical scope because next basic
01600   // block may start new inlined function's body.
01601   unsigned LSSize = LexicalScopeStack.size();
01602   if (LSSize != 0 && LSSize != 1)
01603     LexicalScopeStack.pop_back();
01604 
01605   if (TimePassesIsEnabled)
01606     DebugTimer->stopTimer();
01607 
01608   return ID;
01609 }
01610 
01611 /// RecordVariable - Indicate the declaration of a local variable.
01612 void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
01613                                 const MachineInstr *MI) {
01614   if (TimePassesIsEnabled)
01615     DebugTimer->startTimer();
01616 
01617   DIDescriptor Desc(GV);
01618   DbgScope *Scope = NULL;
01619   bool InlinedFnVar = false;
01620 
01621   if (Desc.getTag() == dwarf::DW_TAG_variable) {
01622     // GV is a global variable.
01623     DIGlobalVariable DG(GV);
01624     Scope = getOrCreateScope(DG.getContext().getGV());
01625   } else {
01626     DenseMap<const MachineInstr *, DbgScope *>::iterator
01627       SI = InlinedVariableScopes.find(MI);
01628 
01629     if (SI != InlinedVariableScopes.end()) {
01630       // or GV is an inlined local variable.
01631       Scope = SI->second;
01632       InlinedFnVar = true;
01633     } else {
01634       DIVariable DV(GV);
01635       GlobalVariable *V = DV.getContext().getGV();
01636 
01637       // or GV is a local variable.
01638       Scope = getOrCreateScope(V);
01639     }
01640   }
01641 
01642   assert(Scope && "Unable to find the variable's scope");
01643   DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex, InlinedFnVar);
01644   Scope->AddVariable(DV);
01645 
01646   if (TimePassesIsEnabled)
01647     DebugTimer->stopTimer();
01648 }
01649 
01650 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
01651 unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
01652                                           unsigned Line, unsigned Col) {
01653   unsigned LabelID = MMI->NextLabelID();
01654 
01655   if (!TAI->doesDwarfUsesInlineInfoSection())
01656     return LabelID;
01657 
01658   if (TimePassesIsEnabled)
01659     DebugTimer->startTimer();
01660 
01661   GlobalVariable *GV = SP.getGV();
01662   DenseMap<const GlobalVariable *, DbgScope *>::iterator
01663     II = AbstractInstanceRootMap.find(GV);
01664 
01665   if (II == AbstractInstanceRootMap.end()) {
01666     // Create an abstract instance entry for this inlined function if it doesn't
01667     // already exist.
01668     DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
01669 
01670     // Get the compile unit context.
01671     DIE *SPDie = ModuleCU->getDieMapSlotFor(GV);
01672     if (!SPDie)
01673       SPDie = CreateSubprogramDIE(ModuleCU, SP, false, true);
01674 
01675     // Mark as being inlined. This makes this subprogram entry an abstract
01676     // instance root.
01677     // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
01678     // that it's defined. That probably won't change in the future. However,
01679     // this could be more elegant.
01680     AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
01681 
01682     // Keep track of the abstract scope for this function.
01683     DbgAbstractScopeMap[GV] = Scope;
01684 
01685     AbstractInstanceRootMap[GV] = Scope;
01686     AbstractInstanceRootList.push_back(Scope);
01687   }
01688 
01689   // Create a concrete inlined instance for this inlined function.
01690   DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
01691   DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
01692   ScopeDie->setAbstractCompileUnit(ModuleCU);
01693 
01694   DIE *Origin = ModuleCU->getDieMapSlotFor(GV);
01695   AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
01696               dwarf::DW_FORM_ref4, Origin);
01697   AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
01698   AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
01699   AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
01700 
01701   ConcreteScope->setDie(ScopeDie);
01702   ConcreteScope->setStartLabelID(LabelID);
01703   MMI->RecordUsedDbgLabel(LabelID);
01704 
01705   LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
01706 
01707   // Keep track of the concrete scope that's inlined into this function.
01708   DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
01709     SI = DbgConcreteScopeMap.find(GV);
01710 
01711   if (SI == DbgConcreteScopeMap.end())
01712     DbgConcreteScopeMap[GV].push_back(ConcreteScope);
01713   else
01714     SI->second.push_back(ConcreteScope);
01715 
01716   // Track the start label for this inlined function.
01717   DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
01718     I = InlineInfo.find(GV);
01719 
01720   if (I == InlineInfo.end())
01721     InlineInfo[GV].push_back(LabelID);
01722   else
01723     I->second.push_back(LabelID);
01724 
01725   if (TimePassesIsEnabled)
01726     DebugTimer->stopTimer();
01727 
01728   return LabelID;
01729 }
01730 
01731 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
01732 unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
01733   if (!TAI->doesDwarfUsesInlineInfoSection())
01734     return 0;
01735 
01736   if (TimePassesIsEnabled)
01737     DebugTimer->startTimer();
01738 
01739   GlobalVariable *GV = SP.getGV();
01740   DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
01741     I = DbgConcreteScopeMap.find(GV);
01742 
01743   if (I == DbgConcreteScopeMap.end()) {
01744     // FIXME: Can this situation actually happen? And if so, should it?
01745     if (TimePassesIsEnabled)
01746       DebugTimer->stopTimer();
01747 
01748     return 0;
01749   }
01750 
01751   SmallVector<DbgScope *, 8> &Scopes = I->second;
01752   if (Scopes.empty()) {
01753     // Returned ID is 0 if this is unbalanced "end of inlined
01754     // scope". This could happen if optimizer eats dbg intrinsics
01755     // or "beginning of inlined scope" is not recoginized due to
01756     // missing location info. In such cases, ignore this region.end.
01757     return 0;
01758   }
01759 
01760   DbgScope *Scope = Scopes.back(); Scopes.pop_back();
01761   unsigned ID = MMI->NextLabelID();
01762   MMI->RecordUsedDbgLabel(ID);
01763   Scope->setEndLabelID(ID);
01764 
01765   if (TimePassesIsEnabled)
01766     DebugTimer->stopTimer();
01767 
01768   return ID;
01769 }
01770 
01771 /// RecordVariableScope - Record scope for the variable declared by
01772 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
01773 /// for only inlined subroutine variables. Other variables's scopes are
01774 /// determined during RecordVariable().
01775 void DwarfDebug::RecordVariableScope(DIVariable &DV,
01776                                      const MachineInstr *DeclareMI) {
01777   if (TimePassesIsEnabled)
01778     DebugTimer->startTimer();
01779 
01780   DISubprogram SP(DV.getContext().getGV());
01781 
01782   if (SP.isNull()) {
01783     if (TimePassesIsEnabled)
01784       DebugTimer->stopTimer();
01785 
01786     return;
01787   }
01788 
01789   DenseMap<GlobalVariable *, DbgScope *>::iterator
01790     I = DbgAbstractScopeMap.find(SP.getGV());
01791   if (I != DbgAbstractScopeMap.end())
01792     InlinedVariableScopes[DeclareMI] = I->second;
01793 
01794   if (TimePassesIsEnabled)
01795     DebugTimer->stopTimer();
01796 }
01797 
01798 //===----------------------------------------------------------------------===//
01799 // Emit Methods
01800 //===----------------------------------------------------------------------===//
01801 
01802 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
01803 ///
01804 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
01805   // Get the children.
01806   const std::vector<DIE *> &Children = Die->getChildren();
01807 
01808   // If not last sibling and has children then add sibling offset attribute.
01809   if (!Last && !Children.empty()) Die->AddSiblingOffset();
01810 
01811   // Record the abbreviation.
01812   AssignAbbrevNumber(Die->getAbbrev());
01813 
01814   // Get the abbreviation for this DIE.
01815   unsigned AbbrevNumber = Die->getAbbrevNumber();
01816   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
01817 
01818   // Set DIE offset
01819   Die->setOffset(Offset);
01820 
01821   // Start the size with the size of abbreviation code.
01822   Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
01823 
01824   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
01825   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
01826 
01827   // Size the DIE attribute values.
01828   for (unsigned i = 0, N = Values.size(); i < N; ++i)
01829     // Size attribute value.
01830     Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
01831 
01832   // Size the DIE children if any.
01833   if (!Children.empty()) {
01834     assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
01835            "Children flag not set");
01836 
01837     for (unsigned j = 0, M = Children.size(); j < M; ++j)
01838       Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
01839 
01840     // End of children marker.
01841     Offset += sizeof(int8_t);
01842   }
01843 
01844   Die->setSize(Offset - Die->getOffset());
01845   return Offset;
01846 }
01847 
01848 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
01849 ///
01850 void DwarfDebug::SizeAndOffsets() {
01851   // Compute size of compile unit header.
01852   static unsigned Offset =
01853     sizeof(int32_t) + // Length of Compilation Unit Info
01854     sizeof(int16_t) + // DWARF version number
01855     sizeof(int32_t) + // Offset Into Abbrev. Section
01856     sizeof(int8_t);   // Pointer Size (in bytes)
01857 
01858   SizeAndOffsetDie(ModuleCU->getDie(), Offset, true);
01859   CompileUnitOffsets[ModuleCU] = 0;
01860 }
01861 
01862 /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
01863 /// tools to recognize the object file contains Dwarf information.
01864 void DwarfDebug::EmitInitial() {
01865   // Check to see if we already emitted intial headers.
01866   if (didInitial) return;
01867   didInitial = true;
01868 
01869   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
01870   
01871   // Dwarf sections base addresses.
01872   if (TAI->doesDwarfRequireFrameSection()) {
01873     Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
01874     EmitLabel("section_debug_frame", 0);
01875   }
01876 
01877   Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
01878   EmitLabel("section_info", 0);
01879   Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
01880   EmitLabel("section_abbrev", 0);
01881   Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
01882   EmitLabel("section_aranges", 0);
01883 
01884   if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
01885     Asm->OutStreamer.SwitchSection(LineInfoDirective);
01886     EmitLabel("section_macinfo", 0);
01887   }
01888 
01889   Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
01890   EmitLabel("section_line", 0);
01891   Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
01892   EmitLabel("section_loc", 0);
01893   Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
01894   EmitLabel("section_pubnames", 0);
01895   Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
01896   EmitLabel("section_str", 0);
01897   Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
01898   EmitLabel("section_ranges", 0);
01899 
01900   Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
01901   EmitLabel("text_begin", 0);
01902   Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
01903   EmitLabel("data_begin", 0);
01904 }
01905 
01906 /// EmitDIE - Recusively Emits a debug information entry.
01907 ///
01908 void DwarfDebug::EmitDIE(DIE *Die) {
01909   // Get the abbreviation for this DIE.
01910   unsigned AbbrevNumber = Die->getAbbrevNumber();
01911   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
01912 
01913   Asm->EOL();
01914 
01915   // Emit the code (index) for the abbreviation.
01916   Asm->EmitULEB128Bytes(AbbrevNumber);
01917 
01918   if (Asm->isVerbose())
01919     Asm->EOL(std::string("Abbrev [" +
01920                          utostr(AbbrevNumber) +
01921                          "] 0x" + utohexstr(Die->getOffset()) +
01922                          ":0x" + utohexstr(Die->getSize()) + " " +
01923                          dwarf::TagString(Abbrev->getTag())));
01924   else
01925     Asm->EOL();
01926 
01927   SmallVector<DIEValue*, 32> &Values = Die->getValues();
01928   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
01929 
01930   // Emit the DIE attribute values.
01931   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
01932     unsigned Attr = AbbrevData[i].getAttribute();
01933     unsigned Form = AbbrevData[i].getForm();
01934     assert(Form && "Too many attributes for DIE (check abbreviation)");
01935 
01936     switch (Attr) {
01937     case dwarf::DW_AT_sibling:
01938       Asm->EmitInt32(Die->SiblingOffset());
01939       break;
01940     case dwarf::DW_AT_abstract_origin: {
01941       DIEEntry *E = cast<DIEEntry>(Values[i]);
01942       DIE *Origin = E->getEntry();
01943       unsigned Addr =
01944         CompileUnitOffsets[Die->getAbstractCompileUnit()] +
01945         Origin->getOffset();
01946 
01947       Asm->EmitInt32(Addr);
01948       break;
01949     }
01950     default:
01951       // Emit an attribute using the defined form.
01952       Values[i]->EmitValue(this, Form);
01953       break;
01954     }
01955 
01956     Asm->EOL(dwarf::AttributeString(Attr));
01957   }
01958 
01959   // Emit the DIE children if any.
01960   if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
01961     const std::vector<DIE *> &Children = Die->getChildren();
01962 
01963     for (unsigned j = 0, M = Children.size(); j < M; ++j)
01964       EmitDIE(Children[j]);
01965 
01966     Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
01967   }
01968 }
01969 
01970 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
01971 ///
01972 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
01973   DIE *Die = Unit->getDie();
01974 
01975   // Emit the compile units header.
01976   EmitLabel("info_begin", Unit->getID());
01977 
01978   // Emit size of content not including length itself
01979   unsigned ContentSize = Die->getSize() +
01980     sizeof(int16_t) + // DWARF version number
01981     sizeof(int32_t) + // Offset Into Abbrev. Section
01982     sizeof(int8_t) +  // Pointer Size (in bytes)
01983     sizeof(int32_t);  // FIXME - extra pad for gdb bug.
01984 
01985   Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
01986   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
01987   EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
01988   Asm->EOL("Offset Into Abbrev. Section");
01989   Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
01990 
01991   EmitDIE(Die);
01992   // FIXME - extra padding for gdb bug.
01993   Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
01994   Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
01995   Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
01996   Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
01997   EmitLabel("info_end", Unit->getID());
01998 
01999   Asm->EOL();
02000 }
02001 
02002 void DwarfDebug::EmitDebugInfo() {
02003   // Start debug info section.
02004   Asm->OutStreamer.SwitchSection(
02005                             Asm->getObjFileLowering().getDwarfInfoSection());
02006 
02007   EmitDebugInfoPerCU(ModuleCU);
02008 }
02009 
02010 /// EmitAbbreviations - Emit the abbreviation section.
02011 ///
02012 void DwarfDebug::EmitAbbreviations() const {
02013   // Check to see if it is worth the effort.
02014   if (!Abbreviations.empty()) {
02015     // Start the debug abbrev section.
02016     Asm->OutStreamer.SwitchSection(
02017                             Asm->getObjFileLowering().getDwarfAbbrevSection());
02018 
02019     EmitLabel("abbrev_begin", 0);
02020 
02021     // For each abbrevation.
02022     for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
02023       // Get abbreviation data
02024       const DIEAbbrev *Abbrev = Abbreviations[i];
02025 
02026       // Emit the abbrevations code (base 1 index.)
02027       Asm->EmitULEB128Bytes(Abbrev->getNumber());
02028       Asm->EOL("Abbreviation Code");
02029 
02030       // Emit the abbreviations data.
02031       Abbrev->Emit(Asm);
02032 
02033       Asm->EOL();
02034     }
02035 
02036     // Mark end of abbreviations.
02037     Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
02038 
02039     EmitLabel("abbrev_end", 0);
02040     Asm->EOL();
02041   }
02042 }
02043 
02044 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
02045 /// the line matrix.
02046 ///
02047 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
02048   // Define last address of section.
02049   Asm->EmitInt8(0); Asm->EOL("Extended Op");
02050   Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
02051   Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
02052   EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
02053 
02054   // Mark end of matrix.
02055   Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
02056   Asm->EmitULEB128Bytes(1); Asm->EOL();
02057   Asm->EmitInt8(1); Asm->EOL();
02058 }
02059 
02060 /// EmitDebugLines - Emit source line information.
02061 ///
02062 void DwarfDebug::EmitDebugLines() {
02063   // If the target is using .loc/.file, the assembler will be emitting the
02064   // .debug_line table automatically.
02065   if (TAI->hasDotLocAndDotFile())
02066     return;
02067 
02068   // Minimum line delta, thus ranging from -10..(255-10).
02069   const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
02070   // Maximum line delta, thus ranging from -10..(255-10).
02071   const int MaxLineDelta = 255 + MinLineDelta;
02072 
02073   // Start the dwarf line section.
02074   Asm->OutStreamer.SwitchSection(
02075                             Asm->getObjFileLowering().getDwarfLineSection());
02076 
02077   // Construct the section header.
02078   EmitDifference("line_end", 0, "line_begin", 0, true);
02079   Asm->EOL("Length of Source Line Info");
02080   EmitLabel("line_begin", 0);
02081 
02082   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
02083 
02084   EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
02085   Asm->EOL("Prolog Length");
02086   EmitLabel("line_prolog_begin", 0);
02087 
02088   Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
02089 
02090   Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
02091 
02092   Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
02093 
02094   Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
02095 
02096   Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
02097 
02098   // Line number standard opcode encodings argument count
02099   Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
02100   Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
02101   Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
02102   Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
02103   Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
02104   Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
02105   Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
02106   Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
02107   Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
02108 
02109   // Emit directories.
02110   for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
02111     Asm->EmitString(getSourceDirectoryName(DI));
02112     Asm->EOL("Directory");
02113   }
02114 
02115   Asm->EmitInt8(0); Asm->EOL("End of directories");
02116 
02117   // Emit files.
02118   for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
02119     // Remember source id starts at 1.
02120     std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
02121     Asm->EmitString(getSourceFileName(Id.second));
02122     Asm->EOL("Source");
02123     Asm->EmitULEB128Bytes(Id.first);
02124     Asm->EOL("Directory #");
02125     Asm->EmitULEB128Bytes(0);
02126     Asm->EOL("Mod date");
02127     Asm->EmitULEB128Bytes(0);
02128     Asm->EOL("File size");
02129   }
02130 
02131   Asm->EmitInt8(0); Asm->EOL("End of files");
02132 
02133   EmitLabel("line_prolog_end", 0);
02134 
02135   // A sequence for each text section.
02136   unsigned SecSrcLinesSize = SectionSourceLines.size();
02137 
02138   for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
02139     // Isolate current sections line info.
02140     const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
02141 
02142     /*if (Asm->isVerbose()) {
02143       const MCSection *S = SectionMap[j + 1];
02144       O << '\t' << TAI->getCommentString() << " Section"
02145         << S->getName() << '\n';
02146     }*/
02147     Asm->EOL();
02148 
02149     // Dwarf assumes we start with first line of first source file.
02150     unsigned Source = 1;
02151     unsigned Line = 1;
02152 
02153     // Construct rows of the address, source, line, column matrix.
02154     for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
02155       const SrcLineInfo &LineInfo = LineInfos[i];
02156       unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
02157       if (!LabelID) continue;
02158 
02159       if (!Asm->isVerbose())
02160         Asm->EOL();
02161       else {
02162         std::pair<unsigned, unsigned> SourceID =
02163           getSourceDirectoryAndFileIds(LineInfo.getSourceID());
02164         O << '\t' << TAI->getCommentString() << ' '
02165           << getSourceDirectoryName(SourceID.first) << ' '
02166           << getSourceFileName(SourceID.second)
02167           <<" :" << utostr_32(LineInfo.getLine()) << '\n';
02168       }
02169 
02170       // Define the line address.
02171       Asm->EmitInt8(0); Asm->EOL("Extended Op");
02172       Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
02173       Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
02174       EmitReference("label",  LabelID); Asm->EOL("Location label");
02175 
02176       // If change of source, then switch to the new source.
02177       if (Source != LineInfo.getSourceID()) {
02178         Source = LineInfo.getSourceID();
02179         Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
02180         Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
02181       }
02182 
02183       // If change of line.
02184       if (Line != LineInfo.getLine()) {
02185         // Determine offset.
02186         int Offset = LineInfo.getLine() - Line;
02187         int Delta = Offset - MinLineDelta;
02188 
02189         // Update line.
02190         Line = LineInfo.getLine();
02191 
02192         // If delta is small enough and in range...
02193         if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
02194           // ... then use fast opcode.
02195           Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
02196         } else {
02197           // ... otherwise use long hand.
02198           Asm->EmitInt8(dwarf::DW_LNS_advance_line);
02199           Asm->EOL("DW_LNS_advance_line");
02200           Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
02201           Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
02202         }
02203       } else {
02204         // Copy the previous row (different address or source)
02205         Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
02206       }
02207     }
02208 
02209     EmitEndOfLineMatrix(j + 1);
02210   }
02211 
02212   if (SecSrcLinesSize == 0)
02213     // Because we're emitting a debug_line section, we still need a line
02214     // table. The linker and friends expect it to exist. If there's nothing to
02215     // put into it, emit an empty table.
02216     EmitEndOfLineMatrix(1);
02217 
02218   EmitLabel("line_end", 0);
02219   Asm->EOL();
02220 }
02221 
02222 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
02223 ///
02224 void DwarfDebug::EmitCommonDebugFrame() {
02225   if (!TAI->doesDwarfRequireFrameSection())
02226     return;
02227 
02228   int stackGrowth =
02229     Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
02230       TargetFrameInfo::StackGrowsUp ?
02231     TD->getPointerSize() : -TD->getPointerSize();
02232 
02233   // Start the dwarf frame section.
02234   Asm->OutStreamer.SwitchSection(
02235                               Asm->getObjFileLowering().getDwarfFrameSection());
02236 
02237   EmitLabel("debug_frame_common", 0);
02238   EmitDifference("debug_frame_common_end", 0,
02239                  "debug_frame_common_begin", 0, true);
02240   Asm->EOL("Length of Common Information Entry");
02241 
02242   EmitLabel("debug_frame_common_begin", 0);
02243   Asm->EmitInt32((int)dwarf::DW_CIE_ID);
02244   Asm->EOL("CIE Identifier Tag");
02245   Asm->EmitInt8(dwarf::DW_CIE_VERSION);
02246   Asm->EOL("CIE Version");
02247   Asm->EmitString("");
02248   Asm->EOL("CIE Augmentation");
02249   Asm->EmitULEB128Bytes(1);
02250   Asm->EOL("CIE Code Alignment Factor");
02251   Asm->EmitSLEB128Bytes(stackGrowth);
02252   Asm->EOL("CIE Data Alignment Factor");
02253   Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
02254   Asm->EOL("CIE RA Column");
02255 
02256   std::vector<MachineMove> Moves;
02257   RI->getInitialFrameState(Moves);
02258 
02259   EmitFrameMoves(NULL, 0, Moves, false);
02260 
02261   Asm->EmitAlignment(2, 0, 0, false);
02262   EmitLabel("debug_frame_common_end", 0);
02263 
02264   Asm->EOL();
02265 }
02266 
02267 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
02268 /// section.
02269 void
02270 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
02271   if (!TAI->doesDwarfRequireFrameSection())
02272     return;
02273 
02274   // Start the dwarf frame section.
02275   Asm->OutStreamer.SwitchSection(
02276                               Asm->getObjFileLowering().getDwarfFrameSection());
02277 
02278   EmitDifference("debug_frame_end", DebugFrameInfo.Number,
02279                  "debug_frame_begin", DebugFrameInfo.Number, true);
02280   Asm->EOL("Length of Frame Information Entry");
02281 
02282   EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
02283 
02284   EmitSectionOffset("debug_frame_common", "section_debug_frame",
02285                     0, 0, true, false);
02286   Asm->EOL("FDE CIE offset");
02287 
02288   EmitReference("func_begin", DebugFrameInfo.Number);
02289   Asm->EOL("FDE initial location");
02290   EmitDifference("func_end", DebugFrameInfo.Number,
02291                  "func_begin", DebugFrameInfo.Number);
02292   Asm->EOL("FDE address range");
02293 
02294   EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
02295                  false);
02296 
02297   Asm->EmitAlignment(2, 0, 0, false);
02298   EmitLabel("debug_frame_end", DebugFrameInfo.Number);
02299 
02300   Asm->EOL();
02301 }
02302 
02303 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
02304   EmitDifference("pubnames_end", Unit->getID(),
02305                  "pubnames_begin", Unit->getID(), true);
02306   Asm->EOL("Length of Public Names Info");
02307 
02308   EmitLabel("pubnames_begin", Unit->getID());
02309 
02310   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
02311 
02312   EmitSectionOffset("info_begin", "section_info",
02313                     Unit->getID(), 0, true, false);
02314   Asm->EOL("Offset of Compilation Unit Info");
02315 
02316   EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
02317                  true);
02318   Asm->EOL("Compilation Unit Length");
02319 
02320   StringMap<DIE*> &Globals = Unit->getGlobals();
02321   for (StringMap<DIE*>::const_iterator
02322          GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
02323     const char *Name = GI->getKeyData();
02324     DIE * Entity = GI->second;
02325 
02326     Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
02327     Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
02328   }
02329 
02330   Asm->EmitInt32(0); Asm->EOL("End Mark");
02331   EmitLabel("pubnames_end", Unit->getID());
02332 
02333   Asm->EOL();
02334 }
02335 
02336 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
02337 ///
02338 void DwarfDebug::EmitDebugPubNames() {
02339   // Start the dwarf pubnames section.
02340   Asm->OutStreamer.SwitchSection(
02341                           Asm->getObjFileLowering().getDwarfPubNamesSection());
02342 
02343   EmitDebugPubNamesPerCU(ModuleCU);
02344 }
02345 
02346 /// EmitDebugStr - Emit visible names into a debug str section.
02347 ///
02348 void DwarfDebug::EmitDebugStr() {
02349   // Check to see if it is worth the effort.
02350   if (!StringPool.empty()) {
02351     // Start the dwarf str section.
02352     Asm->OutStreamer.SwitchSection(
02353                                 Asm->getObjFileLowering().getDwarfStrSection());
02354 
02355     // For each of strings in the string pool.
02356     for (unsigned StringID = 1, N = StringPool.size();
02357          StringID <= N; ++StringID) {
02358       // Emit a label for reference from debug information entries.
02359       EmitLabel("string", StringID);
02360 
02361       // Emit the string itself.
02362       const std::string &String = StringPool[StringID];
02363       Asm->EmitString(String); Asm->EOL();
02364     }
02365 
02366     Asm->EOL();
02367   }
02368 }
02369 
02370 /// EmitDebugLoc - Emit visible names into a debug loc section.
02371 ///
02372 void DwarfDebug::EmitDebugLoc() {
02373   // Start the dwarf loc section.
02374   Asm->OutStreamer.SwitchSection(
02375                               Asm->getObjFileLowering().getDwarfLocSection());
02376   Asm->EOL();
02377 }
02378 
02379 /// EmitDebugARanges - Emit visible names into a debug aranges section.
02380 ///
02381 void DwarfDebug::EmitDebugARanges() {
02382   // Start the dwarf aranges section.
02383   Asm->OutStreamer.SwitchSection(
02384                           Asm->getObjFileLowering().getDwarfARangesSection());
02385 
02386   // FIXME - Mock up
02387 #if 0
02388   CompileUnit *Unit = GetBaseCompileUnit();
02389 
02390   // Don't include size of length
02391   Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
02392 
02393   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
02394 
02395   EmitReference("info_begin", Unit->getID());
02396   Asm->EOL("Offset of Compilation Unit Info");
02397 
02398   Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
02399 
02400   Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
02401 
02402   Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
02403   Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
02404 
02405   // Range 1
02406   EmitReference("text_begin", 0); Asm->EOL("Address");
02407   EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
02408 
02409   Asm->EmitInt32(0); Asm->EOL("EOM (1)");
02410   Asm->EmitInt32(0); Asm->EOL("EOM (2)");
02411 #endif
02412 
02413   Asm->EOL();
02414 }
02415 
02416 /// EmitDebugRanges - Emit visible names into a debug ranges section.
02417 ///
02418 void DwarfDebug::EmitDebugRanges() {
02419   // Start the dwarf ranges section.
02420   Asm->OutStreamer.SwitchSection(
02421                             Asm->getObjFileLowering().getDwarfRangesSection());
02422   Asm->EOL();
02423 }
02424 
02425 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
02426 ///
02427 void DwarfDebug::EmitDebugMacInfo() {
02428   if (const MCSection *LineInfo = 
02429       Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
02430     // Start the dwarf macinfo section.
02431     Asm->OutStreamer.SwitchSection(LineInfo);
02432     Asm->EOL();
02433   }
02434 }
02435 
02436 /// EmitDebugInlineInfo - Emit inline info using following format.
02437 /// Section Header:
02438 /// 1. length of section
02439 /// 2. Dwarf version number
02440 /// 3. address size.
02441 ///
02442 /// Entries (one "entry" for each function that was inlined):
02443 ///
02444 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
02445 ///   otherwise offset into __debug_str for regular function name.
02446 /// 2. offset into __debug_str section for regular function name.
02447 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
02448 /// instances for the function.
02449 ///
02450 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
02451 /// inlined instance; the die_offset points to the inlined_subroutine die in the
02452 /// __debug_info section, and the low_pc is the starting address for the
02453 /// inlining instance.
02454 void DwarfDebug::EmitDebugInlineInfo() {
02455   if (!TAI->doesDwarfUsesInlineInfoSection())
02456     return;
02457 
02458   if (!ModuleCU)
02459     return;
02460 
02461   Asm->OutStreamer.SwitchSection(
02462                         Asm->getObjFileLowering().getDwarfDebugInlineSection());
02463   Asm->EOL();
02464   EmitDifference("debug_inlined_end", 1,
02465                  "debug_inlined_begin", 1, true);
02466   Asm->EOL("Length of Debug Inlined Information Entry");
02467 
02468   EmitLabel("debug_inlined_begin", 1);
02469 
02470   Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
02471   Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
02472 
02473   for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
02474          I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
02475     GlobalVariable *GV = I->first;
02476     SmallVector<unsigned, 4> &Labels = I->second;
02477     DISubprogram SP(GV);
02478     std::string Name;
02479     std::string LName;
02480 
02481     SP.getLinkageName(LName);
02482     SP.getName(Name);
02483 
02484     if (LName.empty())
02485       Asm->EmitString(Name);
02486     else {
02487       // Skip special LLVM prefix that is used to inform the asm printer to not
02488       // emit usual symbol prefix before the symbol name. This happens for
02489       // Objective-C symbol names and symbol whose name is replaced using GCC's
02490       // __asm__ attribute.
02491       if (LName[0] == 1)
02492         LName = &LName[1];
02493       Asm->EmitString(LName);
02494     }
02495     Asm->EOL("MIPS linkage name");
02496 
02497     Asm->EmitString(Name); Asm->EOL("Function name");
02498 
02499     Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
02500 
02501     for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
02502            LE = Labels.end(); LI != LE; ++LI) {
02503       DIE *SP = ModuleCU->getDieMapSlotFor(GV);
02504       Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
02505 
02506       if (TD->getPointerSize() == sizeof(int32_t))
02507         O << TAI->getData32bitsDirective();
02508       else
02509         O << TAI->getData64bitsDirective();
02510 
02511       PrintLabelName("label", *LI); Asm->EOL("low_pc");
02512     }
02513   }
02514 
02515   EmitLabel("debug_inlined_end", 1);
02516   Asm->EOL();
02517 }