DwarfDebug.cpp 80 KB

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