DwarfDebug.cpp 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585
  1. //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for writing dwarf debug info into asm files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "DwarfDebug.h"
  13. #include "ByteStreamer.h"
  14. #include "DIEHash.h"
  15. #include "DwarfCompileUnit.h"
  16. #include "DwarfExpression.h"
  17. #include "DwarfUnit.h"
  18. #include "llvm/ADT/APInt.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/CodeGen/AsmPrinter.h"
  23. #include "llvm/CodeGen/DIE.h"
  24. #include "llvm/CodeGen/LexicalScopes.h"
  25. #include "llvm/CodeGen/MachineBasicBlock.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineModuleInfo.h"
  28. #include "llvm/CodeGen/MachineOperand.h"
  29. #include "llvm/CodeGen/TargetInstrInfo.h"
  30. #include "llvm/CodeGen/TargetLowering.h"
  31. #include "llvm/CodeGen/TargetRegisterInfo.h"
  32. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  33. #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
  34. #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
  35. #include "llvm/IR/Constants.h"
  36. #include "llvm/IR/Function.h"
  37. #include "llvm/IR/GlobalVariable.h"
  38. #include "llvm/IR/Module.h"
  39. #include "llvm/MC/MCAsmInfo.h"
  40. #include "llvm/MC/MCContext.h"
  41. #include "llvm/MC/MCSection.h"
  42. #include "llvm/MC/MCStreamer.h"
  43. #include "llvm/MC/MCSymbol.h"
  44. #include "llvm/MC/MCTargetOptions.h"
  45. #include "llvm/MC/MachineLocation.h"
  46. #include "llvm/MC/SectionKind.h"
  47. #include "llvm/Support/Casting.h"
  48. #include "llvm/Support/CommandLine.h"
  49. #include "llvm/Support/Debug.h"
  50. #include "llvm/Support/ErrorHandling.h"
  51. #include "llvm/Support/MD5.h"
  52. #include "llvm/Support/raw_ostream.h"
  53. #include "llvm/Target/TargetLoweringObjectFile.h"
  54. #include "llvm/Target/TargetMachine.h"
  55. #include <algorithm>
  56. #include <cstddef>
  57. #include <iterator>
  58. #include <optional>
  59. #include <string>
  60. using namespace llvm;
  61. #define DEBUG_TYPE "dwarfdebug"
  62. STATISTIC(NumCSParams, "Number of dbg call site params created");
  63. static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
  64. "use-dwarf-ranges-base-address-specifier", cl::Hidden,
  65. cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
  66. static cl::opt<bool> GenerateARangeSection("generate-arange-section",
  67. cl::Hidden,
  68. cl::desc("Generate dwarf aranges"),
  69. cl::init(false));
  70. static cl::opt<bool>
  71. GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
  72. cl::desc("Generate DWARF4 type units."),
  73. cl::init(false));
  74. static cl::opt<bool> SplitDwarfCrossCuReferences(
  75. "split-dwarf-cross-cu-references", cl::Hidden,
  76. cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
  77. enum DefaultOnOff { Default, Enable, Disable };
  78. static cl::opt<DefaultOnOff> UnknownLocations(
  79. "use-unknown-locations", cl::Hidden,
  80. cl::desc("Make an absence of debug location information explicit."),
  81. cl::values(clEnumVal(Default, "At top of block or after label"),
  82. clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
  83. cl::init(Default));
  84. static cl::opt<AccelTableKind> AccelTables(
  85. "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
  86. cl::values(clEnumValN(AccelTableKind::Default, "Default",
  87. "Default for platform"),
  88. clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
  89. clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
  90. clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
  91. cl::init(AccelTableKind::Default));
  92. static cl::opt<DefaultOnOff>
  93. DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
  94. cl::desc("Use inlined strings rather than string section."),
  95. cl::values(clEnumVal(Default, "Default for platform"),
  96. clEnumVal(Enable, "Enabled"),
  97. clEnumVal(Disable, "Disabled")),
  98. cl::init(Default));
  99. static cl::opt<bool>
  100. NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
  101. cl::desc("Disable emission .debug_ranges section."),
  102. cl::init(false));
  103. static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
  104. "dwarf-sections-as-references", cl::Hidden,
  105. cl::desc("Use sections+offset as references rather than labels."),
  106. cl::values(clEnumVal(Default, "Default for platform"),
  107. clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
  108. cl::init(Default));
  109. static cl::opt<bool>
  110. UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,
  111. cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
  112. cl::init(false));
  113. static cl::opt<DefaultOnOff> DwarfOpConvert(
  114. "dwarf-op-convert", cl::Hidden,
  115. cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),
  116. cl::values(clEnumVal(Default, "Default for platform"),
  117. clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
  118. cl::init(Default));
  119. enum LinkageNameOption {
  120. DefaultLinkageNames,
  121. AllLinkageNames,
  122. AbstractLinkageNames
  123. };
  124. static cl::opt<LinkageNameOption>
  125. DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
  126. cl::desc("Which DWARF linkage-name attributes to emit."),
  127. cl::values(clEnumValN(DefaultLinkageNames, "Default",
  128. "Default for platform"),
  129. clEnumValN(AllLinkageNames, "All", "All"),
  130. clEnumValN(AbstractLinkageNames, "Abstract",
  131. "Abstract subprograms")),
  132. cl::init(DefaultLinkageNames));
  133. static cl::opt<DwarfDebug::MinimizeAddrInV5> MinimizeAddrInV5Option(
  134. "minimize-addr-in-v5", cl::Hidden,
  135. cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
  136. "address pool entry sharing to reduce relocations/object size"),
  137. cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default",
  138. "Default address minimization strategy"),
  139. clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges",
  140. "Use rnglists for contiguous ranges if that allows "
  141. "using a pre-existing base address"),
  142. clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions,
  143. "Expressions",
  144. "Use exprloc addrx+offset expressions for any "
  145. "address with a prior base address"),
  146. clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form",
  147. "Use addrx+offset extension form for any address "
  148. "with a prior base address"),
  149. clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled",
  150. "Stuff")),
  151. cl::init(DwarfDebug::MinimizeAddrInV5::Default));
  152. static constexpr unsigned ULEB128PadSize = 4;
  153. void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
  154. getActiveStreamer().emitInt8(
  155. Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
  156. : dwarf::OperationEncodingString(Op));
  157. }
  158. void DebugLocDwarfExpression::emitSigned(int64_t Value) {
  159. getActiveStreamer().emitSLEB128(Value, Twine(Value));
  160. }
  161. void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
  162. getActiveStreamer().emitULEB128(Value, Twine(Value));
  163. }
  164. void DebugLocDwarfExpression::emitData1(uint8_t Value) {
  165. getActiveStreamer().emitInt8(Value, Twine(Value));
  166. }
  167. void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
  168. assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
  169. getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
  170. }
  171. bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
  172. llvm::Register MachineReg) {
  173. // This information is not available while emitting .debug_loc entries.
  174. return false;
  175. }
  176. void DebugLocDwarfExpression::enableTemporaryBuffer() {
  177. assert(!IsBuffering && "Already buffering?");
  178. if (!TmpBuf)
  179. TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
  180. IsBuffering = true;
  181. }
  182. void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
  183. unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
  184. return TmpBuf ? TmpBuf->Bytes.size() : 0;
  185. }
  186. void DebugLocDwarfExpression::commitTemporaryBuffer() {
  187. if (!TmpBuf)
  188. return;
  189. for (auto Byte : enumerate(TmpBuf->Bytes)) {
  190. const char *Comment = (Byte.index() < TmpBuf->Comments.size())
  191. ? TmpBuf->Comments[Byte.index()].c_str()
  192. : "";
  193. OutBS.emitInt8(Byte.value(), Comment);
  194. }
  195. TmpBuf->Bytes.clear();
  196. TmpBuf->Comments.clear();
  197. }
  198. const DIType *DbgVariable::getType() const {
  199. return getVariable()->getType();
  200. }
  201. /// Get .debug_loc entry for the instruction range starting at MI.
  202. static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
  203. const DIExpression *Expr = MI->getDebugExpression();
  204. const bool IsVariadic = MI->isDebugValueList();
  205. assert(MI->getNumOperands() >= 3);
  206. SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;
  207. for (const MachineOperand &Op : MI->debug_operands()) {
  208. if (Op.isReg()) {
  209. MachineLocation MLoc(Op.getReg(),
  210. MI->isNonListDebugValue() && MI->isDebugOffsetImm());
  211. DbgValueLocEntries.push_back(DbgValueLocEntry(MLoc));
  212. } else if (Op.isTargetIndex()) {
  213. DbgValueLocEntries.push_back(
  214. DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));
  215. } else if (Op.isImm())
  216. DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getImm()));
  217. else if (Op.isFPImm())
  218. DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getFPImm()));
  219. else if (Op.isCImm())
  220. DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getCImm()));
  221. else
  222. llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");
  223. }
  224. return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
  225. }
  226. void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
  227. assert(FrameIndexExprs.empty() && "Already initialized?");
  228. assert(!ValueLoc.get() && "Already initialized?");
  229. assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
  230. assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
  231. "Wrong inlined-at");
  232. ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
  233. if (auto *E = DbgValue->getDebugExpression())
  234. if (E->getNumElements())
  235. FrameIndexExprs.push_back({0, E});
  236. }
  237. ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
  238. if (FrameIndexExprs.size() == 1)
  239. return FrameIndexExprs;
  240. assert(llvm::all_of(FrameIndexExprs,
  241. [](const FrameIndexExpr &A) {
  242. return A.Expr->isFragment();
  243. }) &&
  244. "multiple FI expressions without DW_OP_LLVM_fragment");
  245. llvm::sort(FrameIndexExprs,
  246. [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
  247. return A.Expr->getFragmentInfo()->OffsetInBits <
  248. B.Expr->getFragmentInfo()->OffsetInBits;
  249. });
  250. return FrameIndexExprs;
  251. }
  252. void DbgVariable::addMMIEntry(const DbgVariable &V) {
  253. assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
  254. assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
  255. assert(V.getVariable() == getVariable() && "conflicting variable");
  256. assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
  257. assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
  258. assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
  259. // FIXME: This logic should not be necessary anymore, as we now have proper
  260. // deduplication. However, without it, we currently run into the assertion
  261. // below, which means that we are likely dealing with broken input, i.e. two
  262. // non-fragment entries for the same variable at different frame indices.
  263. if (FrameIndexExprs.size()) {
  264. auto *Expr = FrameIndexExprs.back().Expr;
  265. if (!Expr || !Expr->isFragment())
  266. return;
  267. }
  268. for (const auto &FIE : V.FrameIndexExprs)
  269. // Ignore duplicate entries.
  270. if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
  271. return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
  272. }))
  273. FrameIndexExprs.push_back(FIE);
  274. assert((FrameIndexExprs.size() == 1 ||
  275. llvm::all_of(FrameIndexExprs,
  276. [](FrameIndexExpr &FIE) {
  277. return FIE.Expr && FIE.Expr->isFragment();
  278. })) &&
  279. "conflicting locations for variable");
  280. }
  281. static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
  282. bool GenerateTypeUnits,
  283. DebuggerKind Tuning,
  284. const Triple &TT) {
  285. // Honor an explicit request.
  286. if (AccelTables != AccelTableKind::Default)
  287. return AccelTables;
  288. // Accelerator tables with type units are currently not supported.
  289. if (GenerateTypeUnits)
  290. return AccelTableKind::None;
  291. // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
  292. // always implies debug_names. For lower standard versions we use apple
  293. // accelerator tables on apple platforms and debug_names elsewhere.
  294. if (DwarfVersion >= 5)
  295. return AccelTableKind::Dwarf;
  296. if (Tuning == DebuggerKind::LLDB)
  297. return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
  298. : AccelTableKind::Dwarf;
  299. return AccelTableKind::None;
  300. }
  301. DwarfDebug::DwarfDebug(AsmPrinter *A)
  302. : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
  303. InfoHolder(A, "info_string", DIEValueAllocator),
  304. SkeletonHolder(A, "skel_string", DIEValueAllocator),
  305. IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
  306. const Triple &TT = Asm->TM.getTargetTriple();
  307. // Make sure we know our "debugger tuning". The target option takes
  308. // precedence; fall back to triple-based defaults.
  309. if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
  310. DebuggerTuning = Asm->TM.Options.DebuggerTuning;
  311. else if (IsDarwin)
  312. DebuggerTuning = DebuggerKind::LLDB;
  313. else if (TT.isPS())
  314. DebuggerTuning = DebuggerKind::SCE;
  315. else if (TT.isOSAIX())
  316. DebuggerTuning = DebuggerKind::DBX;
  317. else
  318. DebuggerTuning = DebuggerKind::GDB;
  319. if (DwarfInlinedStrings == Default)
  320. UseInlineStrings = TT.isNVPTX() || tuneForDBX();
  321. else
  322. UseInlineStrings = DwarfInlinedStrings == Enable;
  323. UseLocSection = !TT.isNVPTX();
  324. HasAppleExtensionAttributes = tuneForLLDB();
  325. // Handle split DWARF.
  326. HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
  327. // SCE defaults to linkage names only for abstract subprograms.
  328. if (DwarfLinkageNames == DefaultLinkageNames)
  329. UseAllLinkageNames = !tuneForSCE();
  330. else
  331. UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
  332. unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
  333. unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
  334. : MMI->getModule()->getDwarfVersion();
  335. // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
  336. DwarfVersion =
  337. TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
  338. bool Dwarf64 = DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3.
  339. TT.isArch64Bit(); // DWARF64 requires 64-bit relocations.
  340. // Support DWARF64
  341. // 1: For ELF when requested.
  342. // 2: For XCOFF64: the AIX assembler will fill in debug section lengths
  343. // according to the DWARF64 format for 64-bit assembly, so we must use
  344. // DWARF64 in the compiler too for 64-bit mode.
  345. Dwarf64 &=
  346. ((Asm->TM.Options.MCOptions.Dwarf64 || MMI->getModule()->isDwarf64()) &&
  347. TT.isOSBinFormatELF()) ||
  348. TT.isOSBinFormatXCOFF();
  349. if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
  350. report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");
  351. UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
  352. // Use sections as references. Force for NVPTX.
  353. if (DwarfSectionsAsReferences == Default)
  354. UseSectionsAsReferences = TT.isNVPTX();
  355. else
  356. UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
  357. // Don't generate type units for unsupported object file formats.
  358. GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
  359. A->TM.getTargetTriple().isOSBinFormatWasm()) &&
  360. GenerateDwarfTypeUnits;
  361. TheAccelTableKind = computeAccelTableKind(
  362. DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
  363. // Work around a GDB bug. GDB doesn't support the standard opcode;
  364. // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
  365. // is defined as of DWARF 3.
  366. // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
  367. // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
  368. UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
  369. UseDWARF2Bitfields = DwarfVersion < 4;
  370. // The DWARF v5 string offsets table has - possibly shared - contributions
  371. // from each compile and type unit each preceded by a header. The string
  372. // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
  373. // a monolithic string offsets table without any header.
  374. UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
  375. // Emit call-site-param debug info for GDB and LLDB, if the target supports
  376. // the debug entry values feature. It can also be enabled explicitly.
  377. EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
  378. // It is unclear if the GCC .debug_macro extension is well-specified
  379. // for split DWARF. For now, do not allow LLVM to emit it.
  380. UseDebugMacroSection =
  381. DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
  382. if (DwarfOpConvert == Default)
  383. EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
  384. else
  385. EnableOpConvert = (DwarfOpConvert == Enable);
  386. // Split DWARF would benefit object size significantly by trading reductions
  387. // in address pool usage for slightly increased range list encodings.
  388. if (DwarfVersion >= 5) {
  389. MinimizeAddr = MinimizeAddrInV5Option;
  390. // FIXME: In the future, enable this by default for Split DWARF where the
  391. // tradeoff is more pronounced due to being able to offload the range
  392. // lists to the dwo file and shrink object files/reduce relocations there.
  393. if (MinimizeAddr == MinimizeAddrInV5::Default)
  394. MinimizeAddr = MinimizeAddrInV5::Disabled;
  395. }
  396. Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
  397. Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
  398. : dwarf::DWARF32);
  399. }
  400. // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
  401. DwarfDebug::~DwarfDebug() = default;
  402. static bool isObjCClass(StringRef Name) {
  403. return Name.startswith("+") || Name.startswith("-");
  404. }
  405. static bool hasObjCCategory(StringRef Name) {
  406. if (!isObjCClass(Name))
  407. return false;
  408. return Name.contains(") ");
  409. }
  410. static void getObjCClassCategory(StringRef In, StringRef &Class,
  411. StringRef &Category) {
  412. if (!hasObjCCategory(In)) {
  413. Class = In.slice(In.find('[') + 1, In.find(' '));
  414. Category = "";
  415. return;
  416. }
  417. Class = In.slice(In.find('[') + 1, In.find('('));
  418. Category = In.slice(In.find('[') + 1, In.find(' '));
  419. }
  420. static StringRef getObjCMethodName(StringRef In) {
  421. return In.slice(In.find(' ') + 1, In.find(']'));
  422. }
  423. // Add the various names to the Dwarf accelerator table names.
  424. void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
  425. const DISubprogram *SP, DIE &Die) {
  426. if (getAccelTableKind() != AccelTableKind::Apple &&
  427. CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
  428. return;
  429. if (!SP->isDefinition())
  430. return;
  431. if (SP->getName() != "")
  432. addAccelName(CU, SP->getName(), Die);
  433. // If the linkage name is different than the name, go ahead and output that as
  434. // well into the name table. Only do that if we are going to actually emit
  435. // that name.
  436. if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
  437. (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
  438. addAccelName(CU, SP->getLinkageName(), Die);
  439. // If this is an Objective-C selector name add it to the ObjC accelerator
  440. // too.
  441. if (isObjCClass(SP->getName())) {
  442. StringRef Class, Category;
  443. getObjCClassCategory(SP->getName(), Class, Category);
  444. addAccelObjC(CU, Class, Die);
  445. if (Category != "")
  446. addAccelObjC(CU, Category, Die);
  447. // Also add the base method name to the name table.
  448. addAccelName(CU, getObjCMethodName(SP->getName()), Die);
  449. }
  450. }
  451. /// Check whether we should create a DIE for the given Scope, return true
  452. /// if we don't create a DIE (the corresponding DIE is null).
  453. bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
  454. if (Scope->isAbstractScope())
  455. return false;
  456. // We don't create a DIE if there is no Range.
  457. const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
  458. if (Ranges.empty())
  459. return true;
  460. if (Ranges.size() > 1)
  461. return false;
  462. // We don't create a DIE if we have a single Range and the end label
  463. // is null.
  464. return !getLabelAfterInsn(Ranges.front().second);
  465. }
  466. template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
  467. F(CU);
  468. if (auto *SkelCU = CU.getSkeleton())
  469. if (CU.getCUNode()->getSplitDebugInlining())
  470. F(*SkelCU);
  471. }
  472. bool DwarfDebug::shareAcrossDWOCUs() const {
  473. return SplitDwarfCrossCuReferences;
  474. }
  475. void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
  476. LexicalScope *Scope) {
  477. assert(Scope && Scope->getScopeNode());
  478. assert(Scope->isAbstractScope());
  479. assert(!Scope->getInlinedAt());
  480. auto *SP = cast<DISubprogram>(Scope->getScopeNode());
  481. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  482. // was inlined from another compile unit.
  483. if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
  484. // Avoid building the original CU if it won't be used
  485. SrcCU.constructAbstractSubprogramScopeDIE(Scope);
  486. else {
  487. auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
  488. if (auto *SkelCU = CU.getSkeleton()) {
  489. (shareAcrossDWOCUs() ? CU : SrcCU)
  490. .constructAbstractSubprogramScopeDIE(Scope);
  491. if (CU.getCUNode()->getSplitDebugInlining())
  492. SkelCU->constructAbstractSubprogramScopeDIE(Scope);
  493. } else
  494. CU.constructAbstractSubprogramScopeDIE(Scope);
  495. }
  496. }
  497. /// Represents a parameter whose call site value can be described by applying a
  498. /// debug expression to a register in the forwarded register worklist.
  499. struct FwdRegParamInfo {
  500. /// The described parameter register.
  501. unsigned ParamReg;
  502. /// Debug expression that has been built up when walking through the
  503. /// instruction chain that produces the parameter's value.
  504. const DIExpression *Expr;
  505. };
  506. /// Register worklist for finding call site values.
  507. using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
  508. /// Container for the set of registers known to be clobbered on the path to a
  509. /// call site.
  510. using ClobberedRegSet = SmallSet<Register, 16>;
  511. /// Append the expression \p Addition to \p Original and return the result.
  512. static const DIExpression *combineDIExpressions(const DIExpression *Original,
  513. const DIExpression *Addition) {
  514. std::vector<uint64_t> Elts = Addition->getElements().vec();
  515. // Avoid multiple DW_OP_stack_values.
  516. if (Original->isImplicit() && Addition->isImplicit())
  517. erase_value(Elts, dwarf::DW_OP_stack_value);
  518. const DIExpression *CombinedExpr =
  519. (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
  520. return CombinedExpr;
  521. }
  522. /// Emit call site parameter entries that are described by the given value and
  523. /// debug expression.
  524. template <typename ValT>
  525. static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
  526. ArrayRef<FwdRegParamInfo> DescribedParams,
  527. ParamSet &Params) {
  528. for (auto Param : DescribedParams) {
  529. bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
  530. // TODO: Entry value operations can currently not be combined with any
  531. // other expressions, so we can't emit call site entries in those cases.
  532. if (ShouldCombineExpressions && Expr->isEntryValue())
  533. continue;
  534. // If a parameter's call site value is produced by a chain of
  535. // instructions we may have already created an expression for the
  536. // parameter when walking through the instructions. Append that to the
  537. // base expression.
  538. const DIExpression *CombinedExpr =
  539. ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
  540. : Expr;
  541. assert((!CombinedExpr || CombinedExpr->isValid()) &&
  542. "Combined debug expression is invalid");
  543. DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));
  544. DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
  545. Params.push_back(CSParm);
  546. ++NumCSParams;
  547. }
  548. }
  549. /// Add \p Reg to the worklist, if it's not already present, and mark that the
  550. /// given parameter registers' values can (potentially) be described using
  551. /// that register and an debug expression.
  552. static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
  553. const DIExpression *Expr,
  554. ArrayRef<FwdRegParamInfo> ParamsToAdd) {
  555. auto I = Worklist.insert({Reg, {}});
  556. auto &ParamsForFwdReg = I.first->second;
  557. for (auto Param : ParamsToAdd) {
  558. assert(none_of(ParamsForFwdReg,
  559. [Param](const FwdRegParamInfo &D) {
  560. return D.ParamReg == Param.ParamReg;
  561. }) &&
  562. "Same parameter described twice by forwarding reg");
  563. // If a parameter's call site value is produced by a chain of
  564. // instructions we may have already created an expression for the
  565. // parameter when walking through the instructions. Append that to the
  566. // new expression.
  567. const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
  568. ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
  569. }
  570. }
  571. /// Interpret values loaded into registers by \p CurMI.
  572. static void interpretValues(const MachineInstr *CurMI,
  573. FwdRegWorklist &ForwardedRegWorklist,
  574. ParamSet &Params,
  575. ClobberedRegSet &ClobberedRegUnits) {
  576. const MachineFunction *MF = CurMI->getMF();
  577. const DIExpression *EmptyExpr =
  578. DIExpression::get(MF->getFunction().getContext(), {});
  579. const auto &TRI = *MF->getSubtarget().getRegisterInfo();
  580. const auto &TII = *MF->getSubtarget().getInstrInfo();
  581. const auto &TLI = *MF->getSubtarget().getTargetLowering();
  582. // If an instruction defines more than one item in the worklist, we may run
  583. // into situations where a worklist register's value is (potentially)
  584. // described by the previous value of another register that is also defined
  585. // by that instruction.
  586. //
  587. // This can for example occur in cases like this:
  588. //
  589. // $r1 = mov 123
  590. // $r0, $r1 = mvrr $r1, 456
  591. // call @foo, $r0, $r1
  592. //
  593. // When describing $r1's value for the mvrr instruction, we need to make sure
  594. // that we don't finalize an entry value for $r0, as that is dependent on the
  595. // previous value of $r1 (123 rather than 456).
  596. //
  597. // In order to not have to distinguish between those cases when finalizing
  598. // entry values, we simply postpone adding new parameter registers to the
  599. // worklist, by first keeping them in this temporary container until the
  600. // instruction has been handled.
  601. FwdRegWorklist TmpWorklistItems;
  602. // If the MI is an instruction defining one or more parameters' forwarding
  603. // registers, add those defines.
  604. ClobberedRegSet NewClobberedRegUnits;
  605. auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
  606. SmallSetVector<unsigned, 4> &Defs) {
  607. if (MI.isDebugInstr())
  608. return;
  609. for (const MachineOperand &MO : MI.operands()) {
  610. if (MO.isReg() && MO.isDef() && MO.getReg().isPhysical()) {
  611. for (auto &FwdReg : ForwardedRegWorklist)
  612. if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
  613. Defs.insert(FwdReg.first);
  614. for (MCRegUnitIterator Units(MO.getReg(), &TRI); Units.isValid(); ++Units)
  615. NewClobberedRegUnits.insert(*Units);
  616. }
  617. }
  618. };
  619. // Set of worklist registers that are defined by this instruction.
  620. SmallSetVector<unsigned, 4> FwdRegDefs;
  621. getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
  622. if (FwdRegDefs.empty()) {
  623. // Any definitions by this instruction will clobber earlier reg movements.
  624. ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
  625. NewClobberedRegUnits.end());
  626. return;
  627. }
  628. // It's possible that we find a copy from a non-volatile register to the param
  629. // register, which is clobbered in the meantime. Test for clobbered reg unit
  630. // overlaps before completing.
  631. auto IsRegClobberedInMeantime = [&](Register Reg) -> bool {
  632. for (auto &RegUnit : ClobberedRegUnits)
  633. if (TRI.hasRegUnit(Reg, RegUnit))
  634. return true;
  635. return false;
  636. };
  637. for (auto ParamFwdReg : FwdRegDefs) {
  638. if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
  639. if (ParamValue->first.isImm()) {
  640. int64_t Val = ParamValue->first.getImm();
  641. finishCallSiteParams(Val, ParamValue->second,
  642. ForwardedRegWorklist[ParamFwdReg], Params);
  643. } else if (ParamValue->first.isReg()) {
  644. Register RegLoc = ParamValue->first.getReg();
  645. Register SP = TLI.getStackPointerRegisterToSaveRestore();
  646. Register FP = TRI.getFrameRegister(*MF);
  647. bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
  648. if (!IsRegClobberedInMeantime(RegLoc) &&
  649. (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {
  650. MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);
  651. finishCallSiteParams(MLoc, ParamValue->second,
  652. ForwardedRegWorklist[ParamFwdReg], Params);
  653. } else {
  654. // ParamFwdReg was described by the non-callee saved register
  655. // RegLoc. Mark that the call site values for the parameters are
  656. // dependent on that register instead of ParamFwdReg. Since RegLoc
  657. // may be a register that will be handled in this iteration, we
  658. // postpone adding the items to the worklist, and instead keep them
  659. // in a temporary container.
  660. addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
  661. ForwardedRegWorklist[ParamFwdReg]);
  662. }
  663. }
  664. }
  665. }
  666. // Remove all registers that this instruction defines from the worklist.
  667. for (auto ParamFwdReg : FwdRegDefs)
  668. ForwardedRegWorklist.erase(ParamFwdReg);
  669. // Any definitions by this instruction will clobber earlier reg movements.
  670. ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
  671. NewClobberedRegUnits.end());
  672. // Now that we are done handling this instruction, add items from the
  673. // temporary worklist to the real one.
  674. for (auto &New : TmpWorklistItems)
  675. addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
  676. TmpWorklistItems.clear();
  677. }
  678. static bool interpretNextInstr(const MachineInstr *CurMI,
  679. FwdRegWorklist &ForwardedRegWorklist,
  680. ParamSet &Params,
  681. ClobberedRegSet &ClobberedRegUnits) {
  682. // Skip bundle headers.
  683. if (CurMI->isBundle())
  684. return true;
  685. // If the next instruction is a call we can not interpret parameter's
  686. // forwarding registers or we finished the interpretation of all
  687. // parameters.
  688. if (CurMI->isCall())
  689. return false;
  690. if (ForwardedRegWorklist.empty())
  691. return false;
  692. // Avoid NOP description.
  693. if (CurMI->getNumOperands() == 0)
  694. return true;
  695. interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
  696. return true;
  697. }
  698. /// Try to interpret values loaded into registers that forward parameters
  699. /// for \p CallMI. Store parameters with interpreted value into \p Params.
  700. static void collectCallSiteParameters(const MachineInstr *CallMI,
  701. ParamSet &Params) {
  702. const MachineFunction *MF = CallMI->getMF();
  703. const auto &CalleesMap = MF->getCallSitesInfo();
  704. auto CallFwdRegsInfo = CalleesMap.find(CallMI);
  705. // There is no information for the call instruction.
  706. if (CallFwdRegsInfo == CalleesMap.end())
  707. return;
  708. const MachineBasicBlock *MBB = CallMI->getParent();
  709. // Skip the call instruction.
  710. auto I = std::next(CallMI->getReverseIterator());
  711. FwdRegWorklist ForwardedRegWorklist;
  712. const DIExpression *EmptyExpr =
  713. DIExpression::get(MF->getFunction().getContext(), {});
  714. // Add all the forwarding registers into the ForwardedRegWorklist.
  715. for (const auto &ArgReg : CallFwdRegsInfo->second) {
  716. bool InsertedReg =
  717. ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
  718. .second;
  719. assert(InsertedReg && "Single register used to forward two arguments?");
  720. (void)InsertedReg;
  721. }
  722. // Do not emit CSInfo for undef forwarding registers.
  723. for (const auto &MO : CallMI->uses())
  724. if (MO.isReg() && MO.isUndef())
  725. ForwardedRegWorklist.erase(MO.getReg());
  726. // We erase, from the ForwardedRegWorklist, those forwarding registers for
  727. // which we successfully describe a loaded value (by using
  728. // the describeLoadedValue()). For those remaining arguments in the working
  729. // list, for which we do not describe a loaded value by
  730. // the describeLoadedValue(), we try to generate an entry value expression
  731. // for their call site value description, if the call is within the entry MBB.
  732. // TODO: Handle situations when call site parameter value can be described
  733. // as the entry value within basic blocks other than the first one.
  734. bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
  735. // Search for a loading value in forwarding registers inside call delay slot.
  736. ClobberedRegSet ClobberedRegUnits;
  737. if (CallMI->hasDelaySlot()) {
  738. auto Suc = std::next(CallMI->getIterator());
  739. // Only one-instruction delay slot is supported.
  740. auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
  741. (void)BundleEnd;
  742. assert(std::next(Suc) == BundleEnd &&
  743. "More than one instruction in call delay slot");
  744. // Try to interpret value loaded by instruction.
  745. if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params, ClobberedRegUnits))
  746. return;
  747. }
  748. // Search for a loading value in forwarding registers.
  749. for (; I != MBB->rend(); ++I) {
  750. // Try to interpret values loaded by instruction.
  751. if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params, ClobberedRegUnits))
  752. return;
  753. }
  754. // Emit the call site parameter's value as an entry value.
  755. if (ShouldTryEmitEntryVals) {
  756. // Create an expression where the register's entry value is used.
  757. DIExpression *EntryExpr = DIExpression::get(
  758. MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
  759. for (auto &RegEntry : ForwardedRegWorklist) {
  760. MachineLocation MLoc(RegEntry.first);
  761. finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
  762. }
  763. }
  764. }
  765. void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
  766. DwarfCompileUnit &CU, DIE &ScopeDIE,
  767. const MachineFunction &MF) {
  768. // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
  769. // the subprogram is required to have one.
  770. if (!SP.areAllCallsDescribed() || !SP.isDefinition())
  771. return;
  772. // Use DW_AT_call_all_calls to express that call site entries are present
  773. // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
  774. // because one of its requirements is not met: call site entries for
  775. // optimized-out calls are elided.
  776. CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
  777. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  778. assert(TII && "TargetInstrInfo not found: cannot label tail calls");
  779. // Delay slot support check.
  780. auto delaySlotSupported = [&](const MachineInstr &MI) {
  781. if (!MI.isBundledWithSucc())
  782. return false;
  783. auto Suc = std::next(MI.getIterator());
  784. auto CallInstrBundle = getBundleStart(MI.getIterator());
  785. (void)CallInstrBundle;
  786. auto DelaySlotBundle = getBundleStart(Suc);
  787. (void)DelaySlotBundle;
  788. // Ensure that label after call is following delay slot instruction.
  789. // Ex. CALL_INSTRUCTION {
  790. // DELAY_SLOT_INSTRUCTION }
  791. // LABEL_AFTER_CALL
  792. assert(getLabelAfterInsn(&*CallInstrBundle) ==
  793. getLabelAfterInsn(&*DelaySlotBundle) &&
  794. "Call and its successor instruction don't have same label after.");
  795. return true;
  796. };
  797. // Emit call site entries for each call or tail call in the function.
  798. for (const MachineBasicBlock &MBB : MF) {
  799. for (const MachineInstr &MI : MBB.instrs()) {
  800. // Bundles with call in them will pass the isCall() test below but do not
  801. // have callee operand information so skip them here. Iterator will
  802. // eventually reach the call MI.
  803. if (MI.isBundle())
  804. continue;
  805. // Skip instructions which aren't calls. Both calls and tail-calling jump
  806. // instructions (e.g TAILJMPd64) are classified correctly here.
  807. if (!MI.isCandidateForCallSiteEntry())
  808. continue;
  809. // Skip instructions marked as frame setup, as they are not interesting to
  810. // the user.
  811. if (MI.getFlag(MachineInstr::FrameSetup))
  812. continue;
  813. // Check if delay slot support is enabled.
  814. if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
  815. return;
  816. // If this is a direct call, find the callee's subprogram.
  817. // In the case of an indirect call find the register that holds
  818. // the callee.
  819. const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);
  820. if (!CalleeOp.isGlobal() &&
  821. (!CalleeOp.isReg() || !CalleeOp.getReg().isPhysical()))
  822. continue;
  823. unsigned CallReg = 0;
  824. const DISubprogram *CalleeSP = nullptr;
  825. const Function *CalleeDecl = nullptr;
  826. if (CalleeOp.isReg()) {
  827. CallReg = CalleeOp.getReg();
  828. if (!CallReg)
  829. continue;
  830. } else {
  831. CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
  832. if (!CalleeDecl || !CalleeDecl->getSubprogram())
  833. continue;
  834. CalleeSP = CalleeDecl->getSubprogram();
  835. }
  836. // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
  837. bool IsTail = TII->isTailCall(MI);
  838. // If MI is in a bundle, the label was created after the bundle since
  839. // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
  840. // to search for that label below.
  841. const MachineInstr *TopLevelCallMI =
  842. MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
  843. // For non-tail calls, the return PC is needed to disambiguate paths in
  844. // the call graph which could lead to some target function. For tail
  845. // calls, no return PC information is needed, unless tuning for GDB in
  846. // DWARF4 mode in which case we fake a return PC for compatibility.
  847. const MCSymbol *PCAddr =
  848. (!IsTail || CU.useGNUAnalogForDwarf5Feature())
  849. ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
  850. : nullptr;
  851. // For tail calls, it's necessary to record the address of the branch
  852. // instruction so that the debugger can show where the tail call occurred.
  853. const MCSymbol *CallAddr =
  854. IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
  855. assert((IsTail || PCAddr) && "Non-tail call without return PC");
  856. LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
  857. << (CalleeDecl ? CalleeDecl->getName()
  858. : StringRef(MF.getSubtarget()
  859. .getRegisterInfo()
  860. ->getName(CallReg)))
  861. << (IsTail ? " [IsTail]" : "") << "\n");
  862. DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
  863. ScopeDIE, CalleeSP, IsTail, PCAddr, CallAddr, CallReg);
  864. // Optionally emit call-site-param debug info.
  865. if (emitDebugEntryValues()) {
  866. ParamSet Params;
  867. // Try to interpret values of call site parameters.
  868. collectCallSiteParameters(&MI, Params);
  869. CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
  870. }
  871. }
  872. }
  873. }
  874. void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
  875. if (!U.hasDwarfPubSections())
  876. return;
  877. U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
  878. }
  879. void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
  880. DwarfCompileUnit &NewCU) {
  881. DIE &Die = NewCU.getUnitDie();
  882. StringRef FN = DIUnit->getFilename();
  883. StringRef Producer = DIUnit->getProducer();
  884. StringRef Flags = DIUnit->getFlags();
  885. if (!Flags.empty() && !useAppleExtensionAttributes()) {
  886. std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
  887. NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
  888. } else
  889. NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
  890. NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  891. DIUnit->getSourceLanguage());
  892. NewCU.addString(Die, dwarf::DW_AT_name, FN);
  893. StringRef SysRoot = DIUnit->getSysRoot();
  894. if (!SysRoot.empty())
  895. NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
  896. StringRef SDK = DIUnit->getSDK();
  897. if (!SDK.empty())
  898. NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
  899. // Add DW_str_offsets_base to the unit DIE, except for split units.
  900. if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
  901. NewCU.addStringOffsetsStart();
  902. if (!useSplitDwarf()) {
  903. NewCU.initStmtList();
  904. // If we're using split dwarf the compilation dir is going to be in the
  905. // skeleton CU and so we don't need to duplicate it here.
  906. if (!CompilationDir.empty())
  907. NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  908. addGnuPubAttributes(NewCU, Die);
  909. }
  910. if (useAppleExtensionAttributes()) {
  911. if (DIUnit->isOptimized())
  912. NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
  913. StringRef Flags = DIUnit->getFlags();
  914. if (!Flags.empty())
  915. NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
  916. if (unsigned RVer = DIUnit->getRuntimeVersion())
  917. NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
  918. dwarf::DW_FORM_data1, RVer);
  919. }
  920. if (DIUnit->getDWOId()) {
  921. // This CU is either a clang module DWO or a skeleton CU.
  922. NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
  923. DIUnit->getDWOId());
  924. if (!DIUnit->getSplitDebugFilename().empty()) {
  925. // This is a prefabricated skeleton CU.
  926. dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
  927. ? dwarf::DW_AT_dwo_name
  928. : dwarf::DW_AT_GNU_dwo_name;
  929. NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
  930. }
  931. }
  932. }
  933. // Create new DwarfCompileUnit for the given metadata node with tag
  934. // DW_TAG_compile_unit.
  935. DwarfCompileUnit &
  936. DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
  937. if (auto *CU = CUMap.lookup(DIUnit))
  938. return *CU;
  939. CompilationDir = DIUnit->getDirectory();
  940. auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
  941. InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
  942. DwarfCompileUnit &NewCU = *OwnedUnit;
  943. InfoHolder.addUnit(std::move(OwnedUnit));
  944. for (auto *IE : DIUnit->getImportedEntities())
  945. NewCU.addImportedEntity(IE);
  946. // LTO with assembly output shares a single line table amongst multiple CUs.
  947. // To avoid the compilation directory being ambiguous, let the line table
  948. // explicitly describe the directory of all files, never relying on the
  949. // compilation directory.
  950. if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
  951. Asm->OutStreamer->emitDwarfFile0Directive(
  952. CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
  953. DIUnit->getSource(), NewCU.getUniqueID());
  954. if (useSplitDwarf()) {
  955. NewCU.setSkeleton(constructSkeletonCU(NewCU));
  956. NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
  957. } else {
  958. finishUnitAttributes(DIUnit, NewCU);
  959. NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
  960. }
  961. CUMap.insert({DIUnit, &NewCU});
  962. CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
  963. return NewCU;
  964. }
  965. void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
  966. const DIImportedEntity *N) {
  967. if (isa<DILocalScope>(N->getScope()))
  968. return;
  969. if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
  970. D->addChild(TheCU.constructImportedEntityDIE(N));
  971. }
  972. /// Sort and unique GVEs by comparing their fragment offset.
  973. static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
  974. sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
  975. llvm::sort(
  976. GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
  977. // Sort order: first null exprs, then exprs without fragment
  978. // info, then sort by fragment offset in bits.
  979. // FIXME: Come up with a more comprehensive comparator so
  980. // the sorting isn't non-deterministic, and so the following
  981. // std::unique call works correctly.
  982. if (!A.Expr || !B.Expr)
  983. return !!B.Expr;
  984. auto FragmentA = A.Expr->getFragmentInfo();
  985. auto FragmentB = B.Expr->getFragmentInfo();
  986. if (!FragmentA || !FragmentB)
  987. return !!FragmentB;
  988. return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
  989. });
  990. GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
  991. [](DwarfCompileUnit::GlobalExpr A,
  992. DwarfCompileUnit::GlobalExpr B) {
  993. return A.Expr == B.Expr;
  994. }),
  995. GVEs.end());
  996. return GVEs;
  997. }
  998. // Emit all Dwarf sections that should come prior to the content. Create
  999. // global DIEs and emit initial debug info sections. This is invoked by
  1000. // the target AsmPrinter.
  1001. void DwarfDebug::beginModule(Module *M) {
  1002. DebugHandlerBase::beginModule(M);
  1003. if (!Asm || !MMI->hasDebugInfo())
  1004. return;
  1005. unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
  1006. M->debug_compile_units_end());
  1007. assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
  1008. assert(MMI->hasDebugInfo() &&
  1009. "DebugInfoAvailabilty unexpectedly not initialized");
  1010. SingleCU = NumDebugCUs == 1;
  1011. DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
  1012. GVMap;
  1013. for (const GlobalVariable &Global : M->globals()) {
  1014. SmallVector<DIGlobalVariableExpression *, 1> GVs;
  1015. Global.getDebugInfo(GVs);
  1016. for (auto *GVE : GVs)
  1017. GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
  1018. }
  1019. // Create the symbol that designates the start of the unit's contribution
  1020. // to the string offsets table. In a split DWARF scenario, only the skeleton
  1021. // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
  1022. if (useSegmentedStringOffsetsTable())
  1023. (useSplitDwarf() ? SkeletonHolder : InfoHolder)
  1024. .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
  1025. // Create the symbols that designates the start of the DWARF v5 range list
  1026. // and locations list tables. They are located past the table headers.
  1027. if (getDwarfVersion() >= 5) {
  1028. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1029. Holder.setRnglistsTableBaseSym(
  1030. Asm->createTempSymbol("rnglists_table_base"));
  1031. if (useSplitDwarf())
  1032. InfoHolder.setRnglistsTableBaseSym(
  1033. Asm->createTempSymbol("rnglists_dwo_table_base"));
  1034. }
  1035. // Create the symbol that points to the first entry following the debug
  1036. // address table (.debug_addr) header.
  1037. AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
  1038. DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
  1039. for (DICompileUnit *CUNode : M->debug_compile_units()) {
  1040. // FIXME: Move local imported entities into a list attached to the
  1041. // subprogram, then this search won't be needed and a
  1042. // getImportedEntities().empty() test should go below with the rest.
  1043. bool HasNonLocalImportedEntities = llvm::any_of(
  1044. CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
  1045. return !isa<DILocalScope>(IE->getScope());
  1046. });
  1047. if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
  1048. CUNode->getRetainedTypes().empty() &&
  1049. CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
  1050. continue;
  1051. DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
  1052. // Global Variables.
  1053. for (auto *GVE : CUNode->getGlobalVariables()) {
  1054. // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
  1055. // already know about the variable and it isn't adding a constant
  1056. // expression.
  1057. auto &GVMapEntry = GVMap[GVE->getVariable()];
  1058. auto *Expr = GVE->getExpression();
  1059. if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
  1060. GVMapEntry.push_back({nullptr, Expr});
  1061. }
  1062. DenseSet<DIGlobalVariable *> Processed;
  1063. for (auto *GVE : CUNode->getGlobalVariables()) {
  1064. DIGlobalVariable *GV = GVE->getVariable();
  1065. if (Processed.insert(GV).second)
  1066. CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
  1067. }
  1068. for (auto *Ty : CUNode->getEnumTypes())
  1069. CU.getOrCreateTypeDIE(cast<DIType>(Ty));
  1070. for (auto *Ty : CUNode->getRetainedTypes()) {
  1071. // The retained types array by design contains pointers to
  1072. // MDNodes rather than DIRefs. Unique them here.
  1073. if (DIType *RT = dyn_cast<DIType>(Ty))
  1074. // There is no point in force-emitting a forward declaration.
  1075. CU.getOrCreateTypeDIE(RT);
  1076. }
  1077. // Emit imported_modules last so that the relevant context is already
  1078. // available.
  1079. for (auto *IE : CUNode->getImportedEntities())
  1080. constructAndAddImportedEntityDIE(CU, IE);
  1081. }
  1082. }
  1083. void DwarfDebug::finishEntityDefinitions() {
  1084. for (const auto &Entity : ConcreteEntities) {
  1085. DIE *Die = Entity->getDIE();
  1086. assert(Die);
  1087. // FIXME: Consider the time-space tradeoff of just storing the unit pointer
  1088. // in the ConcreteEntities list, rather than looking it up again here.
  1089. // DIE::getUnit isn't simple - it walks parent pointers, etc.
  1090. DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
  1091. assert(Unit);
  1092. Unit->finishEntityDefinition(Entity.get());
  1093. }
  1094. }
  1095. void DwarfDebug::finishSubprogramDefinitions() {
  1096. for (const DISubprogram *SP : ProcessedSPNodes) {
  1097. assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
  1098. forBothCUs(
  1099. getOrCreateDwarfCompileUnit(SP->getUnit()),
  1100. [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
  1101. }
  1102. }
  1103. void DwarfDebug::finalizeModuleInfo() {
  1104. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1105. finishSubprogramDefinitions();
  1106. finishEntityDefinitions();
  1107. // Include the DWO file name in the hash if there's more than one CU.
  1108. // This handles ThinLTO's situation where imported CUs may very easily be
  1109. // duplicate with the same CU partially imported into another ThinLTO unit.
  1110. StringRef DWOName;
  1111. if (CUMap.size() > 1)
  1112. DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
  1113. // Handle anything that needs to be done on a per-unit basis after
  1114. // all other generation.
  1115. for (const auto &P : CUMap) {
  1116. auto &TheCU = *P.second;
  1117. if (TheCU.getCUNode()->isDebugDirectivesOnly())
  1118. continue;
  1119. // Emit DW_AT_containing_type attribute to connect types with their
  1120. // vtable holding type.
  1121. TheCU.constructContainingTypeDIEs();
  1122. // Add CU specific attributes if we need to add any.
  1123. // If we're splitting the dwarf out now that we've got the entire
  1124. // CU then add the dwo id to it.
  1125. auto *SkCU = TheCU.getSkeleton();
  1126. bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
  1127. if (HasSplitUnit) {
  1128. dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
  1129. ? dwarf::DW_AT_dwo_name
  1130. : dwarf::DW_AT_GNU_dwo_name;
  1131. finishUnitAttributes(TheCU.getCUNode(), TheCU);
  1132. TheCU.addString(TheCU.getUnitDie(), attrDWOName,
  1133. Asm->TM.Options.MCOptions.SplitDwarfFile);
  1134. SkCU->addString(SkCU->getUnitDie(), attrDWOName,
  1135. Asm->TM.Options.MCOptions.SplitDwarfFile);
  1136. // Emit a unique identifier for this CU.
  1137. uint64_t ID =
  1138. DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
  1139. if (getDwarfVersion() >= 5) {
  1140. TheCU.setDWOId(ID);
  1141. SkCU->setDWOId(ID);
  1142. } else {
  1143. TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  1144. dwarf::DW_FORM_data8, ID);
  1145. SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  1146. dwarf::DW_FORM_data8, ID);
  1147. }
  1148. if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
  1149. const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
  1150. SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
  1151. Sym, Sym);
  1152. }
  1153. } else if (SkCU) {
  1154. finishUnitAttributes(SkCU->getCUNode(), *SkCU);
  1155. }
  1156. // If we have code split among multiple sections or non-contiguous
  1157. // ranges of code then emit a DW_AT_ranges attribute on the unit that will
  1158. // remain in the .o file, otherwise add a DW_AT_low_pc.
  1159. // FIXME: We should use ranges allow reordering of code ala
  1160. // .subsections_via_symbols in mach-o. This would mean turning on
  1161. // ranges for all subprogram DIEs for mach-o.
  1162. DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
  1163. if (unsigned NumRanges = TheCU.getRanges().size()) {
  1164. if (NumRanges > 1 && useRangesSection())
  1165. // A DW_AT_low_pc attribute may also be specified in combination with
  1166. // DW_AT_ranges to specify the default base address for use in
  1167. // location lists (see Section 2.6.2) and range lists (see Section
  1168. // 2.17.3).
  1169. U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
  1170. else
  1171. U.setBaseAddress(TheCU.getRanges().front().Begin);
  1172. U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
  1173. }
  1174. // We don't keep track of which addresses are used in which CU so this
  1175. // is a bit pessimistic under LTO.
  1176. if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
  1177. U.addAddrTableBase();
  1178. if (getDwarfVersion() >= 5) {
  1179. if (U.hasRangeLists())
  1180. U.addRnglistsBase();
  1181. if (!DebugLocs.getLists().empty()) {
  1182. if (!useSplitDwarf())
  1183. U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
  1184. DebugLocs.getSym(),
  1185. TLOF.getDwarfLoclistsSection()->getBeginSymbol());
  1186. }
  1187. }
  1188. auto *CUNode = cast<DICompileUnit>(P.first);
  1189. // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
  1190. // attribute.
  1191. if (CUNode->getMacros()) {
  1192. if (UseDebugMacroSection) {
  1193. if (useSplitDwarf())
  1194. TheCU.addSectionDelta(
  1195. TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
  1196. TLOF.getDwarfMacroDWOSection()->getBeginSymbol());
  1197. else {
  1198. dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
  1199. ? dwarf::DW_AT_macros
  1200. : dwarf::DW_AT_GNU_macros;
  1201. U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
  1202. TLOF.getDwarfMacroSection()->getBeginSymbol());
  1203. }
  1204. } else {
  1205. if (useSplitDwarf())
  1206. TheCU.addSectionDelta(
  1207. TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
  1208. U.getMacroLabelBegin(),
  1209. TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
  1210. else
  1211. U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
  1212. U.getMacroLabelBegin(),
  1213. TLOF.getDwarfMacinfoSection()->getBeginSymbol());
  1214. }
  1215. }
  1216. }
  1217. // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
  1218. for (auto *CUNode : MMI->getModule()->debug_compile_units())
  1219. if (CUNode->getDWOId())
  1220. getOrCreateDwarfCompileUnit(CUNode);
  1221. // Compute DIE offsets and sizes.
  1222. InfoHolder.computeSizeAndOffsets();
  1223. if (useSplitDwarf())
  1224. SkeletonHolder.computeSizeAndOffsets();
  1225. }
  1226. // Emit all Dwarf sections that should come after the content.
  1227. void DwarfDebug::endModule() {
  1228. // Terminate the pending line table.
  1229. if (PrevCU)
  1230. terminateLineTable(PrevCU);
  1231. PrevCU = nullptr;
  1232. assert(CurFn == nullptr);
  1233. assert(CurMI == nullptr);
  1234. for (const auto &P : CUMap) {
  1235. auto &CU = *P.second;
  1236. CU.createBaseTypeDIEs();
  1237. }
  1238. // If we aren't actually generating debug info (check beginModule -
  1239. // conditionalized on the presence of the llvm.dbg.cu metadata node)
  1240. if (!Asm || !MMI->hasDebugInfo())
  1241. return;
  1242. // Finalize the debug info for the module.
  1243. finalizeModuleInfo();
  1244. if (useSplitDwarf())
  1245. // Emit debug_loc.dwo/debug_loclists.dwo section.
  1246. emitDebugLocDWO();
  1247. else
  1248. // Emit debug_loc/debug_loclists section.
  1249. emitDebugLoc();
  1250. // Corresponding abbreviations into a abbrev section.
  1251. emitAbbreviations();
  1252. // Emit all the DIEs into a debug info section.
  1253. emitDebugInfo();
  1254. // Emit info into a debug aranges section.
  1255. if (GenerateARangeSection)
  1256. emitDebugARanges();
  1257. // Emit info into a debug ranges section.
  1258. emitDebugRanges();
  1259. if (useSplitDwarf())
  1260. // Emit info into a debug macinfo.dwo section.
  1261. emitDebugMacinfoDWO();
  1262. else
  1263. // Emit info into a debug macinfo/macro section.
  1264. emitDebugMacinfo();
  1265. emitDebugStr();
  1266. if (useSplitDwarf()) {
  1267. emitDebugStrDWO();
  1268. emitDebugInfoDWO();
  1269. emitDebugAbbrevDWO();
  1270. emitDebugLineDWO();
  1271. emitDebugRangesDWO();
  1272. }
  1273. emitDebugAddr();
  1274. // Emit info into the dwarf accelerator table sections.
  1275. switch (getAccelTableKind()) {
  1276. case AccelTableKind::Apple:
  1277. emitAccelNames();
  1278. emitAccelObjC();
  1279. emitAccelNamespaces();
  1280. emitAccelTypes();
  1281. break;
  1282. case AccelTableKind::Dwarf:
  1283. emitAccelDebugNames();
  1284. break;
  1285. case AccelTableKind::None:
  1286. break;
  1287. case AccelTableKind::Default:
  1288. llvm_unreachable("Default should have already been resolved.");
  1289. }
  1290. // Emit the pubnames and pubtypes sections if requested.
  1291. emitDebugPubSections();
  1292. // clean up.
  1293. // FIXME: AbstractVariables.clear();
  1294. }
  1295. void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
  1296. const DINode *Node,
  1297. const MDNode *ScopeNode) {
  1298. if (CU.getExistingAbstractEntity(Node))
  1299. return;
  1300. CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
  1301. cast<DILocalScope>(ScopeNode)));
  1302. }
  1303. void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
  1304. const DINode *Node, const MDNode *ScopeNode) {
  1305. if (CU.getExistingAbstractEntity(Node))
  1306. return;
  1307. if (LexicalScope *Scope =
  1308. LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
  1309. CU.createAbstractEntity(Node, Scope);
  1310. }
  1311. // Collect variable information from side table maintained by MF.
  1312. void DwarfDebug::collectVariableInfoFromMFTable(
  1313. DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
  1314. SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
  1315. LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
  1316. for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
  1317. if (!VI.Var)
  1318. continue;
  1319. assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
  1320. "Expected inlined-at fields to agree");
  1321. InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
  1322. Processed.insert(Var);
  1323. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  1324. // If variable scope is not found then skip this variable.
  1325. if (!Scope) {
  1326. LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
  1327. << ", no variable scope found\n");
  1328. continue;
  1329. }
  1330. ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
  1331. auto RegVar = std::make_unique<DbgVariable>(
  1332. cast<DILocalVariable>(Var.first), Var.second);
  1333. RegVar->initializeMMI(VI.Expr, VI.Slot);
  1334. LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
  1335. << "\n");
  1336. if (DbgVariable *DbgVar = MFVars.lookup(Var))
  1337. DbgVar->addMMIEntry(*RegVar);
  1338. else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
  1339. MFVars.insert({Var, RegVar.get()});
  1340. ConcreteEntities.push_back(std::move(RegVar));
  1341. }
  1342. }
  1343. }
  1344. /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
  1345. /// enclosing lexical scope. The check ensures there are no other instructions
  1346. /// in the same lexical scope preceding the DBG_VALUE and that its range is
  1347. /// either open or otherwise rolls off the end of the scope.
  1348. static bool validThroughout(LexicalScopes &LScopes,
  1349. const MachineInstr *DbgValue,
  1350. const MachineInstr *RangeEnd,
  1351. const InstructionOrdering &Ordering) {
  1352. assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
  1353. auto MBB = DbgValue->getParent();
  1354. auto DL = DbgValue->getDebugLoc();
  1355. auto *LScope = LScopes.findLexicalScope(DL);
  1356. // Scope doesn't exist; this is a dead DBG_VALUE.
  1357. if (!LScope)
  1358. return false;
  1359. auto &LSRange = LScope->getRanges();
  1360. if (LSRange.size() == 0)
  1361. return false;
  1362. const MachineInstr *LScopeBegin = LSRange.front().first;
  1363. // If the scope starts before the DBG_VALUE then we may have a negative
  1364. // result. Otherwise the location is live coming into the scope and we
  1365. // can skip the following checks.
  1366. if (!Ordering.isBefore(DbgValue, LScopeBegin)) {
  1367. // Exit if the lexical scope begins outside of the current block.
  1368. if (LScopeBegin->getParent() != MBB)
  1369. return false;
  1370. MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
  1371. for (++Pred; Pred != MBB->rend(); ++Pred) {
  1372. if (Pred->getFlag(MachineInstr::FrameSetup))
  1373. break;
  1374. auto PredDL = Pred->getDebugLoc();
  1375. if (!PredDL || Pred->isMetaInstruction())
  1376. continue;
  1377. // Check whether the instruction preceding the DBG_VALUE is in the same
  1378. // (sub)scope as the DBG_VALUE.
  1379. if (DL->getScope() == PredDL->getScope())
  1380. return false;
  1381. auto *PredScope = LScopes.findLexicalScope(PredDL);
  1382. if (!PredScope || LScope->dominates(PredScope))
  1383. return false;
  1384. }
  1385. }
  1386. // If the range of the DBG_VALUE is open-ended, report success.
  1387. if (!RangeEnd)
  1388. return true;
  1389. // Single, constant DBG_VALUEs in the prologue are promoted to be live
  1390. // throughout the function. This is a hack, presumably for DWARF v2 and not
  1391. // necessarily correct. It would be much better to use a dbg.declare instead
  1392. // if we know the constant is live throughout the scope.
  1393. if (MBB->pred_empty() &&
  1394. all_of(DbgValue->debug_operands(),
  1395. [](const MachineOperand &Op) { return Op.isImm(); }))
  1396. return true;
  1397. // Test if the location terminates before the end of the scope.
  1398. const MachineInstr *LScopeEnd = LSRange.back().second;
  1399. if (Ordering.isBefore(RangeEnd, LScopeEnd))
  1400. return false;
  1401. // There's a single location which starts at the scope start, and ends at or
  1402. // after the scope end.
  1403. return true;
  1404. }
  1405. /// Build the location list for all DBG_VALUEs in the function that
  1406. /// describe the same variable. The resulting DebugLocEntries will have
  1407. /// strict monotonically increasing begin addresses and will never
  1408. /// overlap. If the resulting list has only one entry that is valid
  1409. /// throughout variable's scope return true.
  1410. //
  1411. // See the definition of DbgValueHistoryMap::Entry for an explanation of the
  1412. // different kinds of history map entries. One thing to be aware of is that if
  1413. // a debug value is ended by another entry (rather than being valid until the
  1414. // end of the function), that entry's instruction may or may not be included in
  1415. // the range, depending on if the entry is a clobbering entry (it has an
  1416. // instruction that clobbers one or more preceding locations), or if it is an
  1417. // (overlapping) debug value entry. This distinction can be seen in the example
  1418. // below. The first debug value is ended by the clobbering entry 2, and the
  1419. // second and third debug values are ended by the overlapping debug value entry
  1420. // 4.
  1421. //
  1422. // Input:
  1423. //
  1424. // History map entries [type, end index, mi]
  1425. //
  1426. // 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
  1427. // 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
  1428. // 2 | | [Clobber, $reg0 = [...], -, -]
  1429. // 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
  1430. // 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
  1431. //
  1432. // Output [start, end) [Value...]:
  1433. //
  1434. // [0-1) [(reg0, fragment 0, 32)]
  1435. // [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
  1436. // [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
  1437. // [4-) [(@g, fragment 0, 96)]
  1438. bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
  1439. const DbgValueHistoryMap::Entries &Entries) {
  1440. using OpenRange =
  1441. std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
  1442. SmallVector<OpenRange, 4> OpenRanges;
  1443. bool isSafeForSingleLocation = true;
  1444. const MachineInstr *StartDebugMI = nullptr;
  1445. const MachineInstr *EndMI = nullptr;
  1446. for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
  1447. const MachineInstr *Instr = EI->getInstr();
  1448. // Remove all values that are no longer live.
  1449. size_t Index = std::distance(EB, EI);
  1450. erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
  1451. // If we are dealing with a clobbering entry, this iteration will result in
  1452. // a location list entry starting after the clobbering instruction.
  1453. const MCSymbol *StartLabel =
  1454. EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
  1455. assert(StartLabel &&
  1456. "Forgot label before/after instruction starting a range!");
  1457. const MCSymbol *EndLabel;
  1458. if (std::next(EI) == Entries.end()) {
  1459. const MachineBasicBlock &EndMBB = Asm->MF->back();
  1460. EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionIDNum()].EndLabel;
  1461. if (EI->isClobber())
  1462. EndMI = EI->getInstr();
  1463. }
  1464. else if (std::next(EI)->isClobber())
  1465. EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
  1466. else
  1467. EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
  1468. assert(EndLabel && "Forgot label after instruction ending a range!");
  1469. if (EI->isDbgValue())
  1470. LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
  1471. // If this history map entry has a debug value, add that to the list of
  1472. // open ranges and check if its location is valid for a single value
  1473. // location.
  1474. if (EI->isDbgValue()) {
  1475. // Do not add undef debug values, as they are redundant information in
  1476. // the location list entries. An undef debug results in an empty location
  1477. // description. If there are any non-undef fragments then padding pieces
  1478. // with empty location descriptions will automatically be inserted, and if
  1479. // all fragments are undef then the whole location list entry is
  1480. // redundant.
  1481. if (!Instr->isUndefDebugValue()) {
  1482. auto Value = getDebugLocValue(Instr);
  1483. OpenRanges.emplace_back(EI->getEndIndex(), Value);
  1484. // TODO: Add support for single value fragment locations.
  1485. if (Instr->getDebugExpression()->isFragment())
  1486. isSafeForSingleLocation = false;
  1487. if (!StartDebugMI)
  1488. StartDebugMI = Instr;
  1489. } else {
  1490. isSafeForSingleLocation = false;
  1491. }
  1492. }
  1493. // Location list entries with empty location descriptions are redundant
  1494. // information in DWARF, so do not emit those.
  1495. if (OpenRanges.empty())
  1496. continue;
  1497. // Omit entries with empty ranges as they do not have any effect in DWARF.
  1498. if (StartLabel == EndLabel) {
  1499. LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
  1500. continue;
  1501. }
  1502. SmallVector<DbgValueLoc, 4> Values;
  1503. for (auto &R : OpenRanges)
  1504. Values.push_back(R.second);
  1505. // With Basic block sections, it is posssible that the StartLabel and the
  1506. // Instr are not in the same section. This happens when the StartLabel is
  1507. // the function begin label and the dbg value appears in a basic block
  1508. // that is not the entry. In this case, the range needs to be split to
  1509. // span each individual section in the range from StartLabel to EndLabel.
  1510. if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&
  1511. !Instr->getParent()->sameSection(&Asm->MF->front())) {
  1512. const MCSymbol *BeginSectionLabel = StartLabel;
  1513. for (const MachineBasicBlock &MBB : *Asm->MF) {
  1514. if (MBB.isBeginSection() && &MBB != &Asm->MF->front())
  1515. BeginSectionLabel = MBB.getSymbol();
  1516. if (MBB.sameSection(Instr->getParent())) {
  1517. DebugLoc.emplace_back(BeginSectionLabel, EndLabel, Values);
  1518. break;
  1519. }
  1520. if (MBB.isEndSection())
  1521. DebugLoc.emplace_back(BeginSectionLabel, MBB.getEndSymbol(), Values);
  1522. }
  1523. } else {
  1524. DebugLoc.emplace_back(StartLabel, EndLabel, Values);
  1525. }
  1526. // Attempt to coalesce the ranges of two otherwise identical
  1527. // DebugLocEntries.
  1528. auto CurEntry = DebugLoc.rbegin();
  1529. LLVM_DEBUG({
  1530. dbgs() << CurEntry->getValues().size() << " Values:\n";
  1531. for (auto &Value : CurEntry->getValues())
  1532. Value.dump();
  1533. dbgs() << "-----\n";
  1534. });
  1535. auto PrevEntry = std::next(CurEntry);
  1536. if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
  1537. DebugLoc.pop_back();
  1538. }
  1539. if (!isSafeForSingleLocation ||
  1540. !validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()))
  1541. return false;
  1542. if (DebugLoc.size() == 1)
  1543. return true;
  1544. if (!Asm->MF->hasBBSections())
  1545. return false;
  1546. // Check here to see if loclist can be merged into a single range. If not,
  1547. // we must keep the split loclists per section. This does exactly what
  1548. // MergeRanges does without sections. We don't actually merge the ranges
  1549. // as the split ranges must be kept intact if this cannot be collapsed
  1550. // into a single range.
  1551. const MachineBasicBlock *RangeMBB = nullptr;
  1552. if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())
  1553. RangeMBB = &Asm->MF->front();
  1554. else
  1555. RangeMBB = Entries.begin()->getInstr()->getParent();
  1556. auto *CurEntry = DebugLoc.begin();
  1557. auto *NextEntry = std::next(CurEntry);
  1558. while (NextEntry != DebugLoc.end()) {
  1559. // Get the last machine basic block of this section.
  1560. while (!RangeMBB->isEndSection())
  1561. RangeMBB = RangeMBB->getNextNode();
  1562. if (!RangeMBB->getNextNode())
  1563. return false;
  1564. // CurEntry should end the current section and NextEntry should start
  1565. // the next section and the Values must match for these two ranges to be
  1566. // merged.
  1567. if (CurEntry->getEndSym() != RangeMBB->getEndSymbol() ||
  1568. NextEntry->getBeginSym() != RangeMBB->getNextNode()->getSymbol() ||
  1569. CurEntry->getValues() != NextEntry->getValues())
  1570. return false;
  1571. RangeMBB = RangeMBB->getNextNode();
  1572. CurEntry = NextEntry;
  1573. NextEntry = std::next(CurEntry);
  1574. }
  1575. return true;
  1576. }
  1577. DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
  1578. LexicalScope &Scope,
  1579. const DINode *Node,
  1580. const DILocation *Location,
  1581. const MCSymbol *Sym) {
  1582. ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
  1583. if (isa<const DILocalVariable>(Node)) {
  1584. ConcreteEntities.push_back(
  1585. std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
  1586. Location));
  1587. InfoHolder.addScopeVariable(&Scope,
  1588. cast<DbgVariable>(ConcreteEntities.back().get()));
  1589. } else if (isa<const DILabel>(Node)) {
  1590. ConcreteEntities.push_back(
  1591. std::make_unique<DbgLabel>(cast<const DILabel>(Node),
  1592. Location, Sym));
  1593. InfoHolder.addScopeLabel(&Scope,
  1594. cast<DbgLabel>(ConcreteEntities.back().get()));
  1595. }
  1596. return ConcreteEntities.back().get();
  1597. }
  1598. // Find variables for each lexical scope.
  1599. void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
  1600. const DISubprogram *SP,
  1601. DenseSet<InlinedEntity> &Processed) {
  1602. // Grab the variable info that was squirreled away in the MMI side-table.
  1603. collectVariableInfoFromMFTable(TheCU, Processed);
  1604. for (const auto &I : DbgValues) {
  1605. InlinedEntity IV = I.first;
  1606. if (Processed.count(IV))
  1607. continue;
  1608. // Instruction ranges, specifying where IV is accessible.
  1609. const auto &HistoryMapEntries = I.second;
  1610. // Try to find any non-empty variable location. Do not create a concrete
  1611. // entity if there are no locations.
  1612. if (!DbgValues.hasNonEmptyLocation(HistoryMapEntries))
  1613. continue;
  1614. LexicalScope *Scope = nullptr;
  1615. const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
  1616. if (const DILocation *IA = IV.second)
  1617. Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
  1618. else
  1619. Scope = LScopes.findLexicalScope(LocalVar->getScope());
  1620. // If variable scope is not found then skip this variable.
  1621. if (!Scope)
  1622. continue;
  1623. Processed.insert(IV);
  1624. DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
  1625. *Scope, LocalVar, IV.second));
  1626. const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
  1627. assert(MInsn->isDebugValue() && "History must begin with debug value");
  1628. // Check if there is a single DBG_VALUE, valid throughout the var's scope.
  1629. // If the history map contains a single debug value, there may be an
  1630. // additional entry which clobbers the debug value.
  1631. size_t HistSize = HistoryMapEntries.size();
  1632. bool SingleValueWithClobber =
  1633. HistSize == 2 && HistoryMapEntries[1].isClobber();
  1634. if (HistSize == 1 || SingleValueWithClobber) {
  1635. const auto *End =
  1636. SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
  1637. if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {
  1638. RegVar->initializeDbgValue(MInsn);
  1639. continue;
  1640. }
  1641. }
  1642. // Do not emit location lists if .debug_loc secton is disabled.
  1643. if (!useLocSection())
  1644. continue;
  1645. // Handle multiple DBG_VALUE instructions describing one variable.
  1646. DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
  1647. // Build the location list for this variable.
  1648. SmallVector<DebugLocEntry, 8> Entries;
  1649. bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
  1650. // Check whether buildLocationList managed to merge all locations to one
  1651. // that is valid throughout the variable's scope. If so, produce single
  1652. // value location.
  1653. if (isValidSingleLocation) {
  1654. RegVar->initializeDbgValue(Entries[0].getValues()[0]);
  1655. continue;
  1656. }
  1657. // If the variable has a DIBasicType, extract it. Basic types cannot have
  1658. // unique identifiers, so don't bother resolving the type with the
  1659. // identifier map.
  1660. const DIBasicType *BT = dyn_cast<DIBasicType>(
  1661. static_cast<const Metadata *>(LocalVar->getType()));
  1662. // Finalize the entry by lowering it into a DWARF bytestream.
  1663. for (auto &Entry : Entries)
  1664. Entry.finalize(*Asm, List, BT, TheCU);
  1665. }
  1666. // For each InlinedEntity collected from DBG_LABEL instructions, convert to
  1667. // DWARF-related DbgLabel.
  1668. for (const auto &I : DbgLabels) {
  1669. InlinedEntity IL = I.first;
  1670. const MachineInstr *MI = I.second;
  1671. if (MI == nullptr)
  1672. continue;
  1673. LexicalScope *Scope = nullptr;
  1674. const DILabel *Label = cast<DILabel>(IL.first);
  1675. // The scope could have an extra lexical block file.
  1676. const DILocalScope *LocalScope =
  1677. Label->getScope()->getNonLexicalBlockFileScope();
  1678. // Get inlined DILocation if it is inlined label.
  1679. if (const DILocation *IA = IL.second)
  1680. Scope = LScopes.findInlinedScope(LocalScope, IA);
  1681. else
  1682. Scope = LScopes.findLexicalScope(LocalScope);
  1683. // If label scope is not found then skip this label.
  1684. if (!Scope)
  1685. continue;
  1686. Processed.insert(IL);
  1687. /// At this point, the temporary label is created.
  1688. /// Save the temporary label to DbgLabel entity to get the
  1689. /// actually address when generating Dwarf DIE.
  1690. MCSymbol *Sym = getLabelBeforeInsn(MI);
  1691. createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
  1692. }
  1693. // Collect info for variables/labels that were optimized out.
  1694. for (const DINode *DN : SP->getRetainedNodes()) {
  1695. if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
  1696. continue;
  1697. LexicalScope *Scope = nullptr;
  1698. if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
  1699. Scope = LScopes.findLexicalScope(DV->getScope());
  1700. } else if (auto *DL = dyn_cast<DILabel>(DN)) {
  1701. Scope = LScopes.findLexicalScope(DL->getScope());
  1702. }
  1703. if (Scope)
  1704. createConcreteEntity(TheCU, *Scope, DN, nullptr);
  1705. }
  1706. }
  1707. // Process beginning of an instruction.
  1708. void DwarfDebug::beginInstruction(const MachineInstr *MI) {
  1709. const MachineFunction &MF = *MI->getMF();
  1710. const auto *SP = MF.getFunction().getSubprogram();
  1711. bool NoDebug =
  1712. !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
  1713. // Delay slot support check.
  1714. auto delaySlotSupported = [](const MachineInstr &MI) {
  1715. if (!MI.isBundledWithSucc())
  1716. return false;
  1717. auto Suc = std::next(MI.getIterator());
  1718. (void)Suc;
  1719. // Ensure that delay slot instruction is successor of the call instruction.
  1720. // Ex. CALL_INSTRUCTION {
  1721. // DELAY_SLOT_INSTRUCTION }
  1722. assert(Suc->isBundledWithPred() &&
  1723. "Call bundle instructions are out of order");
  1724. return true;
  1725. };
  1726. // When describing calls, we need a label for the call instruction.
  1727. if (!NoDebug && SP->areAllCallsDescribed() &&
  1728. MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
  1729. (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
  1730. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  1731. bool IsTail = TII->isTailCall(*MI);
  1732. // For tail calls, we need the address of the branch instruction for
  1733. // DW_AT_call_pc.
  1734. if (IsTail)
  1735. requestLabelBeforeInsn(MI);
  1736. // For non-tail calls, we need the return address for the call for
  1737. // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
  1738. // tail calls as well.
  1739. requestLabelAfterInsn(MI);
  1740. }
  1741. DebugHandlerBase::beginInstruction(MI);
  1742. if (!CurMI)
  1743. return;
  1744. if (NoDebug)
  1745. return;
  1746. // Check if source location changes, but ignore DBG_VALUE and CFI locations.
  1747. // If the instruction is part of the function frame setup code, do not emit
  1748. // any line record, as there is no correspondence with any user code.
  1749. if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
  1750. return;
  1751. const DebugLoc &DL = MI->getDebugLoc();
  1752. unsigned Flags = 0;
  1753. if (MI->getFlag(MachineInstr::FrameDestroy) && DL) {
  1754. const MachineBasicBlock *MBB = MI->getParent();
  1755. if (MBB && (MBB != EpilogBeginBlock)) {
  1756. // First time FrameDestroy has been seen in this basic block
  1757. EpilogBeginBlock = MBB;
  1758. Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
  1759. }
  1760. }
  1761. // When we emit a line-0 record, we don't update PrevInstLoc; so look at
  1762. // the last line number actually emitted, to see if it was line 0.
  1763. unsigned LastAsmLine =
  1764. Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
  1765. if (DL == PrevInstLoc) {
  1766. // If we have an ongoing unspecified location, nothing to do here.
  1767. if (!DL)
  1768. return;
  1769. // We have an explicit location, same as the previous location.
  1770. // But we might be coming back to it after a line 0 record.
  1771. if ((LastAsmLine == 0 && DL.getLine() != 0) || Flags) {
  1772. // Reinstate the source location but not marked as a statement.
  1773. const MDNode *Scope = DL.getScope();
  1774. recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
  1775. }
  1776. return;
  1777. }
  1778. if (!DL) {
  1779. // We have an unspecified location, which might want to be line 0.
  1780. // If we have already emitted a line-0 record, don't repeat it.
  1781. if (LastAsmLine == 0)
  1782. return;
  1783. // If user said Don't Do That, don't do that.
  1784. if (UnknownLocations == Disable)
  1785. return;
  1786. // See if we have a reason to emit a line-0 record now.
  1787. // Reasons to emit a line-0 record include:
  1788. // - User asked for it (UnknownLocations).
  1789. // - Instruction has a label, so it's referenced from somewhere else,
  1790. // possibly debug information; we want it to have a source location.
  1791. // - Instruction is at the top of a block; we don't want to inherit the
  1792. // location from the physically previous (maybe unrelated) block.
  1793. if (UnknownLocations == Enable || PrevLabel ||
  1794. (PrevInstBB && PrevInstBB != MI->getParent())) {
  1795. // Preserve the file and column numbers, if we can, to save space in
  1796. // the encoded line table.
  1797. // Do not update PrevInstLoc, it remembers the last non-0 line.
  1798. const MDNode *Scope = nullptr;
  1799. unsigned Column = 0;
  1800. if (PrevInstLoc) {
  1801. Scope = PrevInstLoc.getScope();
  1802. Column = PrevInstLoc.getCol();
  1803. }
  1804. recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
  1805. }
  1806. return;
  1807. }
  1808. // We have an explicit location, different from the previous location.
  1809. // Don't repeat a line-0 record, but otherwise emit the new location.
  1810. // (The new location might be an explicit line 0, which we do emit.)
  1811. if (DL.getLine() == 0 && LastAsmLine == 0)
  1812. return;
  1813. if (DL == PrologEndLoc) {
  1814. Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
  1815. PrologEndLoc = DebugLoc();
  1816. }
  1817. // If the line changed, we call that a new statement; unless we went to
  1818. // line 0 and came back, in which case it is not a new statement.
  1819. unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
  1820. if (DL.getLine() && DL.getLine() != OldLine)
  1821. Flags |= DWARF2_FLAG_IS_STMT;
  1822. const MDNode *Scope = DL.getScope();
  1823. recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
  1824. // If we're not at line 0, remember this location.
  1825. if (DL.getLine())
  1826. PrevInstLoc = DL;
  1827. }
  1828. static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
  1829. // First known non-DBG_VALUE and non-frame setup location marks
  1830. // the beginning of the function body.
  1831. DebugLoc LineZeroLoc;
  1832. for (const auto &MBB : *MF) {
  1833. for (const auto &MI : MBB) {
  1834. if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
  1835. MI.getDebugLoc()) {
  1836. // Scan forward to try to find a non-zero line number. The prologue_end
  1837. // marks the first breakpoint in the function after the frame setup, and
  1838. // a compiler-generated line 0 location is not a meaningful breakpoint.
  1839. // If none is found, return the first location after the frame setup.
  1840. if (MI.getDebugLoc().getLine())
  1841. return MI.getDebugLoc();
  1842. LineZeroLoc = MI.getDebugLoc();
  1843. }
  1844. }
  1845. }
  1846. return LineZeroLoc;
  1847. }
  1848. /// Register a source line with debug info. Returns the unique label that was
  1849. /// emitted and which provides correspondence to the source line list.
  1850. static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
  1851. const MDNode *S, unsigned Flags, unsigned CUID,
  1852. uint16_t DwarfVersion,
  1853. ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
  1854. StringRef Fn;
  1855. unsigned FileNo = 1;
  1856. unsigned Discriminator = 0;
  1857. if (auto *Scope = cast_or_null<DIScope>(S)) {
  1858. Fn = Scope->getFilename();
  1859. if (Line != 0 && DwarfVersion >= 4)
  1860. if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
  1861. Discriminator = LBF->getDiscriminator();
  1862. FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
  1863. .getOrCreateSourceID(Scope->getFile());
  1864. }
  1865. Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
  1866. Discriminator, Fn);
  1867. }
  1868. DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
  1869. unsigned CUID) {
  1870. // Get beginning of function.
  1871. if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
  1872. // Ensure the compile unit is created if the function is called before
  1873. // beginFunction().
  1874. (void)getOrCreateDwarfCompileUnit(
  1875. MF.getFunction().getSubprogram()->getUnit());
  1876. // We'd like to list the prologue as "not statements" but GDB behaves
  1877. // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
  1878. const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
  1879. ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
  1880. CUID, getDwarfVersion(), getUnits());
  1881. return PrologEndLoc;
  1882. }
  1883. return DebugLoc();
  1884. }
  1885. // Gather pre-function debug information. Assumes being called immediately
  1886. // after the function entry point has been emitted.
  1887. void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
  1888. CurFn = MF;
  1889. auto *SP = MF->getFunction().getSubprogram();
  1890. assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
  1891. if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
  1892. return;
  1893. DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
  1894. Asm->OutStreamer->getContext().setDwarfCompileUnitID(
  1895. getDwarfCompileUnitIDForLineTable(CU));
  1896. // Record beginning of function.
  1897. PrologEndLoc = emitInitialLocDirective(
  1898. *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
  1899. }
  1900. unsigned
  1901. DwarfDebug::getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU) {
  1902. // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
  1903. // belongs to so that we add to the correct per-cu line table in the
  1904. // non-asm case.
  1905. if (Asm->OutStreamer->hasRawTextSupport())
  1906. // Use a single line table if we are generating assembly.
  1907. return 0;
  1908. else
  1909. return CU.getUniqueID();
  1910. }
  1911. void DwarfDebug::terminateLineTable(const DwarfCompileUnit *CU) {
  1912. const auto &CURanges = CU->getRanges();
  1913. auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(
  1914. getDwarfCompileUnitIDForLineTable(*CU));
  1915. // Add the last range label for the given CU.
  1916. LineTable.getMCLineSections().addEndEntry(
  1917. const_cast<MCSymbol *>(CURanges.back().End));
  1918. }
  1919. void DwarfDebug::skippedNonDebugFunction() {
  1920. // If we don't have a subprogram for this function then there will be a hole
  1921. // in the range information. Keep note of this by setting the previously used
  1922. // section to nullptr.
  1923. // Terminate the pending line table.
  1924. if (PrevCU)
  1925. terminateLineTable(PrevCU);
  1926. PrevCU = nullptr;
  1927. CurFn = nullptr;
  1928. }
  1929. // Gather and emit post-function debug information.
  1930. void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
  1931. const DISubprogram *SP = MF->getFunction().getSubprogram();
  1932. assert(CurFn == MF &&
  1933. "endFunction should be called with the same function as beginFunction");
  1934. // Set DwarfDwarfCompileUnitID in MCContext to default value.
  1935. Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
  1936. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  1937. assert(!FnScope || SP == FnScope->getScopeNode());
  1938. DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
  1939. if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
  1940. PrevLabel = nullptr;
  1941. CurFn = nullptr;
  1942. return;
  1943. }
  1944. DenseSet<InlinedEntity> Processed;
  1945. collectEntityInfo(TheCU, SP, Processed);
  1946. // Add the range of this function to the list of ranges for the CU.
  1947. // With basic block sections, add ranges for all basic block sections.
  1948. for (const auto &R : Asm->MBBSectionRanges)
  1949. TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
  1950. // Under -gmlt, skip building the subprogram if there are no inlined
  1951. // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
  1952. // is still needed as we need its source location.
  1953. if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
  1954. TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
  1955. LScopes.getAbstractScopesList().empty() && !IsDarwin) {
  1956. assert(InfoHolder.getScopeVariables().empty());
  1957. PrevLabel = nullptr;
  1958. CurFn = nullptr;
  1959. return;
  1960. }
  1961. #ifndef NDEBUG
  1962. size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
  1963. #endif
  1964. // Construct abstract scopes.
  1965. for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
  1966. const auto *SP = cast<DISubprogram>(AScope->getScopeNode());
  1967. for (const DINode *DN : SP->getRetainedNodes()) {
  1968. if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
  1969. continue;
  1970. const MDNode *Scope = nullptr;
  1971. if (auto *DV = dyn_cast<DILocalVariable>(DN))
  1972. Scope = DV->getScope();
  1973. else if (auto *DL = dyn_cast<DILabel>(DN))
  1974. Scope = DL->getScope();
  1975. else
  1976. llvm_unreachable("Unexpected DI type!");
  1977. // Collect info for variables/labels that were optimized out.
  1978. ensureAbstractEntityIsCreated(TheCU, DN, Scope);
  1979. assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
  1980. && "ensureAbstractEntityIsCreated inserted abstract scopes");
  1981. }
  1982. constructAbstractSubprogramScopeDIE(TheCU, AScope);
  1983. }
  1984. ProcessedSPNodes.insert(SP);
  1985. DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
  1986. if (auto *SkelCU = TheCU.getSkeleton())
  1987. if (!LScopes.getAbstractScopesList().empty() &&
  1988. TheCU.getCUNode()->getSplitDebugInlining())
  1989. SkelCU->constructSubprogramScopeDIE(SP, FnScope);
  1990. // Construct call site entries.
  1991. constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
  1992. // Clear debug info
  1993. // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
  1994. // DbgVariables except those that are also in AbstractVariables (since they
  1995. // can be used cross-function)
  1996. InfoHolder.getScopeVariables().clear();
  1997. InfoHolder.getScopeLabels().clear();
  1998. PrevLabel = nullptr;
  1999. CurFn = nullptr;
  2000. }
  2001. // Register a source line with debug info. Returns the unique label that was
  2002. // emitted and which provides correspondence to the source line list.
  2003. void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
  2004. unsigned Flags) {
  2005. ::recordSourceLine(*Asm, Line, Col, S, Flags,
  2006. Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
  2007. getDwarfVersion(), getUnits());
  2008. }
  2009. //===----------------------------------------------------------------------===//
  2010. // Emit Methods
  2011. //===----------------------------------------------------------------------===//
  2012. // Emit the debug info section.
  2013. void DwarfDebug::emitDebugInfo() {
  2014. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  2015. Holder.emitUnits(/* UseOffsets */ false);
  2016. }
  2017. // Emit the abbreviation section.
  2018. void DwarfDebug::emitAbbreviations() {
  2019. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  2020. Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
  2021. }
  2022. void DwarfDebug::emitStringOffsetsTableHeader() {
  2023. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  2024. Holder.getStringPool().emitStringOffsetsTableHeader(
  2025. *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
  2026. Holder.getStringOffsetsStartSym());
  2027. }
  2028. template <typename AccelTableT>
  2029. void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
  2030. StringRef TableName) {
  2031. Asm->OutStreamer->switchSection(Section);
  2032. // Emit the full data.
  2033. emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
  2034. }
  2035. void DwarfDebug::emitAccelDebugNames() {
  2036. // Don't emit anything if we have no compilation units to index.
  2037. if (getUnits().empty())
  2038. return;
  2039. emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
  2040. }
  2041. // Emit visible names into a hashed accelerator table section.
  2042. void DwarfDebug::emitAccelNames() {
  2043. emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
  2044. "Names");
  2045. }
  2046. // Emit objective C classes and categories into a hashed accelerator table
  2047. // section.
  2048. void DwarfDebug::emitAccelObjC() {
  2049. emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
  2050. "ObjC");
  2051. }
  2052. // Emit namespace dies into a hashed accelerator table.
  2053. void DwarfDebug::emitAccelNamespaces() {
  2054. emitAccel(AccelNamespace,
  2055. Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
  2056. "namespac");
  2057. }
  2058. // Emit type dies into a hashed accelerator table.
  2059. void DwarfDebug::emitAccelTypes() {
  2060. emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
  2061. "types");
  2062. }
  2063. // Public name handling.
  2064. // The format for the various pubnames:
  2065. //
  2066. // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
  2067. // for the DIE that is named.
  2068. //
  2069. // gnu pubnames - offset/index value/name tuples where the offset is the offset
  2070. // into the CU and the index value is computed according to the type of value
  2071. // for the DIE that is named.
  2072. //
  2073. // For type units the offset is the offset of the skeleton DIE. For split dwarf
  2074. // it's the offset within the debug_info/debug_types dwo section, however, the
  2075. // reference in the pubname header doesn't change.
  2076. /// computeIndexValue - Compute the gdb index value for the DIE and CU.
  2077. static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
  2078. const DIE *Die) {
  2079. // Entities that ended up only in a Type Unit reference the CU instead (since
  2080. // the pub entry has offsets within the CU there's no real offset that can be
  2081. // provided anyway). As it happens all such entities (namespaces and types,
  2082. // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
  2083. // not to be true it would be necessary to persist this information from the
  2084. // point at which the entry is added to the index data structure - since by
  2085. // the time the index is built from that, the original type/namespace DIE in a
  2086. // type unit has already been destroyed so it can't be queried for properties
  2087. // like tag, etc.
  2088. if (Die->getTag() == dwarf::DW_TAG_compile_unit)
  2089. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
  2090. dwarf::GIEL_EXTERNAL);
  2091. dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
  2092. // We could have a specification DIE that has our most of our knowledge,
  2093. // look for that now.
  2094. if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
  2095. DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
  2096. if (SpecDIE.findAttribute(dwarf::DW_AT_external))
  2097. Linkage = dwarf::GIEL_EXTERNAL;
  2098. } else if (Die->findAttribute(dwarf::DW_AT_external))
  2099. Linkage = dwarf::GIEL_EXTERNAL;
  2100. switch (Die->getTag()) {
  2101. case dwarf::DW_TAG_class_type:
  2102. case dwarf::DW_TAG_structure_type:
  2103. case dwarf::DW_TAG_union_type:
  2104. case dwarf::DW_TAG_enumeration_type:
  2105. return dwarf::PubIndexEntryDescriptor(
  2106. dwarf::GIEK_TYPE,
  2107. dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
  2108. ? dwarf::GIEL_EXTERNAL
  2109. : dwarf::GIEL_STATIC);
  2110. case dwarf::DW_TAG_typedef:
  2111. case dwarf::DW_TAG_base_type:
  2112. case dwarf::DW_TAG_subrange_type:
  2113. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
  2114. case dwarf::DW_TAG_namespace:
  2115. return dwarf::GIEK_TYPE;
  2116. case dwarf::DW_TAG_subprogram:
  2117. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
  2118. case dwarf::DW_TAG_variable:
  2119. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
  2120. case dwarf::DW_TAG_enumerator:
  2121. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
  2122. dwarf::GIEL_STATIC);
  2123. default:
  2124. return dwarf::GIEK_NONE;
  2125. }
  2126. }
  2127. /// emitDebugPubSections - Emit visible names and types into debug pubnames and
  2128. /// pubtypes sections.
  2129. void DwarfDebug::emitDebugPubSections() {
  2130. for (const auto &NU : CUMap) {
  2131. DwarfCompileUnit *TheU = NU.second;
  2132. if (!TheU->hasDwarfPubSections())
  2133. continue;
  2134. bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
  2135. DICompileUnit::DebugNameTableKind::GNU;
  2136. Asm->OutStreamer->switchSection(
  2137. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
  2138. : Asm->getObjFileLowering().getDwarfPubNamesSection());
  2139. emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
  2140. Asm->OutStreamer->switchSection(
  2141. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
  2142. : Asm->getObjFileLowering().getDwarfPubTypesSection());
  2143. emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
  2144. }
  2145. }
  2146. void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
  2147. if (useSectionsAsReferences())
  2148. Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
  2149. CU.getDebugSectionOffset());
  2150. else
  2151. Asm->emitDwarfSymbolReference(CU.getLabelBegin());
  2152. }
  2153. void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
  2154. DwarfCompileUnit *TheU,
  2155. const StringMap<const DIE *> &Globals) {
  2156. if (auto *Skeleton = TheU->getSkeleton())
  2157. TheU = Skeleton;
  2158. // Emit the header.
  2159. MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
  2160. "pub" + Name, "Length of Public " + Name + " Info");
  2161. Asm->OutStreamer->AddComment("DWARF Version");
  2162. Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
  2163. Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
  2164. emitSectionReference(*TheU);
  2165. Asm->OutStreamer->AddComment("Compilation Unit Length");
  2166. Asm->emitDwarfLengthOrOffset(TheU->getLength());
  2167. // Emit the pubnames for this compilation unit.
  2168. for (const auto &GI : Globals) {
  2169. const char *Name = GI.getKeyData();
  2170. const DIE *Entity = GI.second;
  2171. Asm->OutStreamer->AddComment("DIE offset");
  2172. Asm->emitDwarfLengthOrOffset(Entity->getOffset());
  2173. if (GnuStyle) {
  2174. dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
  2175. Asm->OutStreamer->AddComment(
  2176. Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
  2177. ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
  2178. Asm->emitInt8(Desc.toBits());
  2179. }
  2180. Asm->OutStreamer->AddComment("External Name");
  2181. Asm->OutStreamer->emitBytes(StringRef(Name, GI.getKeyLength() + 1));
  2182. }
  2183. Asm->OutStreamer->AddComment("End Mark");
  2184. Asm->emitDwarfLengthOrOffset(0);
  2185. Asm->OutStreamer->emitLabel(EndLabel);
  2186. }
  2187. /// Emit null-terminated strings into a debug str section.
  2188. void DwarfDebug::emitDebugStr() {
  2189. MCSection *StringOffsetsSection = nullptr;
  2190. if (useSegmentedStringOffsetsTable()) {
  2191. emitStringOffsetsTableHeader();
  2192. StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
  2193. }
  2194. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  2195. Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
  2196. StringOffsetsSection, /* UseRelativeOffsets = */ true);
  2197. }
  2198. void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
  2199. const DebugLocStream::Entry &Entry,
  2200. const DwarfCompileUnit *CU) {
  2201. auto &&Comments = DebugLocs.getComments(Entry);
  2202. auto Comment = Comments.begin();
  2203. auto End = Comments.end();
  2204. // The expressions are inserted into a byte stream rather early (see
  2205. // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
  2206. // need to reference a base_type DIE the offset of that DIE is not yet known.
  2207. // To deal with this we instead insert a placeholder early and then extract
  2208. // it here and replace it with the real reference.
  2209. unsigned PtrSize = Asm->MAI->getCodePointerSize();
  2210. DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
  2211. DebugLocs.getBytes(Entry).size()),
  2212. Asm->getDataLayout().isLittleEndian(), PtrSize);
  2213. DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
  2214. using Encoding = DWARFExpression::Operation::Encoding;
  2215. uint64_t Offset = 0;
  2216. for (const auto &Op : Expr) {
  2217. assert(Op.getCode() != dwarf::DW_OP_const_type &&
  2218. "3 operand ops not yet supported");
  2219. Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
  2220. Offset++;
  2221. for (unsigned I = 0; I < 2; ++I) {
  2222. if (Op.getDescription().Op[I] == Encoding::SizeNA)
  2223. continue;
  2224. if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
  2225. unsigned Length =
  2226. Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);
  2227. // Make sure comments stay aligned.
  2228. for (unsigned J = 0; J < Length; ++J)
  2229. if (Comment != End)
  2230. Comment++;
  2231. } else {
  2232. for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
  2233. Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
  2234. }
  2235. Offset = Op.getOperandEndOffset(I);
  2236. }
  2237. assert(Offset == Op.getEndOffset());
  2238. }
  2239. }
  2240. void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
  2241. const DbgValueLoc &Value,
  2242. DwarfExpression &DwarfExpr) {
  2243. auto *DIExpr = Value.getExpression();
  2244. DIExpressionCursor ExprCursor(DIExpr);
  2245. DwarfExpr.addFragmentOffset(DIExpr);
  2246. // If the DIExpr is is an Entry Value, we want to follow the same code path
  2247. // regardless of whether the DBG_VALUE is variadic or not.
  2248. if (DIExpr && DIExpr->isEntryValue()) {
  2249. // Entry values can only be a single register with no additional DIExpr,
  2250. // so just add it directly.
  2251. assert(Value.getLocEntries().size() == 1);
  2252. assert(Value.getLocEntries()[0].isLocation());
  2253. MachineLocation Location = Value.getLocEntries()[0].getLoc();
  2254. DwarfExpr.setLocation(Location, DIExpr);
  2255. DwarfExpr.beginEntryValueExpression(ExprCursor);
  2256. const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
  2257. if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))
  2258. return;
  2259. return DwarfExpr.addExpression(std::move(ExprCursor));
  2260. }
  2261. // Regular entry.
  2262. auto EmitValueLocEntry = [&DwarfExpr, &BT,
  2263. &AP](const DbgValueLocEntry &Entry,
  2264. DIExpressionCursor &Cursor) -> bool {
  2265. if (Entry.isInt()) {
  2266. if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
  2267. BT->getEncoding() == dwarf::DW_ATE_signed_char))
  2268. DwarfExpr.addSignedConstant(Entry.getInt());
  2269. else
  2270. DwarfExpr.addUnsignedConstant(Entry.getInt());
  2271. } else if (Entry.isLocation()) {
  2272. MachineLocation Location = Entry.getLoc();
  2273. if (Location.isIndirect())
  2274. DwarfExpr.setMemoryLocationKind();
  2275. const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
  2276. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
  2277. return false;
  2278. } else if (Entry.isTargetIndexLocation()) {
  2279. TargetIndexLocation Loc = Entry.getTargetIndexLocation();
  2280. // TODO TargetIndexLocation is a target-independent. Currently only the
  2281. // WebAssembly-specific encoding is supported.
  2282. assert(AP.TM.getTargetTriple().isWasm());
  2283. DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
  2284. } else if (Entry.isConstantFP()) {
  2285. if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
  2286. !Cursor) {
  2287. DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
  2288. } else if (Entry.getConstantFP()
  2289. ->getValueAPF()
  2290. .bitcastToAPInt()
  2291. .getBitWidth() <= 64 /*bits*/) {
  2292. DwarfExpr.addUnsignedConstant(
  2293. Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
  2294. } else {
  2295. LLVM_DEBUG(
  2296. dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
  2297. << Entry.getConstantFP()
  2298. ->getValueAPF()
  2299. .bitcastToAPInt()
  2300. .getBitWidth()
  2301. << " bits\n");
  2302. return false;
  2303. }
  2304. }
  2305. return true;
  2306. };
  2307. if (!Value.isVariadic()) {
  2308. if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
  2309. return;
  2310. DwarfExpr.addExpression(std::move(ExprCursor));
  2311. return;
  2312. }
  2313. // If any of the location entries are registers with the value 0, then the
  2314. // location is undefined.
  2315. if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {
  2316. return Entry.isLocation() && !Entry.getLoc().getReg();
  2317. }))
  2318. return;
  2319. DwarfExpr.addExpression(
  2320. std::move(ExprCursor),
  2321. [EmitValueLocEntry, &Value](unsigned Idx,
  2322. DIExpressionCursor &Cursor) -> bool {
  2323. return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
  2324. });
  2325. }
  2326. void DebugLocEntry::finalize(const AsmPrinter &AP,
  2327. DebugLocStream::ListBuilder &List,
  2328. const DIBasicType *BT,
  2329. DwarfCompileUnit &TheCU) {
  2330. assert(!Values.empty() &&
  2331. "location list entries without values are redundant");
  2332. assert(Begin != End && "unexpected location list entry with empty range");
  2333. DebugLocStream::EntryBuilder Entry(List, Begin, End);
  2334. BufferByteStreamer Streamer = Entry.getStreamer();
  2335. DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
  2336. const DbgValueLoc &Value = Values[0];
  2337. if (Value.isFragment()) {
  2338. // Emit all fragments that belong to the same variable and range.
  2339. assert(llvm::all_of(Values, [](DbgValueLoc P) {
  2340. return P.isFragment();
  2341. }) && "all values are expected to be fragments");
  2342. assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
  2343. for (const auto &Fragment : Values)
  2344. DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
  2345. } else {
  2346. assert(Values.size() == 1 && "only fragments may have >1 value");
  2347. DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
  2348. }
  2349. DwarfExpr.finalize();
  2350. if (DwarfExpr.TagOffset)
  2351. List.setTagOffset(*DwarfExpr.TagOffset);
  2352. }
  2353. void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
  2354. const DwarfCompileUnit *CU) {
  2355. // Emit the size.
  2356. Asm->OutStreamer->AddComment("Loc expr size");
  2357. if (getDwarfVersion() >= 5)
  2358. Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
  2359. else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
  2360. Asm->emitInt16(DebugLocs.getBytes(Entry).size());
  2361. else {
  2362. // The entry is too big to fit into 16 bit, drop it as there is nothing we
  2363. // can do.
  2364. Asm->emitInt16(0);
  2365. return;
  2366. }
  2367. // Emit the entry.
  2368. APByteStreamer Streamer(*Asm);
  2369. emitDebugLocEntry(Streamer, Entry, CU);
  2370. }
  2371. // Emit the header of a DWARF 5 range list table list table. Returns the symbol
  2372. // that designates the end of the table for the caller to emit when the table is
  2373. // complete.
  2374. static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
  2375. const DwarfFile &Holder) {
  2376. MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
  2377. Asm->OutStreamer->AddComment("Offset entry count");
  2378. Asm->emitInt32(Holder.getRangeLists().size());
  2379. Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
  2380. for (const RangeSpanList &List : Holder.getRangeLists())
  2381. Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
  2382. Asm->getDwarfOffsetByteSize());
  2383. return TableEnd;
  2384. }
  2385. // Emit the header of a DWARF 5 locations list table. Returns the symbol that
  2386. // designates the end of the table for the caller to emit when the table is
  2387. // complete.
  2388. static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
  2389. const DwarfDebug &DD) {
  2390. MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
  2391. const auto &DebugLocs = DD.getDebugLocs();
  2392. Asm->OutStreamer->AddComment("Offset entry count");
  2393. Asm->emitInt32(DebugLocs.getLists().size());
  2394. Asm->OutStreamer->emitLabel(DebugLocs.getSym());
  2395. for (const auto &List : DebugLocs.getLists())
  2396. Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
  2397. Asm->getDwarfOffsetByteSize());
  2398. return TableEnd;
  2399. }
  2400. template <typename Ranges, typename PayloadEmitter>
  2401. static void emitRangeList(
  2402. DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
  2403. const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
  2404. unsigned StartxLength, unsigned EndOfList,
  2405. StringRef (*StringifyEnum)(unsigned),
  2406. bool ShouldUseBaseAddress,
  2407. PayloadEmitter EmitPayload) {
  2408. auto Size = Asm->MAI->getCodePointerSize();
  2409. bool UseDwarf5 = DD.getDwarfVersion() >= 5;
  2410. // Emit our symbol so we can find the beginning of the range.
  2411. Asm->OutStreamer->emitLabel(Sym);
  2412. // Gather all the ranges that apply to the same section so they can share
  2413. // a base address entry.
  2414. MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
  2415. for (const auto &Range : R)
  2416. SectionRanges[&Range.Begin->getSection()].push_back(&Range);
  2417. const MCSymbol *CUBase = CU.getBaseAddress();
  2418. bool BaseIsSet = false;
  2419. for (const auto &P : SectionRanges) {
  2420. auto *Base = CUBase;
  2421. if (!Base && ShouldUseBaseAddress) {
  2422. const MCSymbol *Begin = P.second.front()->Begin;
  2423. const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
  2424. if (!UseDwarf5) {
  2425. Base = NewBase;
  2426. BaseIsSet = true;
  2427. Asm->OutStreamer->emitIntValue(-1, Size);
  2428. Asm->OutStreamer->AddComment(" base address");
  2429. Asm->OutStreamer->emitSymbolValue(Base, Size);
  2430. } else if (NewBase != Begin || P.second.size() > 1) {
  2431. // Only use a base address if
  2432. // * the existing pool address doesn't match (NewBase != Begin)
  2433. // * or, there's more than one entry to share the base address
  2434. Base = NewBase;
  2435. BaseIsSet = true;
  2436. Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
  2437. Asm->emitInt8(BaseAddressx);
  2438. Asm->OutStreamer->AddComment(" base address index");
  2439. Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
  2440. }
  2441. } else if (BaseIsSet && !UseDwarf5) {
  2442. BaseIsSet = false;
  2443. assert(!Base);
  2444. Asm->OutStreamer->emitIntValue(-1, Size);
  2445. Asm->OutStreamer->emitIntValue(0, Size);
  2446. }
  2447. for (const auto *RS : P.second) {
  2448. const MCSymbol *Begin = RS->Begin;
  2449. const MCSymbol *End = RS->End;
  2450. assert(Begin && "Range without a begin symbol?");
  2451. assert(End && "Range without an end symbol?");
  2452. if (Base) {
  2453. if (UseDwarf5) {
  2454. // Emit offset_pair when we have a base.
  2455. Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
  2456. Asm->emitInt8(OffsetPair);
  2457. Asm->OutStreamer->AddComment(" starting offset");
  2458. Asm->emitLabelDifferenceAsULEB128(Begin, Base);
  2459. Asm->OutStreamer->AddComment(" ending offset");
  2460. Asm->emitLabelDifferenceAsULEB128(End, Base);
  2461. } else {
  2462. Asm->emitLabelDifference(Begin, Base, Size);
  2463. Asm->emitLabelDifference(End, Base, Size);
  2464. }
  2465. } else if (UseDwarf5) {
  2466. Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
  2467. Asm->emitInt8(StartxLength);
  2468. Asm->OutStreamer->AddComment(" start index");
  2469. Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
  2470. Asm->OutStreamer->AddComment(" length");
  2471. Asm->emitLabelDifferenceAsULEB128(End, Begin);
  2472. } else {
  2473. Asm->OutStreamer->emitSymbolValue(Begin, Size);
  2474. Asm->OutStreamer->emitSymbolValue(End, Size);
  2475. }
  2476. EmitPayload(*RS);
  2477. }
  2478. }
  2479. if (UseDwarf5) {
  2480. Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
  2481. Asm->emitInt8(EndOfList);
  2482. } else {
  2483. // Terminate the list with two 0 values.
  2484. Asm->OutStreamer->emitIntValue(0, Size);
  2485. Asm->OutStreamer->emitIntValue(0, Size);
  2486. }
  2487. }
  2488. // Handles emission of both debug_loclist / debug_loclist.dwo
  2489. static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
  2490. emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
  2491. *List.CU, dwarf::DW_LLE_base_addressx,
  2492. dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
  2493. dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
  2494. /* ShouldUseBaseAddress */ true,
  2495. [&](const DebugLocStream::Entry &E) {
  2496. DD.emitDebugLocEntryLocation(E, List.CU);
  2497. });
  2498. }
  2499. void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
  2500. if (DebugLocs.getLists().empty())
  2501. return;
  2502. Asm->OutStreamer->switchSection(Sec);
  2503. MCSymbol *TableEnd = nullptr;
  2504. if (getDwarfVersion() >= 5)
  2505. TableEnd = emitLoclistsTableHeader(Asm, *this);
  2506. for (const auto &List : DebugLocs.getLists())
  2507. emitLocList(*this, Asm, List);
  2508. if (TableEnd)
  2509. Asm->OutStreamer->emitLabel(TableEnd);
  2510. }
  2511. // Emit locations into the .debug_loc/.debug_loclists section.
  2512. void DwarfDebug::emitDebugLoc() {
  2513. emitDebugLocImpl(
  2514. getDwarfVersion() >= 5
  2515. ? Asm->getObjFileLowering().getDwarfLoclistsSection()
  2516. : Asm->getObjFileLowering().getDwarfLocSection());
  2517. }
  2518. // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
  2519. void DwarfDebug::emitDebugLocDWO() {
  2520. if (getDwarfVersion() >= 5) {
  2521. emitDebugLocImpl(
  2522. Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
  2523. return;
  2524. }
  2525. for (const auto &List : DebugLocs.getLists()) {
  2526. Asm->OutStreamer->switchSection(
  2527. Asm->getObjFileLowering().getDwarfLocDWOSection());
  2528. Asm->OutStreamer->emitLabel(List.Label);
  2529. for (const auto &Entry : DebugLocs.getEntries(List)) {
  2530. // GDB only supports startx_length in pre-standard split-DWARF.
  2531. // (in v5 standard loclists, it currently* /only/ supports base_address +
  2532. // offset_pair, so the implementations can't really share much since they
  2533. // need to use different representations)
  2534. // * as of October 2018, at least
  2535. //
  2536. // In v5 (see emitLocList), this uses SectionLabels to reuse existing
  2537. // addresses in the address pool to minimize object size/relocations.
  2538. Asm->emitInt8(dwarf::DW_LLE_startx_length);
  2539. unsigned idx = AddrPool.getIndex(Entry.Begin);
  2540. Asm->emitULEB128(idx);
  2541. // Also the pre-standard encoding is slightly different, emitting this as
  2542. // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
  2543. Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
  2544. emitDebugLocEntryLocation(Entry, List.CU);
  2545. }
  2546. Asm->emitInt8(dwarf::DW_LLE_end_of_list);
  2547. }
  2548. }
  2549. struct ArangeSpan {
  2550. const MCSymbol *Start, *End;
  2551. };
  2552. // Emit a debug aranges section, containing a CU lookup for any
  2553. // address we can tie back to a CU.
  2554. void DwarfDebug::emitDebugARanges() {
  2555. // Provides a unique id per text section.
  2556. MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
  2557. // Filter labels by section.
  2558. for (const SymbolCU &SCU : ArangeLabels) {
  2559. if (SCU.Sym->isInSection()) {
  2560. // Make a note of this symbol and it's section.
  2561. MCSection *Section = &SCU.Sym->getSection();
  2562. if (!Section->getKind().isMetadata())
  2563. SectionMap[Section].push_back(SCU);
  2564. } else {
  2565. // Some symbols (e.g. common/bss on mach-o) can have no section but still
  2566. // appear in the output. This sucks as we rely on sections to build
  2567. // arange spans. We can do it without, but it's icky.
  2568. SectionMap[nullptr].push_back(SCU);
  2569. }
  2570. }
  2571. DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
  2572. for (auto &I : SectionMap) {
  2573. MCSection *Section = I.first;
  2574. SmallVector<SymbolCU, 8> &List = I.second;
  2575. if (List.size() < 1)
  2576. continue;
  2577. // If we have no section (e.g. common), just write out
  2578. // individual spans for each symbol.
  2579. if (!Section) {
  2580. for (const SymbolCU &Cur : List) {
  2581. ArangeSpan Span;
  2582. Span.Start = Cur.Sym;
  2583. Span.End = nullptr;
  2584. assert(Cur.CU);
  2585. Spans[Cur.CU].push_back(Span);
  2586. }
  2587. continue;
  2588. }
  2589. // Sort the symbols by offset within the section.
  2590. llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
  2591. unsigned IA = A.Sym ? Asm->OutStreamer->getSymbolOrder(A.Sym) : 0;
  2592. unsigned IB = B.Sym ? Asm->OutStreamer->getSymbolOrder(B.Sym) : 0;
  2593. // Symbols with no order assigned should be placed at the end.
  2594. // (e.g. section end labels)
  2595. if (IA == 0)
  2596. return false;
  2597. if (IB == 0)
  2598. return true;
  2599. return IA < IB;
  2600. });
  2601. // Insert a final terminator.
  2602. List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
  2603. // Build spans between each label.
  2604. const MCSymbol *StartSym = List[0].Sym;
  2605. for (size_t n = 1, e = List.size(); n < e; n++) {
  2606. const SymbolCU &Prev = List[n - 1];
  2607. const SymbolCU &Cur = List[n];
  2608. // Try and build the longest span we can within the same CU.
  2609. if (Cur.CU != Prev.CU) {
  2610. ArangeSpan Span;
  2611. Span.Start = StartSym;
  2612. Span.End = Cur.Sym;
  2613. assert(Prev.CU);
  2614. Spans[Prev.CU].push_back(Span);
  2615. StartSym = Cur.Sym;
  2616. }
  2617. }
  2618. }
  2619. // Start the dwarf aranges section.
  2620. Asm->OutStreamer->switchSection(
  2621. Asm->getObjFileLowering().getDwarfARangesSection());
  2622. unsigned PtrSize = Asm->MAI->getCodePointerSize();
  2623. // Build a list of CUs used.
  2624. std::vector<DwarfCompileUnit *> CUs;
  2625. for (const auto &it : Spans) {
  2626. DwarfCompileUnit *CU = it.first;
  2627. CUs.push_back(CU);
  2628. }
  2629. // Sort the CU list (again, to ensure consistent output order).
  2630. llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
  2631. return A->getUniqueID() < B->getUniqueID();
  2632. });
  2633. // Emit an arange table for each CU we used.
  2634. for (DwarfCompileUnit *CU : CUs) {
  2635. std::vector<ArangeSpan> &List = Spans[CU];
  2636. // Describe the skeleton CU's offset and length, not the dwo file's.
  2637. if (auto *Skel = CU->getSkeleton())
  2638. CU = Skel;
  2639. // Emit size of content not including length itself.
  2640. unsigned ContentSize =
  2641. sizeof(int16_t) + // DWARF ARange version number
  2642. Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
  2643. // section
  2644. sizeof(int8_t) + // Pointer Size (in bytes)
  2645. sizeof(int8_t); // Segment Size (in bytes)
  2646. unsigned TupleSize = PtrSize * 2;
  2647. // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
  2648. unsigned Padding = offsetToAlignment(
  2649. Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
  2650. ContentSize += Padding;
  2651. ContentSize += (List.size() + 1) * TupleSize;
  2652. // For each compile unit, write the list of spans it covers.
  2653. Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
  2654. Asm->OutStreamer->AddComment("DWARF Arange version number");
  2655. Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
  2656. Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
  2657. emitSectionReference(*CU);
  2658. Asm->OutStreamer->AddComment("Address Size (in bytes)");
  2659. Asm->emitInt8(PtrSize);
  2660. Asm->OutStreamer->AddComment("Segment Size (in bytes)");
  2661. Asm->emitInt8(0);
  2662. Asm->OutStreamer->emitFill(Padding, 0xff);
  2663. for (const ArangeSpan &Span : List) {
  2664. Asm->emitLabelReference(Span.Start, PtrSize);
  2665. // Calculate the size as being from the span start to its end.
  2666. //
  2667. // If the size is zero, then round it up to one byte. The DWARF
  2668. // specification requires that entries in this table have nonzero
  2669. // lengths.
  2670. auto SizeRef = SymSize.find(Span.Start);
  2671. if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
  2672. Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
  2673. } else {
  2674. // For symbols without an end marker (e.g. common), we
  2675. // write a single arange entry containing just that one symbol.
  2676. uint64_t Size;
  2677. if (SizeRef == SymSize.end() || SizeRef->second == 0)
  2678. Size = 1;
  2679. else
  2680. Size = SizeRef->second;
  2681. Asm->OutStreamer->emitIntValue(Size, PtrSize);
  2682. }
  2683. }
  2684. Asm->OutStreamer->AddComment("ARange terminator");
  2685. Asm->OutStreamer->emitIntValue(0, PtrSize);
  2686. Asm->OutStreamer->emitIntValue(0, PtrSize);
  2687. }
  2688. }
  2689. /// Emit a single range list. We handle both DWARF v5 and earlier.
  2690. static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
  2691. const RangeSpanList &List) {
  2692. emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
  2693. dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
  2694. dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
  2695. llvm::dwarf::RangeListEncodingString,
  2696. List.CU->getCUNode()->getRangesBaseAddress() ||
  2697. DD.getDwarfVersion() >= 5,
  2698. [](auto) {});
  2699. }
  2700. void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
  2701. if (Holder.getRangeLists().empty())
  2702. return;
  2703. assert(useRangesSection());
  2704. assert(!CUMap.empty());
  2705. assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
  2706. return !Pair.second->getCUNode()->isDebugDirectivesOnly();
  2707. }));
  2708. Asm->OutStreamer->switchSection(Section);
  2709. MCSymbol *TableEnd = nullptr;
  2710. if (getDwarfVersion() >= 5)
  2711. TableEnd = emitRnglistsTableHeader(Asm, Holder);
  2712. for (const RangeSpanList &List : Holder.getRangeLists())
  2713. emitRangeList(*this, Asm, List);
  2714. if (TableEnd)
  2715. Asm->OutStreamer->emitLabel(TableEnd);
  2716. }
  2717. /// Emit address ranges into the .debug_ranges section or into the DWARF v5
  2718. /// .debug_rnglists section.
  2719. void DwarfDebug::emitDebugRanges() {
  2720. const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  2721. emitDebugRangesImpl(Holder,
  2722. getDwarfVersion() >= 5
  2723. ? Asm->getObjFileLowering().getDwarfRnglistsSection()
  2724. : Asm->getObjFileLowering().getDwarfRangesSection());
  2725. }
  2726. void DwarfDebug::emitDebugRangesDWO() {
  2727. emitDebugRangesImpl(InfoHolder,
  2728. Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
  2729. }
  2730. /// Emit the header of a DWARF 5 macro section, or the GNU extension for
  2731. /// DWARF 4.
  2732. static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
  2733. const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
  2734. enum HeaderFlagMask {
  2735. #define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
  2736. #include "llvm/BinaryFormat/Dwarf.def"
  2737. };
  2738. Asm->OutStreamer->AddComment("Macro information version");
  2739. Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
  2740. // We emit the line offset flag unconditionally here, since line offset should
  2741. // be mostly present.
  2742. if (Asm->isDwarf64()) {
  2743. Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
  2744. Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
  2745. } else {
  2746. Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
  2747. Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
  2748. }
  2749. Asm->OutStreamer->AddComment("debug_line_offset");
  2750. if (DD.useSplitDwarf())
  2751. Asm->emitDwarfLengthOrOffset(0);
  2752. else
  2753. Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
  2754. }
  2755. void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
  2756. for (auto *MN : Nodes) {
  2757. if (auto *M = dyn_cast<DIMacro>(MN))
  2758. emitMacro(*M);
  2759. else if (auto *F = dyn_cast<DIMacroFile>(MN))
  2760. emitMacroFile(*F, U);
  2761. else
  2762. llvm_unreachable("Unexpected DI type!");
  2763. }
  2764. }
  2765. void DwarfDebug::emitMacro(DIMacro &M) {
  2766. StringRef Name = M.getName();
  2767. StringRef Value = M.getValue();
  2768. // There should be one space between the macro name and the macro value in
  2769. // define entries. In undef entries, only the macro name is emitted.
  2770. std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
  2771. if (UseDebugMacroSection) {
  2772. if (getDwarfVersion() >= 5) {
  2773. unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
  2774. ? dwarf::DW_MACRO_define_strx
  2775. : dwarf::DW_MACRO_undef_strx;
  2776. Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
  2777. Asm->emitULEB128(Type);
  2778. Asm->OutStreamer->AddComment("Line Number");
  2779. Asm->emitULEB128(M.getLine());
  2780. Asm->OutStreamer->AddComment("Macro String");
  2781. Asm->emitULEB128(
  2782. InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
  2783. } else {
  2784. unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
  2785. ? dwarf::DW_MACRO_GNU_define_indirect
  2786. : dwarf::DW_MACRO_GNU_undef_indirect;
  2787. Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));
  2788. Asm->emitULEB128(Type);
  2789. Asm->OutStreamer->AddComment("Line Number");
  2790. Asm->emitULEB128(M.getLine());
  2791. Asm->OutStreamer->AddComment("Macro String");
  2792. Asm->emitDwarfSymbolReference(
  2793. InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
  2794. }
  2795. } else {
  2796. Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
  2797. Asm->emitULEB128(M.getMacinfoType());
  2798. Asm->OutStreamer->AddComment("Line Number");
  2799. Asm->emitULEB128(M.getLine());
  2800. Asm->OutStreamer->AddComment("Macro String");
  2801. Asm->OutStreamer->emitBytes(Str);
  2802. Asm->emitInt8('\0');
  2803. }
  2804. }
  2805. void DwarfDebug::emitMacroFileImpl(
  2806. DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
  2807. StringRef (*MacroFormToString)(unsigned Form)) {
  2808. Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
  2809. Asm->emitULEB128(StartFile);
  2810. Asm->OutStreamer->AddComment("Line Number");
  2811. Asm->emitULEB128(MF.getLine());
  2812. Asm->OutStreamer->AddComment("File Number");
  2813. DIFile &F = *MF.getFile();
  2814. if (useSplitDwarf())
  2815. Asm->emitULEB128(getDwoLineTable(U)->getFile(
  2816. F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
  2817. Asm->OutContext.getDwarfVersion(), F.getSource()));
  2818. else
  2819. Asm->emitULEB128(U.getOrCreateSourceID(&F));
  2820. handleMacroNodes(MF.getElements(), U);
  2821. Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
  2822. Asm->emitULEB128(EndFile);
  2823. }
  2824. void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
  2825. // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
  2826. // so for readibility/uniformity, We are explicitly emitting those.
  2827. assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
  2828. if (UseDebugMacroSection)
  2829. emitMacroFileImpl(
  2830. F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
  2831. (getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);
  2832. else
  2833. emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
  2834. dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);
  2835. }
  2836. void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
  2837. for (const auto &P : CUMap) {
  2838. auto &TheCU = *P.second;
  2839. auto *SkCU = TheCU.getSkeleton();
  2840. DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
  2841. auto *CUNode = cast<DICompileUnit>(P.first);
  2842. DIMacroNodeArray Macros = CUNode->getMacros();
  2843. if (Macros.empty())
  2844. continue;
  2845. Asm->OutStreamer->switchSection(Section);
  2846. Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
  2847. if (UseDebugMacroSection)
  2848. emitMacroHeader(Asm, *this, U, getDwarfVersion());
  2849. handleMacroNodes(Macros, U);
  2850. Asm->OutStreamer->AddComment("End Of Macro List Mark");
  2851. Asm->emitInt8(0);
  2852. }
  2853. }
  2854. /// Emit macros into a debug macinfo/macro section.
  2855. void DwarfDebug::emitDebugMacinfo() {
  2856. auto &ObjLower = Asm->getObjFileLowering();
  2857. emitDebugMacinfoImpl(UseDebugMacroSection
  2858. ? ObjLower.getDwarfMacroSection()
  2859. : ObjLower.getDwarfMacinfoSection());
  2860. }
  2861. void DwarfDebug::emitDebugMacinfoDWO() {
  2862. auto &ObjLower = Asm->getObjFileLowering();
  2863. emitDebugMacinfoImpl(UseDebugMacroSection
  2864. ? ObjLower.getDwarfMacroDWOSection()
  2865. : ObjLower.getDwarfMacinfoDWOSection());
  2866. }
  2867. // DWARF5 Experimental Separate Dwarf emitters.
  2868. void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
  2869. std::unique_ptr<DwarfCompileUnit> NewU) {
  2870. if (!CompilationDir.empty())
  2871. NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  2872. addGnuPubAttributes(*NewU, Die);
  2873. SkeletonHolder.addUnit(std::move(NewU));
  2874. }
  2875. DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
  2876. auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
  2877. CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
  2878. UnitKind::Skeleton);
  2879. DwarfCompileUnit &NewCU = *OwnedUnit;
  2880. NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
  2881. NewCU.initStmtList();
  2882. if (useSegmentedStringOffsetsTable())
  2883. NewCU.addStringOffsetsStart();
  2884. initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
  2885. return NewCU;
  2886. }
  2887. // Emit the .debug_info.dwo section for separated dwarf. This contains the
  2888. // compile units that would normally be in debug_info.
  2889. void DwarfDebug::emitDebugInfoDWO() {
  2890. assert(useSplitDwarf() && "No split dwarf debug info?");
  2891. // Don't emit relocations into the dwo file.
  2892. InfoHolder.emitUnits(/* UseOffsets */ true);
  2893. }
  2894. // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
  2895. // abbreviations for the .debug_info.dwo section.
  2896. void DwarfDebug::emitDebugAbbrevDWO() {
  2897. assert(useSplitDwarf() && "No split dwarf?");
  2898. InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
  2899. }
  2900. void DwarfDebug::emitDebugLineDWO() {
  2901. assert(useSplitDwarf() && "No split dwarf?");
  2902. SplitTypeUnitFileTable.Emit(
  2903. *Asm->OutStreamer, MCDwarfLineTableParams(),
  2904. Asm->getObjFileLowering().getDwarfLineDWOSection());
  2905. }
  2906. void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
  2907. assert(useSplitDwarf() && "No split dwarf?");
  2908. InfoHolder.getStringPool().emitStringOffsetsTableHeader(
  2909. *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
  2910. InfoHolder.getStringOffsetsStartSym());
  2911. }
  2912. // Emit the .debug_str.dwo section for separated dwarf. This contains the
  2913. // string section and is identical in format to traditional .debug_str
  2914. // sections.
  2915. void DwarfDebug::emitDebugStrDWO() {
  2916. if (useSegmentedStringOffsetsTable())
  2917. emitStringOffsetsTableHeaderDWO();
  2918. assert(useSplitDwarf() && "No split dwarf?");
  2919. MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
  2920. InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
  2921. OffSec, /* UseRelativeOffsets = */ false);
  2922. }
  2923. // Emit address pool.
  2924. void DwarfDebug::emitDebugAddr() {
  2925. AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
  2926. }
  2927. MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
  2928. if (!useSplitDwarf())
  2929. return nullptr;
  2930. const DICompileUnit *DIUnit = CU.getCUNode();
  2931. SplitTypeUnitFileTable.maybeSetRootFile(
  2932. DIUnit->getDirectory(), DIUnit->getFilename(),
  2933. getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
  2934. return &SplitTypeUnitFileTable;
  2935. }
  2936. uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
  2937. MD5 Hash;
  2938. Hash.update(Identifier);
  2939. // ... take the least significant 8 bytes and return those. Our MD5
  2940. // implementation always returns its results in little endian, so we actually
  2941. // need the "high" word.
  2942. MD5::MD5Result Result;
  2943. Hash.final(Result);
  2944. return Result.high();
  2945. }
  2946. void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
  2947. StringRef Identifier, DIE &RefDie,
  2948. const DICompositeType *CTy) {
  2949. // Fast path if we're building some type units and one has already used the
  2950. // address pool we know we're going to throw away all this work anyway, so
  2951. // don't bother building dependent types.
  2952. if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
  2953. return;
  2954. auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
  2955. if (!Ins.second) {
  2956. CU.addDIETypeSignature(RefDie, Ins.first->second);
  2957. return;
  2958. }
  2959. bool TopLevelType = TypeUnitsUnderConstruction.empty();
  2960. AddrPool.resetUsedFlag();
  2961. auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
  2962. getDwoLineTable(CU));
  2963. DwarfTypeUnit &NewTU = *OwnedUnit;
  2964. DIE &UnitDie = NewTU.getUnitDie();
  2965. TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
  2966. NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  2967. CU.getLanguage());
  2968. uint64_t Signature = makeTypeSignature(Identifier);
  2969. NewTU.setTypeSignature(Signature);
  2970. Ins.first->second = Signature;
  2971. if (useSplitDwarf()) {
  2972. MCSection *Section =
  2973. getDwarfVersion() <= 4
  2974. ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
  2975. : Asm->getObjFileLowering().getDwarfInfoDWOSection();
  2976. NewTU.setSection(Section);
  2977. } else {
  2978. MCSection *Section =
  2979. getDwarfVersion() <= 4
  2980. ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
  2981. : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
  2982. NewTU.setSection(Section);
  2983. // Non-split type units reuse the compile unit's line table.
  2984. CU.applyStmtList(UnitDie);
  2985. }
  2986. // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
  2987. // units.
  2988. if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
  2989. NewTU.addStringOffsetsStart();
  2990. NewTU.setType(NewTU.createTypeDIE(CTy));
  2991. if (TopLevelType) {
  2992. auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
  2993. TypeUnitsUnderConstruction.clear();
  2994. // Types referencing entries in the address table cannot be placed in type
  2995. // units.
  2996. if (AddrPool.hasBeenUsed()) {
  2997. // Remove all the types built while building this type.
  2998. // This is pessimistic as some of these types might not be dependent on
  2999. // the type that used an address.
  3000. for (const auto &TU : TypeUnitsToAdd)
  3001. TypeSignatures.erase(TU.second);
  3002. // Construct this type in the CU directly.
  3003. // This is inefficient because all the dependent types will be rebuilt
  3004. // from scratch, including building them in type units, discovering that
  3005. // they depend on addresses, throwing them out and rebuilding them.
  3006. CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
  3007. return;
  3008. }
  3009. // If the type wasn't dependent on fission addresses, finish adding the type
  3010. // and all its dependent types.
  3011. for (auto &TU : TypeUnitsToAdd) {
  3012. InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
  3013. InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
  3014. }
  3015. }
  3016. CU.addDIETypeSignature(RefDie, Signature);
  3017. }
  3018. // Add the Name along with its companion DIE to the appropriate accelerator
  3019. // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
  3020. // AccelTableKind::Apple, we use the table we got as an argument). If
  3021. // accelerator tables are disabled, this function does nothing.
  3022. template <typename DataT>
  3023. void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
  3024. AccelTable<DataT> &AppleAccel, StringRef Name,
  3025. const DIE &Die) {
  3026. if (getAccelTableKind() == AccelTableKind::None)
  3027. return;
  3028. if (getAccelTableKind() != AccelTableKind::Apple &&
  3029. CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
  3030. return;
  3031. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  3032. DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
  3033. switch (getAccelTableKind()) {
  3034. case AccelTableKind::Apple:
  3035. AppleAccel.addName(Ref, Die);
  3036. break;
  3037. case AccelTableKind::Dwarf:
  3038. AccelDebugNames.addName(Ref, Die);
  3039. break;
  3040. case AccelTableKind::Default:
  3041. llvm_unreachable("Default should have already been resolved.");
  3042. case AccelTableKind::None:
  3043. llvm_unreachable("None handled above");
  3044. }
  3045. }
  3046. void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
  3047. const DIE &Die) {
  3048. addAccelNameImpl(CU, AccelNames, Name, Die);
  3049. }
  3050. void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
  3051. const DIE &Die) {
  3052. // ObjC names go only into the Apple accelerator tables.
  3053. if (getAccelTableKind() == AccelTableKind::Apple)
  3054. addAccelNameImpl(CU, AccelObjC, Name, Die);
  3055. }
  3056. void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
  3057. const DIE &Die) {
  3058. addAccelNameImpl(CU, AccelNamespace, Name, Die);
  3059. }
  3060. void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
  3061. const DIE &Die, char Flags) {
  3062. addAccelNameImpl(CU, AccelTypes, Name, Die);
  3063. }
  3064. uint16_t DwarfDebug::getDwarfVersion() const {
  3065. return Asm->OutStreamer->getContext().getDwarfVersion();
  3066. }
  3067. dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const {
  3068. if (Asm->getDwarfVersion() >= 4)
  3069. return dwarf::Form::DW_FORM_sec_offset;
  3070. assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
  3071. "DWARF64 is not defined prior DWARFv3");
  3072. return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
  3073. : dwarf::Form::DW_FORM_data4;
  3074. }
  3075. const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
  3076. auto I = SectionLabels.find(S);
  3077. if (I == SectionLabels.end())
  3078. return nullptr;
  3079. return I->second;
  3080. }
  3081. void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
  3082. if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
  3083. if (useSplitDwarf() || getDwarfVersion() >= 5)
  3084. AddrPool.getIndex(S);
  3085. }
  3086. std::optional<MD5::MD5Result>
  3087. DwarfDebug::getMD5AsBytes(const DIFile *File) const {
  3088. assert(File);
  3089. if (getDwarfVersion() < 5)
  3090. return std::nullopt;
  3091. std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
  3092. if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
  3093. return std::nullopt;
  3094. // Convert the string checksum to an MD5Result for the streamer.
  3095. // The verifier validates the checksum so we assume it's okay.
  3096. // An MD5 checksum is 16 bytes.
  3097. std::string ChecksumString = fromHex(Checksum->Value);
  3098. MD5::MD5Result CKMem;
  3099. std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());
  3100. return CKMem;
  3101. }