DwarfDebug.cpp 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598
  1. //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains support for writing dwarf debug info into asm files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "DwarfDebug.h"
  14. #include "ByteStreamer.h"
  15. #include "DIEHash.h"
  16. #include "DebugLocEntry.h"
  17. #include "DebugLocStream.h"
  18. #include "DwarfCompileUnit.h"
  19. #include "DwarfExpression.h"
  20. #include "DwarfFile.h"
  21. #include "DwarfUnit.h"
  22. #include "llvm/ADT/APInt.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/DenseSet.h"
  25. #include "llvm/ADT/MapVector.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/StringRef.h"
  29. #include "llvm/ADT/Triple.h"
  30. #include "llvm/ADT/Twine.h"
  31. #include "llvm/BinaryFormat/Dwarf.h"
  32. #include "llvm/CodeGen/AccelTable.h"
  33. #include "llvm/CodeGen/AsmPrinter.h"
  34. #include "llvm/CodeGen/DIE.h"
  35. #include "llvm/CodeGen/LexicalScopes.h"
  36. #include "llvm/CodeGen/MachineBasicBlock.h"
  37. #include "llvm/CodeGen/MachineFunction.h"
  38. #include "llvm/CodeGen/MachineInstr.h"
  39. #include "llvm/CodeGen/MachineModuleInfo.h"
  40. #include "llvm/CodeGen/MachineOperand.h"
  41. #include "llvm/CodeGen/TargetInstrInfo.h"
  42. #include "llvm/CodeGen/TargetRegisterInfo.h"
  43. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  44. #include "llvm/IR/Constants.h"
  45. #include "llvm/IR/DebugInfoMetadata.h"
  46. #include "llvm/IR/DebugLoc.h"
  47. #include "llvm/IR/Function.h"
  48. #include "llvm/IR/GlobalVariable.h"
  49. #include "llvm/IR/Module.h"
  50. #include "llvm/MC/MCAsmInfo.h"
  51. #include "llvm/MC/MCContext.h"
  52. #include "llvm/MC/MCDwarf.h"
  53. #include "llvm/MC/MCSection.h"
  54. #include "llvm/MC/MCStreamer.h"
  55. #include "llvm/MC/MCSymbol.h"
  56. #include "llvm/MC/MCTargetOptions.h"
  57. #include "llvm/MC/MachineLocation.h"
  58. #include "llvm/MC/SectionKind.h"
  59. #include "llvm/Pass.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/Debug.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include "llvm/Support/MD5.h"
  65. #include "llvm/Support/MathExtras.h"
  66. #include "llvm/Support/Timer.h"
  67. #include "llvm/Support/raw_ostream.h"
  68. #include "llvm/Target/TargetLoweringObjectFile.h"
  69. #include "llvm/Target/TargetMachine.h"
  70. #include "llvm/Target/TargetOptions.h"
  71. #include <algorithm>
  72. #include <cassert>
  73. #include <cstddef>
  74. #include <cstdint>
  75. #include <iterator>
  76. #include <string>
  77. #include <utility>
  78. #include <vector>
  79. using namespace llvm;
  80. #define DEBUG_TYPE "dwarfdebug"
  81. static cl::opt<bool>
  82. DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
  83. cl::desc("Disable debug info printing"));
  84. static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
  85. "use-dwarf-ranges-base-address-specifier", cl::Hidden,
  86. cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
  87. static cl::opt<bool> GenerateARangeSection("generate-arange-section",
  88. cl::Hidden,
  89. cl::desc("Generate dwarf aranges"),
  90. cl::init(false));
  91. static cl::opt<bool>
  92. GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
  93. cl::desc("Generate DWARF4 type units."),
  94. cl::init(false));
  95. static cl::opt<bool> SplitDwarfCrossCuReferences(
  96. "split-dwarf-cross-cu-references", cl::Hidden,
  97. cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
  98. enum DefaultOnOff { Default, Enable, Disable };
  99. static cl::opt<DefaultOnOff> UnknownLocations(
  100. "use-unknown-locations", cl::Hidden,
  101. cl::desc("Make an absence of debug location information explicit."),
  102. cl::values(clEnumVal(Default, "At top of block or after label"),
  103. clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
  104. cl::init(Default));
  105. static cl::opt<AccelTableKind> AccelTables(
  106. "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
  107. cl::values(clEnumValN(AccelTableKind::Default, "Default",
  108. "Default for platform"),
  109. clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
  110. clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
  111. clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
  112. cl::init(AccelTableKind::Default));
  113. static cl::opt<DefaultOnOff>
  114. DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
  115. cl::desc("Use inlined strings rather than string section."),
  116. cl::values(clEnumVal(Default, "Default for platform"),
  117. clEnumVal(Enable, "Enabled"),
  118. clEnumVal(Disable, "Disabled")),
  119. cl::init(Default));
  120. static cl::opt<bool>
  121. NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
  122. cl::desc("Disable emission .debug_ranges section."),
  123. cl::init(false));
  124. static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
  125. "dwarf-sections-as-references", cl::Hidden,
  126. cl::desc("Use sections+offset as references rather than labels."),
  127. cl::values(clEnumVal(Default, "Default for platform"),
  128. clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
  129. cl::init(Default));
  130. enum LinkageNameOption {
  131. DefaultLinkageNames,
  132. AllLinkageNames,
  133. AbstractLinkageNames
  134. };
  135. static cl::opt<LinkageNameOption>
  136. DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
  137. cl::desc("Which DWARF linkage-name attributes to emit."),
  138. cl::values(clEnumValN(DefaultLinkageNames, "Default",
  139. "Default for platform"),
  140. clEnumValN(AllLinkageNames, "All", "All"),
  141. clEnumValN(AbstractLinkageNames, "Abstract",
  142. "Abstract subprograms")),
  143. cl::init(DefaultLinkageNames));
  144. static const char *const DWARFGroupName = "dwarf";
  145. static const char *const DWARFGroupDescription = "DWARF Emission";
  146. static const char *const DbgTimerName = "writer";
  147. static const char *const DbgTimerDescription = "DWARF Debug Writer";
  148. void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
  149. BS.EmitInt8(
  150. Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
  151. : dwarf::OperationEncodingString(Op));
  152. }
  153. void DebugLocDwarfExpression::emitSigned(int64_t Value) {
  154. BS.EmitSLEB128(Value, Twine(Value));
  155. }
  156. void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
  157. BS.EmitULEB128(Value, Twine(Value));
  158. }
  159. bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
  160. unsigned MachineReg) {
  161. // This information is not available while emitting .debug_loc entries.
  162. return false;
  163. }
  164. bool DbgVariable::isBlockByrefVariable() const {
  165. assert(getVariable() && "Invalid complex DbgVariable!");
  166. return getVariable()->getType().resolve()->isBlockByrefStruct();
  167. }
  168. const DIType *DbgVariable::getType() const {
  169. DIType *Ty = getVariable()->getType().resolve();
  170. // FIXME: isBlockByrefVariable should be reformulated in terms of complex
  171. // addresses instead.
  172. if (Ty->isBlockByrefStruct()) {
  173. /* Byref variables, in Blocks, are declared by the programmer as
  174. "SomeType VarName;", but the compiler creates a
  175. __Block_byref_x_VarName struct, and gives the variable VarName
  176. either the struct, or a pointer to the struct, as its type. This
  177. is necessary for various behind-the-scenes things the compiler
  178. needs to do with by-reference variables in blocks.
  179. However, as far as the original *programmer* is concerned, the
  180. variable should still have type 'SomeType', as originally declared.
  181. The following function dives into the __Block_byref_x_VarName
  182. struct to find the original type of the variable. This will be
  183. passed back to the code generating the type for the Debug
  184. Information Entry for the variable 'VarName'. 'VarName' will then
  185. have the original type 'SomeType' in its debug information.
  186. The original type 'SomeType' will be the type of the field named
  187. 'VarName' inside the __Block_byref_x_VarName struct.
  188. NOTE: In order for this to not completely fail on the debugger
  189. side, the Debug Information Entry for the variable VarName needs to
  190. have a DW_AT_location that tells the debugger how to unwind through
  191. the pointers and __Block_byref_x_VarName struct to find the actual
  192. value of the variable. The function addBlockByrefType does this. */
  193. DIType *subType = Ty;
  194. uint16_t tag = Ty->getTag();
  195. if (tag == dwarf::DW_TAG_pointer_type)
  196. subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
  197. auto Elements = cast<DICompositeType>(subType)->getElements();
  198. for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
  199. auto *DT = cast<DIDerivedType>(Elements[i]);
  200. if (getName() == DT->getName())
  201. return resolve(DT->getBaseType());
  202. }
  203. }
  204. return Ty;
  205. }
  206. ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
  207. if (FrameIndexExprs.size() == 1)
  208. return FrameIndexExprs;
  209. assert(llvm::all_of(FrameIndexExprs,
  210. [](const FrameIndexExpr &A) {
  211. return A.Expr->isFragment();
  212. }) &&
  213. "multiple FI expressions without DW_OP_LLVM_fragment");
  214. llvm::sort(FrameIndexExprs,
  215. [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
  216. return A.Expr->getFragmentInfo()->OffsetInBits <
  217. B.Expr->getFragmentInfo()->OffsetInBits;
  218. });
  219. return FrameIndexExprs;
  220. }
  221. void DbgVariable::addMMIEntry(const DbgVariable &V) {
  222. assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
  223. assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
  224. assert(V.getVariable() == getVariable() && "conflicting variable");
  225. assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
  226. assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
  227. assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
  228. // FIXME: This logic should not be necessary anymore, as we now have proper
  229. // deduplication. However, without it, we currently run into the assertion
  230. // below, which means that we are likely dealing with broken input, i.e. two
  231. // non-fragment entries for the same variable at different frame indices.
  232. if (FrameIndexExprs.size()) {
  233. auto *Expr = FrameIndexExprs.back().Expr;
  234. if (!Expr || !Expr->isFragment())
  235. return;
  236. }
  237. for (const auto &FIE : V.FrameIndexExprs)
  238. // Ignore duplicate entries.
  239. if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
  240. return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
  241. }))
  242. FrameIndexExprs.push_back(FIE);
  243. assert((FrameIndexExprs.size() == 1 ||
  244. llvm::all_of(FrameIndexExprs,
  245. [](FrameIndexExpr &FIE) {
  246. return FIE.Expr && FIE.Expr->isFragment();
  247. })) &&
  248. "conflicting locations for variable");
  249. }
  250. static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
  251. bool GenerateTypeUnits,
  252. DebuggerKind Tuning,
  253. const Triple &TT) {
  254. // Honor an explicit request.
  255. if (AccelTables != AccelTableKind::Default)
  256. return AccelTables;
  257. // Accelerator tables with type units are currently not supported.
  258. if (GenerateTypeUnits)
  259. return AccelTableKind::None;
  260. // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
  261. // always implies debug_names. For lower standard versions we use apple
  262. // accelerator tables on apple platforms and debug_names elsewhere.
  263. if (DwarfVersion >= 5)
  264. return AccelTableKind::Dwarf;
  265. if (Tuning == DebuggerKind::LLDB)
  266. return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
  267. : AccelTableKind::Dwarf;
  268. return AccelTableKind::None;
  269. }
  270. DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
  271. : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
  272. InfoHolder(A, "info_string", DIEValueAllocator),
  273. SkeletonHolder(A, "skel_string", DIEValueAllocator),
  274. IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
  275. const Triple &TT = Asm->TM.getTargetTriple();
  276. // Make sure we know our "debugger tuning." The target option takes
  277. // precedence; fall back to triple-based defaults.
  278. if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
  279. DebuggerTuning = Asm->TM.Options.DebuggerTuning;
  280. else if (IsDarwin)
  281. DebuggerTuning = DebuggerKind::LLDB;
  282. else if (TT.isPS4CPU())
  283. DebuggerTuning = DebuggerKind::SCE;
  284. else
  285. DebuggerTuning = DebuggerKind::GDB;
  286. if (DwarfInlinedStrings == Default)
  287. UseInlineStrings = TT.isNVPTX();
  288. else
  289. UseInlineStrings = DwarfInlinedStrings == Enable;
  290. UseLocSection = !TT.isNVPTX();
  291. HasAppleExtensionAttributes = tuneForLLDB();
  292. // Handle split DWARF.
  293. HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
  294. // SCE defaults to linkage names only for abstract subprograms.
  295. if (DwarfLinkageNames == DefaultLinkageNames)
  296. UseAllLinkageNames = !tuneForSCE();
  297. else
  298. UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
  299. unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
  300. unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
  301. : MMI->getModule()->getDwarfVersion();
  302. // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
  303. DwarfVersion =
  304. TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
  305. UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
  306. // Use sections as references. Force for NVPTX.
  307. if (DwarfSectionsAsReferences == Default)
  308. UseSectionsAsReferences = TT.isNVPTX();
  309. else
  310. UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
  311. // Don't generate type units for unsupported object file formats.
  312. GenerateTypeUnits =
  313. A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
  314. TheAccelTableKind = computeAccelTableKind(
  315. DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
  316. // Work around a GDB bug. GDB doesn't support the standard opcode;
  317. // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
  318. // is defined as of DWARF 3.
  319. // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
  320. // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
  321. UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
  322. // GDB does not fully support the DWARF 4 representation for bitfields.
  323. UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
  324. // The DWARF v5 string offsets table has - possibly shared - contributions
  325. // from each compile and type unit each preceded by a header. The string
  326. // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
  327. // a monolithic string offsets table without any header.
  328. UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
  329. Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
  330. }
  331. // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
  332. DwarfDebug::~DwarfDebug() = default;
  333. static bool isObjCClass(StringRef Name) {
  334. return Name.startswith("+") || Name.startswith("-");
  335. }
  336. static bool hasObjCCategory(StringRef Name) {
  337. if (!isObjCClass(Name))
  338. return false;
  339. return Name.find(") ") != StringRef::npos;
  340. }
  341. static void getObjCClassCategory(StringRef In, StringRef &Class,
  342. StringRef &Category) {
  343. if (!hasObjCCategory(In)) {
  344. Class = In.slice(In.find('[') + 1, In.find(' '));
  345. Category = "";
  346. return;
  347. }
  348. Class = In.slice(In.find('[') + 1, In.find('('));
  349. Category = In.slice(In.find('[') + 1, In.find(' '));
  350. }
  351. static StringRef getObjCMethodName(StringRef In) {
  352. return In.slice(In.find(' ') + 1, In.find(']'));
  353. }
  354. // Add the various names to the Dwarf accelerator table names.
  355. void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
  356. const DISubprogram *SP, DIE &Die) {
  357. if (getAccelTableKind() != AccelTableKind::Apple &&
  358. CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
  359. return;
  360. if (!SP->isDefinition())
  361. return;
  362. if (SP->getName() != "")
  363. addAccelName(CU, SP->getName(), Die);
  364. // If the linkage name is different than the name, go ahead and output that as
  365. // well into the name table. Only do that if we are going to actually emit
  366. // that name.
  367. if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
  368. (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
  369. addAccelName(CU, SP->getLinkageName(), Die);
  370. // If this is an Objective-C selector name add it to the ObjC accelerator
  371. // too.
  372. if (isObjCClass(SP->getName())) {
  373. StringRef Class, Category;
  374. getObjCClassCategory(SP->getName(), Class, Category);
  375. addAccelObjC(CU, Class, Die);
  376. if (Category != "")
  377. addAccelObjC(CU, Category, Die);
  378. // Also add the base method name to the name table.
  379. addAccelName(CU, getObjCMethodName(SP->getName()), Die);
  380. }
  381. }
  382. /// Check whether we should create a DIE for the given Scope, return true
  383. /// if we don't create a DIE (the corresponding DIE is null).
  384. bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
  385. if (Scope->isAbstractScope())
  386. return false;
  387. // We don't create a DIE if there is no Range.
  388. const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
  389. if (Ranges.empty())
  390. return true;
  391. if (Ranges.size() > 1)
  392. return false;
  393. // We don't create a DIE if we have a single Range and the end label
  394. // is null.
  395. return !getLabelAfterInsn(Ranges.front().second);
  396. }
  397. template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
  398. F(CU);
  399. if (auto *SkelCU = CU.getSkeleton())
  400. if (CU.getCUNode()->getSplitDebugInlining())
  401. F(*SkelCU);
  402. }
  403. bool DwarfDebug::shareAcrossDWOCUs() const {
  404. return SplitDwarfCrossCuReferences;
  405. }
  406. void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
  407. LexicalScope *Scope) {
  408. assert(Scope && Scope->getScopeNode());
  409. assert(Scope->isAbstractScope());
  410. assert(!Scope->getInlinedAt());
  411. auto *SP = cast<DISubprogram>(Scope->getScopeNode());
  412. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  413. // was inlined from another compile unit.
  414. if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
  415. // Avoid building the original CU if it won't be used
  416. SrcCU.constructAbstractSubprogramScopeDIE(Scope);
  417. else {
  418. auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
  419. if (auto *SkelCU = CU.getSkeleton()) {
  420. (shareAcrossDWOCUs() ? CU : SrcCU)
  421. .constructAbstractSubprogramScopeDIE(Scope);
  422. if (CU.getCUNode()->getSplitDebugInlining())
  423. SkelCU->constructAbstractSubprogramScopeDIE(Scope);
  424. } else
  425. CU.constructAbstractSubprogramScopeDIE(Scope);
  426. }
  427. }
  428. void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
  429. DwarfCompileUnit &CU, DIE &ScopeDIE,
  430. const MachineFunction &MF) {
  431. // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
  432. // the subprogram is required to have one.
  433. if (!SP.areAllCallsDescribed() || !SP.isDefinition())
  434. return;
  435. // Use DW_AT_call_all_calls to express that call site entries are present
  436. // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
  437. // because one of its requirements is not met: call site entries for
  438. // optimized-out calls are elided.
  439. CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls);
  440. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  441. assert(TII && "TargetInstrInfo not found: cannot label tail calls");
  442. // Emit call site entries for each call or tail call in the function.
  443. for (const MachineBasicBlock &MBB : MF) {
  444. for (const MachineInstr &MI : MBB.instrs()) {
  445. // Skip instructions which aren't calls. Both calls and tail-calling jump
  446. // instructions (e.g TAILJMPd64) are classified correctly here.
  447. if (!MI.isCall())
  448. continue;
  449. // TODO: Add support for targets with delay slots (see: beginInstruction).
  450. if (MI.hasDelaySlot())
  451. return;
  452. // If this is a direct call, find the callee's subprogram.
  453. const MachineOperand &CalleeOp = MI.getOperand(0);
  454. if (!CalleeOp.isGlobal())
  455. continue;
  456. const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
  457. if (!CalleeDecl || !CalleeDecl->getSubprogram())
  458. continue;
  459. // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
  460. // TODO: Add support for indirect calls.
  461. bool IsTail = TII->isTailCall(MI);
  462. // For tail calls, no return PC information is needed. For regular calls,
  463. // the return PC is needed to disambiguate paths in the call graph which
  464. // could lead to some target function.
  465. const MCSymbol *ReturnPC = IsTail ? nullptr : getLabelAfterInsn(&MI);
  466. assert((IsTail || ReturnPC) && "Call without return PC information");
  467. LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
  468. << CalleeDecl->getName() << (IsTail ? " [tail]" : "")
  469. << "\n");
  470. CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(),
  471. IsTail, ReturnPC);
  472. }
  473. }
  474. }
  475. void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
  476. if (!U.hasDwarfPubSections())
  477. return;
  478. U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
  479. }
  480. // Create new DwarfCompileUnit for the given metadata node with tag
  481. // DW_TAG_compile_unit.
  482. DwarfCompileUnit &
  483. DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
  484. if (auto *CU = CUMap.lookup(DIUnit))
  485. return *CU;
  486. StringRef FN = DIUnit->getFilename();
  487. CompilationDir = DIUnit->getDirectory();
  488. auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
  489. InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
  490. DwarfCompileUnit &NewCU = *OwnedUnit;
  491. DIE &Die = NewCU.getUnitDie();
  492. InfoHolder.addUnit(std::move(OwnedUnit));
  493. if (useSplitDwarf()) {
  494. NewCU.setSkeleton(constructSkeletonCU(NewCU));
  495. NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
  496. Asm->TM.Options.MCOptions.SplitDwarfFile);
  497. }
  498. for (auto *IE : DIUnit->getImportedEntities())
  499. NewCU.addImportedEntity(IE);
  500. // LTO with assembly output shares a single line table amongst multiple CUs.
  501. // To avoid the compilation directory being ambiguous, let the line table
  502. // explicitly describe the directory of all files, never relying on the
  503. // compilation directory.
  504. if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
  505. Asm->OutStreamer->emitDwarfFile0Directive(
  506. CompilationDir, FN, NewCU.getMD5AsBytes(DIUnit->getFile()),
  507. DIUnit->getSource(), NewCU.getUniqueID());
  508. StringRef Producer = DIUnit->getProducer();
  509. StringRef Flags = DIUnit->getFlags();
  510. if (!Flags.empty() && !useAppleExtensionAttributes()) {
  511. std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
  512. NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
  513. } else
  514. NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
  515. NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  516. DIUnit->getSourceLanguage());
  517. NewCU.addString(Die, dwarf::DW_AT_name, FN);
  518. // Add DW_str_offsets_base to the unit DIE, except for split units.
  519. if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
  520. NewCU.addStringOffsetsStart();
  521. if (!useSplitDwarf()) {
  522. NewCU.initStmtList();
  523. // If we're using split dwarf the compilation dir is going to be in the
  524. // skeleton CU and so we don't need to duplicate it here.
  525. if (!CompilationDir.empty())
  526. NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  527. addGnuPubAttributes(NewCU, Die);
  528. }
  529. if (useAppleExtensionAttributes()) {
  530. if (DIUnit->isOptimized())
  531. NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
  532. StringRef Flags = DIUnit->getFlags();
  533. if (!Flags.empty())
  534. NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
  535. if (unsigned RVer = DIUnit->getRuntimeVersion())
  536. NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
  537. dwarf::DW_FORM_data1, RVer);
  538. }
  539. if (useSplitDwarf())
  540. NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
  541. else
  542. NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
  543. if (DIUnit->getDWOId()) {
  544. // This CU is either a clang module DWO or a skeleton CU.
  545. NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
  546. DIUnit->getDWOId());
  547. if (!DIUnit->getSplitDebugFilename().empty())
  548. // This is a prefabricated skeleton CU.
  549. NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
  550. DIUnit->getSplitDebugFilename());
  551. }
  552. CUMap.insert({DIUnit, &NewCU});
  553. CUDieMap.insert({&Die, &NewCU});
  554. return NewCU;
  555. }
  556. void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
  557. const DIImportedEntity *N) {
  558. if (isa<DILocalScope>(N->getScope()))
  559. return;
  560. if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
  561. D->addChild(TheCU.constructImportedEntityDIE(N));
  562. }
  563. /// Sort and unique GVEs by comparing their fragment offset.
  564. static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
  565. sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
  566. llvm::sort(
  567. GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
  568. // Sort order: first null exprs, then exprs without fragment
  569. // info, then sort by fragment offset in bits.
  570. // FIXME: Come up with a more comprehensive comparator so
  571. // the sorting isn't non-deterministic, and so the following
  572. // std::unique call works correctly.
  573. if (!A.Expr || !B.Expr)
  574. return !!B.Expr;
  575. auto FragmentA = A.Expr->getFragmentInfo();
  576. auto FragmentB = B.Expr->getFragmentInfo();
  577. if (!FragmentA || !FragmentB)
  578. return !!FragmentB;
  579. return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
  580. });
  581. GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
  582. [](DwarfCompileUnit::GlobalExpr A,
  583. DwarfCompileUnit::GlobalExpr B) {
  584. return A.Expr == B.Expr;
  585. }),
  586. GVEs.end());
  587. return GVEs;
  588. }
  589. // Emit all Dwarf sections that should come prior to the content. Create
  590. // global DIEs and emit initial debug info sections. This is invoked by
  591. // the target AsmPrinter.
  592. void DwarfDebug::beginModule() {
  593. NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
  594. DWARFGroupDescription, TimePassesIsEnabled);
  595. if (DisableDebugInfoPrinting)
  596. return;
  597. const Module *M = MMI->getModule();
  598. unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
  599. M->debug_compile_units_end());
  600. // Tell MMI whether we have debug info.
  601. MMI->setDebugInfoAvailability(NumDebugCUs > 0);
  602. SingleCU = NumDebugCUs == 1;
  603. DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
  604. GVMap;
  605. for (const GlobalVariable &Global : M->globals()) {
  606. SmallVector<DIGlobalVariableExpression *, 1> GVs;
  607. Global.getDebugInfo(GVs);
  608. for (auto *GVE : GVs)
  609. GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
  610. }
  611. // Create the symbol that designates the start of the unit's contribution
  612. // to the string offsets table. In a split DWARF scenario, only the skeleton
  613. // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
  614. if (useSegmentedStringOffsetsTable())
  615. (useSplitDwarf() ? SkeletonHolder : InfoHolder)
  616. .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
  617. // Create the symbol that designates the start of the DWARF v5 range list
  618. // table. It is located past the header and before the offsets table.
  619. if (getDwarfVersion() >= 5) {
  620. (useSplitDwarf() ? SkeletonHolder : InfoHolder)
  621. .setRnglistsTableBaseSym(Asm->createTempSymbol("rnglists_table_base"));
  622. if (useSplitDwarf())
  623. InfoHolder.setRnglistsTableBaseSym(
  624. Asm->createTempSymbol("rnglists_dwo_table_base"));
  625. }
  626. // Create the symbol that points to the first entry following the debug
  627. // address table (.debug_addr) header.
  628. AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
  629. for (DICompileUnit *CUNode : M->debug_compile_units()) {
  630. // FIXME: Move local imported entities into a list attached to the
  631. // subprogram, then this search won't be needed and a
  632. // getImportedEntities().empty() test should go below with the rest.
  633. bool HasNonLocalImportedEntities = llvm::any_of(
  634. CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
  635. return !isa<DILocalScope>(IE->getScope());
  636. });
  637. if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
  638. CUNode->getRetainedTypes().empty() &&
  639. CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
  640. continue;
  641. DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
  642. // Global Variables.
  643. for (auto *GVE : CUNode->getGlobalVariables()) {
  644. // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
  645. // already know about the variable and it isn't adding a constant
  646. // expression.
  647. auto &GVMapEntry = GVMap[GVE->getVariable()];
  648. auto *Expr = GVE->getExpression();
  649. if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
  650. GVMapEntry.push_back({nullptr, Expr});
  651. }
  652. DenseSet<DIGlobalVariable *> Processed;
  653. for (auto *GVE : CUNode->getGlobalVariables()) {
  654. DIGlobalVariable *GV = GVE->getVariable();
  655. if (Processed.insert(GV).second)
  656. CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
  657. }
  658. for (auto *Ty : CUNode->getEnumTypes()) {
  659. // The enum types array by design contains pointers to
  660. // MDNodes rather than DIRefs. Unique them here.
  661. CU.getOrCreateTypeDIE(cast<DIType>(Ty));
  662. }
  663. for (auto *Ty : CUNode->getRetainedTypes()) {
  664. // The retained types array by design contains pointers to
  665. // MDNodes rather than DIRefs. Unique them here.
  666. if (DIType *RT = dyn_cast<DIType>(Ty))
  667. // There is no point in force-emitting a forward declaration.
  668. CU.getOrCreateTypeDIE(RT);
  669. }
  670. // Emit imported_modules last so that the relevant context is already
  671. // available.
  672. for (auto *IE : CUNode->getImportedEntities())
  673. constructAndAddImportedEntityDIE(CU, IE);
  674. }
  675. }
  676. void DwarfDebug::finishEntityDefinitions() {
  677. for (const auto &Entity : ConcreteEntities) {
  678. DIE *Die = Entity->getDIE();
  679. assert(Die);
  680. // FIXME: Consider the time-space tradeoff of just storing the unit pointer
  681. // in the ConcreteEntities list, rather than looking it up again here.
  682. // DIE::getUnit isn't simple - it walks parent pointers, etc.
  683. DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
  684. assert(Unit);
  685. Unit->finishEntityDefinition(Entity.get());
  686. }
  687. }
  688. void DwarfDebug::finishSubprogramDefinitions() {
  689. for (const DISubprogram *SP : ProcessedSPNodes) {
  690. assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
  691. forBothCUs(
  692. getOrCreateDwarfCompileUnit(SP->getUnit()),
  693. [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
  694. }
  695. }
  696. void DwarfDebug::finalizeModuleInfo() {
  697. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  698. finishSubprogramDefinitions();
  699. finishEntityDefinitions();
  700. // Include the DWO file name in the hash if there's more than one CU.
  701. // This handles ThinLTO's situation where imported CUs may very easily be
  702. // duplicate with the same CU partially imported into another ThinLTO unit.
  703. StringRef DWOName;
  704. if (CUMap.size() > 1)
  705. DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
  706. // Handle anything that needs to be done on a per-unit basis after
  707. // all other generation.
  708. for (const auto &P : CUMap) {
  709. auto &TheCU = *P.second;
  710. if (TheCU.getCUNode()->isDebugDirectivesOnly())
  711. continue;
  712. // Emit DW_AT_containing_type attribute to connect types with their
  713. // vtable holding type.
  714. TheCU.constructContainingTypeDIEs();
  715. // Add CU specific attributes if we need to add any.
  716. // If we're splitting the dwarf out now that we've got the entire
  717. // CU then add the dwo id to it.
  718. auto *SkCU = TheCU.getSkeleton();
  719. if (useSplitDwarf()) {
  720. // Emit a unique identifier for this CU.
  721. uint64_t ID =
  722. DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
  723. if (getDwarfVersion() >= 5) {
  724. TheCU.setDWOId(ID);
  725. SkCU->setDWOId(ID);
  726. } else {
  727. TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  728. dwarf::DW_FORM_data8, ID);
  729. SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  730. dwarf::DW_FORM_data8, ID);
  731. }
  732. if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
  733. const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
  734. SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
  735. Sym, Sym);
  736. }
  737. }
  738. // If we have code split among multiple sections or non-contiguous
  739. // ranges of code then emit a DW_AT_ranges attribute on the unit that will
  740. // remain in the .o file, otherwise add a DW_AT_low_pc.
  741. // FIXME: We should use ranges allow reordering of code ala
  742. // .subsections_via_symbols in mach-o. This would mean turning on
  743. // ranges for all subprogram DIEs for mach-o.
  744. DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
  745. // We don't keep track of which addresses are used in which CU so this
  746. // is a bit pessimistic under LTO.
  747. if (!AddrPool.isEmpty())
  748. U.addAddrTableBase();
  749. if (unsigned NumRanges = TheCU.getRanges().size()) {
  750. if (NumRanges > 1 && useRangesSection())
  751. // A DW_AT_low_pc attribute may also be specified in combination with
  752. // DW_AT_ranges to specify the default base address for use in
  753. // location lists (see Section 2.6.2) and range lists (see Section
  754. // 2.17.3).
  755. U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
  756. else
  757. U.setBaseAddress(TheCU.getRanges().front().getStart());
  758. U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
  759. }
  760. if (getDwarfVersion() >= 5 && U.hasRangeLists())
  761. U.addRnglistsBase();
  762. auto *CUNode = cast<DICompileUnit>(P.first);
  763. // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
  764. if (CUNode->getMacros())
  765. U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
  766. U.getMacroLabelBegin(),
  767. TLOF.getDwarfMacinfoSection()->getBeginSymbol());
  768. }
  769. // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
  770. for (auto *CUNode : MMI->getModule()->debug_compile_units())
  771. if (CUNode->getDWOId())
  772. getOrCreateDwarfCompileUnit(CUNode);
  773. // Compute DIE offsets and sizes.
  774. InfoHolder.computeSizeAndOffsets();
  775. if (useSplitDwarf())
  776. SkeletonHolder.computeSizeAndOffsets();
  777. }
  778. // Emit all Dwarf sections that should come after the content.
  779. void DwarfDebug::endModule() {
  780. assert(CurFn == nullptr);
  781. assert(CurMI == nullptr);
  782. // If we aren't actually generating debug info (check beginModule -
  783. // conditionalized on !DisableDebugInfoPrinting and the presence of the
  784. // llvm.dbg.cu metadata node)
  785. if (!MMI->hasDebugInfo())
  786. return;
  787. // Finalize the debug info for the module.
  788. finalizeModuleInfo();
  789. emitDebugStr();
  790. if (useSplitDwarf())
  791. emitDebugLocDWO();
  792. else
  793. // Emit info into a debug loc section.
  794. emitDebugLoc();
  795. // Corresponding abbreviations into a abbrev section.
  796. emitAbbreviations();
  797. // Emit all the DIEs into a debug info section.
  798. emitDebugInfo();
  799. // Emit info into a debug aranges section.
  800. if (GenerateARangeSection)
  801. emitDebugARanges();
  802. // Emit info into a debug ranges section.
  803. emitDebugRanges();
  804. // Emit info into a debug macinfo section.
  805. emitDebugMacinfo();
  806. if (useSplitDwarf()) {
  807. emitDebugStrDWO();
  808. emitDebugInfoDWO();
  809. emitDebugAbbrevDWO();
  810. emitDebugLineDWO();
  811. }
  812. emitDebugAddr();
  813. // Emit info into the dwarf accelerator table sections.
  814. switch (getAccelTableKind()) {
  815. case AccelTableKind::Apple:
  816. emitAccelNames();
  817. emitAccelObjC();
  818. emitAccelNamespaces();
  819. emitAccelTypes();
  820. break;
  821. case AccelTableKind::Dwarf:
  822. emitAccelDebugNames();
  823. break;
  824. case AccelTableKind::None:
  825. break;
  826. case AccelTableKind::Default:
  827. llvm_unreachable("Default should have already been resolved.");
  828. }
  829. // Emit the pubnames and pubtypes sections if requested.
  830. emitDebugPubSections();
  831. // clean up.
  832. // FIXME: AbstractVariables.clear();
  833. }
  834. void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
  835. const DINode *Node,
  836. const MDNode *ScopeNode) {
  837. if (CU.getExistingAbstractEntity(Node))
  838. return;
  839. CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
  840. cast<DILocalScope>(ScopeNode)));
  841. }
  842. void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
  843. const DINode *Node, const MDNode *ScopeNode) {
  844. if (CU.getExistingAbstractEntity(Node))
  845. return;
  846. if (LexicalScope *Scope =
  847. LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
  848. CU.createAbstractEntity(Node, Scope);
  849. }
  850. // Collect variable information from side table maintained by MF.
  851. void DwarfDebug::collectVariableInfoFromMFTable(
  852. DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
  853. SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
  854. for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
  855. if (!VI.Var)
  856. continue;
  857. assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
  858. "Expected inlined-at fields to agree");
  859. InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
  860. Processed.insert(Var);
  861. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  862. // If variable scope is not found then skip this variable.
  863. if (!Scope)
  864. continue;
  865. ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
  866. auto RegVar = llvm::make_unique<DbgVariable>(
  867. cast<DILocalVariable>(Var.first), Var.second);
  868. RegVar->initializeMMI(VI.Expr, VI.Slot);
  869. if (DbgVariable *DbgVar = MFVars.lookup(Var))
  870. DbgVar->addMMIEntry(*RegVar);
  871. else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
  872. MFVars.insert({Var, RegVar.get()});
  873. ConcreteEntities.push_back(std::move(RegVar));
  874. }
  875. }
  876. }
  877. // Get .debug_loc entry for the instruction range starting at MI.
  878. static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
  879. const DIExpression *Expr = MI->getDebugExpression();
  880. assert(MI->getNumOperands() == 4);
  881. if (MI->getOperand(0).isReg()) {
  882. auto RegOp = MI->getOperand(0);
  883. auto Op1 = MI->getOperand(1);
  884. // If the second operand is an immediate, this is a
  885. // register-indirect address.
  886. assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
  887. MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
  888. return DebugLocEntry::Value(Expr, MLoc);
  889. }
  890. if (MI->getOperand(0).isImm())
  891. return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
  892. if (MI->getOperand(0).isFPImm())
  893. return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
  894. if (MI->getOperand(0).isCImm())
  895. return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
  896. llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
  897. }
  898. /// If this and Next are describing different fragments of the same
  899. /// variable, merge them by appending Next's values to the current
  900. /// list of values.
  901. /// Return true if the merge was successful.
  902. bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
  903. if (Begin == Next.Begin) {
  904. auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
  905. auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
  906. if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
  907. return false;
  908. // We can only merge entries if none of the fragments overlap any others.
  909. // In doing so, we can take advantage of the fact that both lists are
  910. // sorted.
  911. for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
  912. for (; j < Next.Values.size(); ++j) {
  913. int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp(
  914. cast<DIExpression>(Next.Values[j].Expression));
  915. if (res == 0) // The two expressions overlap, we can't merge.
  916. return false;
  917. // Values[i] is entirely before Next.Values[j],
  918. // so go back to the next entry of Values.
  919. else if (res == -1)
  920. break;
  921. // Next.Values[j] is entirely before Values[i], so go on to the
  922. // next entry of Next.Values.
  923. }
  924. }
  925. addValues(Next.Values);
  926. End = Next.End;
  927. return true;
  928. }
  929. return false;
  930. }
  931. /// Build the location list for all DBG_VALUEs in the function that
  932. /// describe the same variable. If the ranges of several independent
  933. /// fragments of the same variable overlap partially, split them up and
  934. /// combine the ranges. The resulting DebugLocEntries are will have
  935. /// strict monotonically increasing begin addresses and will never
  936. /// overlap.
  937. //
  938. // Input:
  939. //
  940. // Ranges History [var, loc, fragment ofs size]
  941. // 0 | [x, (reg0, fragment 0, 32)]
  942. // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
  943. // 2 | | ...
  944. // 3 | [clobber reg0]
  945. // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
  946. // x.
  947. //
  948. // Output:
  949. //
  950. // [0-1] [x, (reg0, fragment 0, 32)]
  951. // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)]
  952. // [3-4] [x, (reg1, fragment 32, 32)]
  953. // [4- ] [x, (mem, fragment 0, 64)]
  954. void
  955. DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
  956. const DbgValueHistoryMap::InstrRanges &Ranges) {
  957. SmallVector<DebugLocEntry::Value, 4> OpenRanges;
  958. for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  959. const MachineInstr *Begin = I->first;
  960. const MachineInstr *End = I->second;
  961. assert(Begin->isDebugValue() && "Invalid History entry");
  962. // Check if a variable is inaccessible in this range.
  963. if (Begin->getNumOperands() > 1 &&
  964. Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
  965. OpenRanges.clear();
  966. continue;
  967. }
  968. // If this fragment overlaps with any open ranges, truncate them.
  969. const DIExpression *DIExpr = Begin->getDebugExpression();
  970. auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
  971. return DIExpr->fragmentsOverlap(R.getExpression());
  972. });
  973. OpenRanges.erase(Last, OpenRanges.end());
  974. const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
  975. assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
  976. const MCSymbol *EndLabel;
  977. if (End != nullptr)
  978. EndLabel = getLabelAfterInsn(End);
  979. else if (std::next(I) == Ranges.end())
  980. EndLabel = Asm->getFunctionEnd();
  981. else
  982. EndLabel = getLabelBeforeInsn(std::next(I)->first);
  983. assert(EndLabel && "Forgot label after instruction ending a range!");
  984. LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
  985. auto Value = getDebugLocValue(Begin);
  986. DebugLocEntry Loc(StartLabel, EndLabel, Value);
  987. bool couldMerge = false;
  988. // If this is a fragment, it may belong to the current DebugLocEntry.
  989. if (DIExpr->isFragment()) {
  990. // Add this value to the list of open ranges.
  991. OpenRanges.push_back(Value);
  992. // Attempt to add the fragment to the last entry.
  993. if (!DebugLoc.empty())
  994. if (DebugLoc.back().MergeValues(Loc))
  995. couldMerge = true;
  996. }
  997. if (!couldMerge) {
  998. // Need to add a new DebugLocEntry. Add all values from still
  999. // valid non-overlapping fragments.
  1000. if (OpenRanges.size())
  1001. Loc.addValues(OpenRanges);
  1002. DebugLoc.push_back(std::move(Loc));
  1003. }
  1004. // Attempt to coalesce the ranges of two otherwise identical
  1005. // DebugLocEntries.
  1006. auto CurEntry = DebugLoc.rbegin();
  1007. LLVM_DEBUG({
  1008. dbgs() << CurEntry->getValues().size() << " Values:\n";
  1009. for (auto &Value : CurEntry->getValues())
  1010. Value.dump();
  1011. dbgs() << "-----\n";
  1012. });
  1013. auto PrevEntry = std::next(CurEntry);
  1014. if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
  1015. DebugLoc.pop_back();
  1016. }
  1017. }
  1018. DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
  1019. LexicalScope &Scope,
  1020. const DINode *Node,
  1021. const DILocation *Location,
  1022. const MCSymbol *Sym) {
  1023. ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
  1024. if (isa<const DILocalVariable>(Node)) {
  1025. ConcreteEntities.push_back(
  1026. llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
  1027. Location));
  1028. InfoHolder.addScopeVariable(&Scope,
  1029. cast<DbgVariable>(ConcreteEntities.back().get()));
  1030. } else if (isa<const DILabel>(Node)) {
  1031. ConcreteEntities.push_back(
  1032. llvm::make_unique<DbgLabel>(cast<const DILabel>(Node),
  1033. Location, Sym));
  1034. InfoHolder.addScopeLabel(&Scope,
  1035. cast<DbgLabel>(ConcreteEntities.back().get()));
  1036. }
  1037. return ConcreteEntities.back().get();
  1038. }
  1039. /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
  1040. /// enclosing lexical scope. The check ensures there are no other instructions
  1041. /// in the same lexical scope preceding the DBG_VALUE and that its range is
  1042. /// either open or otherwise rolls off the end of the scope.
  1043. static bool validThroughout(LexicalScopes &LScopes,
  1044. const MachineInstr *DbgValue,
  1045. const MachineInstr *RangeEnd) {
  1046. assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
  1047. auto MBB = DbgValue->getParent();
  1048. auto DL = DbgValue->getDebugLoc();
  1049. auto *LScope = LScopes.findLexicalScope(DL);
  1050. // Scope doesn't exist; this is a dead DBG_VALUE.
  1051. if (!LScope)
  1052. return false;
  1053. auto &LSRange = LScope->getRanges();
  1054. if (LSRange.size() == 0)
  1055. return false;
  1056. // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
  1057. const MachineInstr *LScopeBegin = LSRange.front().first;
  1058. // Early exit if the lexical scope begins outside of the current block.
  1059. if (LScopeBegin->getParent() != MBB)
  1060. return false;
  1061. MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
  1062. for (++Pred; Pred != MBB->rend(); ++Pred) {
  1063. if (Pred->getFlag(MachineInstr::FrameSetup))
  1064. break;
  1065. auto PredDL = Pred->getDebugLoc();
  1066. if (!PredDL || Pred->isMetaInstruction())
  1067. continue;
  1068. // Check whether the instruction preceding the DBG_VALUE is in the same
  1069. // (sub)scope as the DBG_VALUE.
  1070. if (DL->getScope() == PredDL->getScope())
  1071. return false;
  1072. auto *PredScope = LScopes.findLexicalScope(PredDL);
  1073. if (!PredScope || LScope->dominates(PredScope))
  1074. return false;
  1075. }
  1076. // If the range of the DBG_VALUE is open-ended, report success.
  1077. if (!RangeEnd)
  1078. return true;
  1079. // Fail if there are instructions belonging to our scope in another block.
  1080. const MachineInstr *LScopeEnd = LSRange.back().second;
  1081. if (LScopeEnd->getParent() != MBB)
  1082. return false;
  1083. // Single, constant DBG_VALUEs in the prologue are promoted to be live
  1084. // throughout the function. This is a hack, presumably for DWARF v2 and not
  1085. // necessarily correct. It would be much better to use a dbg.declare instead
  1086. // if we know the constant is live throughout the scope.
  1087. if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
  1088. return true;
  1089. return false;
  1090. }
  1091. // Find variables for each lexical scope.
  1092. void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
  1093. const DISubprogram *SP,
  1094. DenseSet<InlinedEntity> &Processed) {
  1095. // Grab the variable info that was squirreled away in the MMI side-table.
  1096. collectVariableInfoFromMFTable(TheCU, Processed);
  1097. for (const auto &I : DbgValues) {
  1098. InlinedEntity IV = I.first;
  1099. if (Processed.count(IV))
  1100. continue;
  1101. // Instruction ranges, specifying where IV is accessible.
  1102. const auto &Ranges = I.second;
  1103. if (Ranges.empty())
  1104. continue;
  1105. LexicalScope *Scope = nullptr;
  1106. const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
  1107. if (const DILocation *IA = IV.second)
  1108. Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
  1109. else
  1110. Scope = LScopes.findLexicalScope(LocalVar->getScope());
  1111. // If variable scope is not found then skip this variable.
  1112. if (!Scope)
  1113. continue;
  1114. Processed.insert(IV);
  1115. DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
  1116. *Scope, LocalVar, IV.second));
  1117. const MachineInstr *MInsn = Ranges.front().first;
  1118. assert(MInsn->isDebugValue() && "History must begin with debug value");
  1119. // Check if there is a single DBG_VALUE, valid throughout the var's scope.
  1120. if (Ranges.size() == 1 &&
  1121. validThroughout(LScopes, MInsn, Ranges.front().second)) {
  1122. RegVar->initializeDbgValue(MInsn);
  1123. continue;
  1124. }
  1125. // Do not emit location lists if .debug_loc secton is disabled.
  1126. if (!useLocSection())
  1127. continue;
  1128. // Handle multiple DBG_VALUE instructions describing one variable.
  1129. DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
  1130. // Build the location list for this variable.
  1131. SmallVector<DebugLocEntry, 8> Entries;
  1132. buildLocationList(Entries, Ranges);
  1133. // If the variable has a DIBasicType, extract it. Basic types cannot have
  1134. // unique identifiers, so don't bother resolving the type with the
  1135. // identifier map.
  1136. const DIBasicType *BT = dyn_cast<DIBasicType>(
  1137. static_cast<const Metadata *>(LocalVar->getType()));
  1138. // Finalize the entry by lowering it into a DWARF bytestream.
  1139. for (auto &Entry : Entries)
  1140. Entry.finalize(*Asm, List, BT);
  1141. }
  1142. // For each InlinedEntity collected from DBG_LABEL instructions, convert to
  1143. // DWARF-related DbgLabel.
  1144. for (const auto &I : DbgLabels) {
  1145. InlinedEntity IL = I.first;
  1146. const MachineInstr *MI = I.second;
  1147. if (MI == nullptr)
  1148. continue;
  1149. LexicalScope *Scope = nullptr;
  1150. const DILabel *Label = cast<DILabel>(IL.first);
  1151. // Get inlined DILocation if it is inlined label.
  1152. if (const DILocation *IA = IL.second)
  1153. Scope = LScopes.findInlinedScope(Label->getScope(), IA);
  1154. else
  1155. Scope = LScopes.findLexicalScope(Label->getScope());
  1156. // If label scope is not found then skip this label.
  1157. if (!Scope)
  1158. continue;
  1159. Processed.insert(IL);
  1160. /// At this point, the temporary label is created.
  1161. /// Save the temporary label to DbgLabel entity to get the
  1162. /// actually address when generating Dwarf DIE.
  1163. MCSymbol *Sym = getLabelBeforeInsn(MI);
  1164. createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
  1165. }
  1166. // Collect info for variables/labels that were optimized out.
  1167. for (const DINode *DN : SP->getRetainedNodes()) {
  1168. if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
  1169. continue;
  1170. LexicalScope *Scope = nullptr;
  1171. if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
  1172. Scope = LScopes.findLexicalScope(DV->getScope());
  1173. } else if (auto *DL = dyn_cast<DILabel>(DN)) {
  1174. Scope = LScopes.findLexicalScope(DL->getScope());
  1175. }
  1176. if (Scope)
  1177. createConcreteEntity(TheCU, *Scope, DN, nullptr);
  1178. }
  1179. }
  1180. // Process beginning of an instruction.
  1181. void DwarfDebug::beginInstruction(const MachineInstr *MI) {
  1182. DebugHandlerBase::beginInstruction(MI);
  1183. assert(CurMI);
  1184. const auto *SP = MI->getMF()->getFunction().getSubprogram();
  1185. if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
  1186. return;
  1187. // Check if source location changes, but ignore DBG_VALUE and CFI locations.
  1188. // If the instruction is part of the function frame setup code, do not emit
  1189. // any line record, as there is no correspondence with any user code.
  1190. if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
  1191. return;
  1192. const DebugLoc &DL = MI->getDebugLoc();
  1193. // When we emit a line-0 record, we don't update PrevInstLoc; so look at
  1194. // the last line number actually emitted, to see if it was line 0.
  1195. unsigned LastAsmLine =
  1196. Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
  1197. // Request a label after the call in order to emit AT_return_pc information
  1198. // in call site entries. TODO: Add support for targets with delay slots.
  1199. if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
  1200. requestLabelAfterInsn(MI);
  1201. if (DL == PrevInstLoc) {
  1202. // If we have an ongoing unspecified location, nothing to do here.
  1203. if (!DL)
  1204. return;
  1205. // We have an explicit location, same as the previous location.
  1206. // But we might be coming back to it after a line 0 record.
  1207. if (LastAsmLine == 0 && DL.getLine() != 0) {
  1208. // Reinstate the source location but not marked as a statement.
  1209. const MDNode *Scope = DL.getScope();
  1210. recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
  1211. }
  1212. return;
  1213. }
  1214. if (!DL) {
  1215. // We have an unspecified location, which might want to be line 0.
  1216. // If we have already emitted a line-0 record, don't repeat it.
  1217. if (LastAsmLine == 0)
  1218. return;
  1219. // If user said Don't Do That, don't do that.
  1220. if (UnknownLocations == Disable)
  1221. return;
  1222. // See if we have a reason to emit a line-0 record now.
  1223. // Reasons to emit a line-0 record include:
  1224. // - User asked for it (UnknownLocations).
  1225. // - Instruction has a label, so it's referenced from somewhere else,
  1226. // possibly debug information; we want it to have a source location.
  1227. // - Instruction is at the top of a block; we don't want to inherit the
  1228. // location from the physically previous (maybe unrelated) block.
  1229. if (UnknownLocations == Enable || PrevLabel ||
  1230. (PrevInstBB && PrevInstBB != MI->getParent())) {
  1231. // Preserve the file and column numbers, if we can, to save space in
  1232. // the encoded line table.
  1233. // Do not update PrevInstLoc, it remembers the last non-0 line.
  1234. const MDNode *Scope = nullptr;
  1235. unsigned Column = 0;
  1236. if (PrevInstLoc) {
  1237. Scope = PrevInstLoc.getScope();
  1238. Column = PrevInstLoc.getCol();
  1239. }
  1240. recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
  1241. }
  1242. return;
  1243. }
  1244. // We have an explicit location, different from the previous location.
  1245. // Don't repeat a line-0 record, but otherwise emit the new location.
  1246. // (The new location might be an explicit line 0, which we do emit.)
  1247. if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
  1248. return;
  1249. unsigned Flags = 0;
  1250. if (DL == PrologEndLoc) {
  1251. Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
  1252. PrologEndLoc = DebugLoc();
  1253. }
  1254. // If the line changed, we call that a new statement; unless we went to
  1255. // line 0 and came back, in which case it is not a new statement.
  1256. unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
  1257. if (DL.getLine() && DL.getLine() != OldLine)
  1258. Flags |= DWARF2_FLAG_IS_STMT;
  1259. const MDNode *Scope = DL.getScope();
  1260. recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
  1261. // If we're not at line 0, remember this location.
  1262. if (DL.getLine())
  1263. PrevInstLoc = DL;
  1264. }
  1265. static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
  1266. // First known non-DBG_VALUE and non-frame setup location marks
  1267. // the beginning of the function body.
  1268. for (const auto &MBB : *MF)
  1269. for (const auto &MI : MBB)
  1270. if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
  1271. MI.getDebugLoc())
  1272. return MI.getDebugLoc();
  1273. return DebugLoc();
  1274. }
  1275. // Gather pre-function debug information. Assumes being called immediately
  1276. // after the function entry point has been emitted.
  1277. void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
  1278. CurFn = MF;
  1279. auto *SP = MF->getFunction().getSubprogram();
  1280. assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
  1281. if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
  1282. return;
  1283. DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
  1284. // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
  1285. // belongs to so that we add to the correct per-cu line table in the
  1286. // non-asm case.
  1287. if (Asm->OutStreamer->hasRawTextSupport())
  1288. // Use a single line table if we are generating assembly.
  1289. Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
  1290. else
  1291. Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
  1292. // Record beginning of function.
  1293. PrologEndLoc = findPrologueEndLoc(MF);
  1294. if (PrologEndLoc) {
  1295. // We'd like to list the prologue as "not statements" but GDB behaves
  1296. // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
  1297. auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
  1298. recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
  1299. }
  1300. }
  1301. void DwarfDebug::skippedNonDebugFunction() {
  1302. // If we don't have a subprogram for this function then there will be a hole
  1303. // in the range information. Keep note of this by setting the previously used
  1304. // section to nullptr.
  1305. PrevCU = nullptr;
  1306. CurFn = nullptr;
  1307. }
  1308. // Gather and emit post-function debug information.
  1309. void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
  1310. const DISubprogram *SP = MF->getFunction().getSubprogram();
  1311. assert(CurFn == MF &&
  1312. "endFunction should be called with the same function as beginFunction");
  1313. // Set DwarfDwarfCompileUnitID in MCContext to default value.
  1314. Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
  1315. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  1316. assert(!FnScope || SP == FnScope->getScopeNode());
  1317. DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
  1318. if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
  1319. PrevLabel = nullptr;
  1320. CurFn = nullptr;
  1321. return;
  1322. }
  1323. DenseSet<InlinedEntity> Processed;
  1324. collectEntityInfo(TheCU, SP, Processed);
  1325. // Add the range of this function to the list of ranges for the CU.
  1326. TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
  1327. // Under -gmlt, skip building the subprogram if there are no inlined
  1328. // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
  1329. // is still needed as we need its source location.
  1330. if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
  1331. TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
  1332. LScopes.getAbstractScopesList().empty() && !IsDarwin) {
  1333. assert(InfoHolder.getScopeVariables().empty());
  1334. PrevLabel = nullptr;
  1335. CurFn = nullptr;
  1336. return;
  1337. }
  1338. #ifndef NDEBUG
  1339. size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
  1340. #endif
  1341. // Construct abstract scopes.
  1342. for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
  1343. auto *SP = cast<DISubprogram>(AScope->getScopeNode());
  1344. for (const DINode *DN : SP->getRetainedNodes()) {
  1345. if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
  1346. continue;
  1347. const MDNode *Scope = nullptr;
  1348. if (auto *DV = dyn_cast<DILocalVariable>(DN))
  1349. Scope = DV->getScope();
  1350. else if (auto *DL = dyn_cast<DILabel>(DN))
  1351. Scope = DL->getScope();
  1352. else
  1353. llvm_unreachable("Unexpected DI type!");
  1354. // Collect info for variables/labels that were optimized out.
  1355. ensureAbstractEntityIsCreated(TheCU, DN, Scope);
  1356. assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
  1357. && "ensureAbstractEntityIsCreated inserted abstract scopes");
  1358. }
  1359. constructAbstractSubprogramScopeDIE(TheCU, AScope);
  1360. }
  1361. ProcessedSPNodes.insert(SP);
  1362. DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
  1363. if (auto *SkelCU = TheCU.getSkeleton())
  1364. if (!LScopes.getAbstractScopesList().empty() &&
  1365. TheCU.getCUNode()->getSplitDebugInlining())
  1366. SkelCU->constructSubprogramScopeDIE(SP, FnScope);
  1367. // Construct call site entries.
  1368. constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
  1369. // Clear debug info
  1370. // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
  1371. // DbgVariables except those that are also in AbstractVariables (since they
  1372. // can be used cross-function)
  1373. InfoHolder.getScopeVariables().clear();
  1374. InfoHolder.getScopeLabels().clear();
  1375. PrevLabel = nullptr;
  1376. CurFn = nullptr;
  1377. }
  1378. // Register a source line with debug info. Returns the unique label that was
  1379. // emitted and which provides correspondence to the source line list.
  1380. void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
  1381. unsigned Flags) {
  1382. StringRef Fn;
  1383. unsigned FileNo = 1;
  1384. unsigned Discriminator = 0;
  1385. if (auto *Scope = cast_or_null<DIScope>(S)) {
  1386. Fn = Scope->getFilename();
  1387. if (Line != 0 && getDwarfVersion() >= 4)
  1388. if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
  1389. Discriminator = LBF->getDiscriminator();
  1390. unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
  1391. FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
  1392. .getOrCreateSourceID(Scope->getFile());
  1393. }
  1394. Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
  1395. Discriminator, Fn);
  1396. }
  1397. //===----------------------------------------------------------------------===//
  1398. // Emit Methods
  1399. //===----------------------------------------------------------------------===//
  1400. // Emit the debug info section.
  1401. void DwarfDebug::emitDebugInfo() {
  1402. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1403. Holder.emitUnits(/* UseOffsets */ false);
  1404. }
  1405. // Emit the abbreviation section.
  1406. void DwarfDebug::emitAbbreviations() {
  1407. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1408. Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
  1409. }
  1410. void DwarfDebug::emitStringOffsetsTableHeader() {
  1411. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1412. Holder.getStringPool().emitStringOffsetsTableHeader(
  1413. *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
  1414. Holder.getStringOffsetsStartSym());
  1415. }
  1416. template <typename AccelTableT>
  1417. void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
  1418. StringRef TableName) {
  1419. Asm->OutStreamer->SwitchSection(Section);
  1420. // Emit the full data.
  1421. emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
  1422. }
  1423. void DwarfDebug::emitAccelDebugNames() {
  1424. // Don't emit anything if we have no compilation units to index.
  1425. if (getUnits().empty())
  1426. return;
  1427. emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
  1428. }
  1429. // Emit visible names into a hashed accelerator table section.
  1430. void DwarfDebug::emitAccelNames() {
  1431. emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
  1432. "Names");
  1433. }
  1434. // Emit objective C classes and categories into a hashed accelerator table
  1435. // section.
  1436. void DwarfDebug::emitAccelObjC() {
  1437. emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
  1438. "ObjC");
  1439. }
  1440. // Emit namespace dies into a hashed accelerator table.
  1441. void DwarfDebug::emitAccelNamespaces() {
  1442. emitAccel(AccelNamespace,
  1443. Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
  1444. "namespac");
  1445. }
  1446. // Emit type dies into a hashed accelerator table.
  1447. void DwarfDebug::emitAccelTypes() {
  1448. emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
  1449. "types");
  1450. }
  1451. // Public name handling.
  1452. // The format for the various pubnames:
  1453. //
  1454. // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
  1455. // for the DIE that is named.
  1456. //
  1457. // gnu pubnames - offset/index value/name tuples where the offset is the offset
  1458. // into the CU and the index value is computed according to the type of value
  1459. // for the DIE that is named.
  1460. //
  1461. // For type units the offset is the offset of the skeleton DIE. For split dwarf
  1462. // it's the offset within the debug_info/debug_types dwo section, however, the
  1463. // reference in the pubname header doesn't change.
  1464. /// computeIndexValue - Compute the gdb index value for the DIE and CU.
  1465. static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
  1466. const DIE *Die) {
  1467. // Entities that ended up only in a Type Unit reference the CU instead (since
  1468. // the pub entry has offsets within the CU there's no real offset that can be
  1469. // provided anyway). As it happens all such entities (namespaces and types,
  1470. // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
  1471. // not to be true it would be necessary to persist this information from the
  1472. // point at which the entry is added to the index data structure - since by
  1473. // the time the index is built from that, the original type/namespace DIE in a
  1474. // type unit has already been destroyed so it can't be queried for properties
  1475. // like tag, etc.
  1476. if (Die->getTag() == dwarf::DW_TAG_compile_unit)
  1477. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
  1478. dwarf::GIEL_EXTERNAL);
  1479. dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
  1480. // We could have a specification DIE that has our most of our knowledge,
  1481. // look for that now.
  1482. if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
  1483. DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
  1484. if (SpecDIE.findAttribute(dwarf::DW_AT_external))
  1485. Linkage = dwarf::GIEL_EXTERNAL;
  1486. } else if (Die->findAttribute(dwarf::DW_AT_external))
  1487. Linkage = dwarf::GIEL_EXTERNAL;
  1488. switch (Die->getTag()) {
  1489. case dwarf::DW_TAG_class_type:
  1490. case dwarf::DW_TAG_structure_type:
  1491. case dwarf::DW_TAG_union_type:
  1492. case dwarf::DW_TAG_enumeration_type:
  1493. return dwarf::PubIndexEntryDescriptor(
  1494. dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
  1495. ? dwarf::GIEL_STATIC
  1496. : dwarf::GIEL_EXTERNAL);
  1497. case dwarf::DW_TAG_typedef:
  1498. case dwarf::DW_TAG_base_type:
  1499. case dwarf::DW_TAG_subrange_type:
  1500. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
  1501. case dwarf::DW_TAG_namespace:
  1502. return dwarf::GIEK_TYPE;
  1503. case dwarf::DW_TAG_subprogram:
  1504. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
  1505. case dwarf::DW_TAG_variable:
  1506. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
  1507. case dwarf::DW_TAG_enumerator:
  1508. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
  1509. dwarf::GIEL_STATIC);
  1510. default:
  1511. return dwarf::GIEK_NONE;
  1512. }
  1513. }
  1514. /// emitDebugPubSections - Emit visible names and types into debug pubnames and
  1515. /// pubtypes sections.
  1516. void DwarfDebug::emitDebugPubSections() {
  1517. for (const auto &NU : CUMap) {
  1518. DwarfCompileUnit *TheU = NU.second;
  1519. if (!TheU->hasDwarfPubSections())
  1520. continue;
  1521. bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
  1522. DICompileUnit::DebugNameTableKind::GNU;
  1523. Asm->OutStreamer->SwitchSection(
  1524. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
  1525. : Asm->getObjFileLowering().getDwarfPubNamesSection());
  1526. emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
  1527. Asm->OutStreamer->SwitchSection(
  1528. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
  1529. : Asm->getObjFileLowering().getDwarfPubTypesSection());
  1530. emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
  1531. }
  1532. }
  1533. void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
  1534. if (useSectionsAsReferences())
  1535. Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
  1536. CU.getDebugSectionOffset());
  1537. else
  1538. Asm->emitDwarfSymbolReference(CU.getLabelBegin());
  1539. }
  1540. void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
  1541. DwarfCompileUnit *TheU,
  1542. const StringMap<const DIE *> &Globals) {
  1543. if (auto *Skeleton = TheU->getSkeleton())
  1544. TheU = Skeleton;
  1545. // Emit the header.
  1546. Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
  1547. MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
  1548. MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
  1549. Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
  1550. Asm->OutStreamer->EmitLabel(BeginLabel);
  1551. Asm->OutStreamer->AddComment("DWARF Version");
  1552. Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
  1553. Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
  1554. emitSectionReference(*TheU);
  1555. Asm->OutStreamer->AddComment("Compilation Unit Length");
  1556. Asm->emitInt32(TheU->getLength());
  1557. // Emit the pubnames for this compilation unit.
  1558. for (const auto &GI : Globals) {
  1559. const char *Name = GI.getKeyData();
  1560. const DIE *Entity = GI.second;
  1561. Asm->OutStreamer->AddComment("DIE offset");
  1562. Asm->emitInt32(Entity->getOffset());
  1563. if (GnuStyle) {
  1564. dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
  1565. Asm->OutStreamer->AddComment(
  1566. Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
  1567. dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
  1568. Asm->emitInt8(Desc.toBits());
  1569. }
  1570. Asm->OutStreamer->AddComment("External Name");
  1571. Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
  1572. }
  1573. Asm->OutStreamer->AddComment("End Mark");
  1574. Asm->emitInt32(0);
  1575. Asm->OutStreamer->EmitLabel(EndLabel);
  1576. }
  1577. /// Emit null-terminated strings into a debug str section.
  1578. void DwarfDebug::emitDebugStr() {
  1579. MCSection *StringOffsetsSection = nullptr;
  1580. if (useSegmentedStringOffsetsTable()) {
  1581. emitStringOffsetsTableHeader();
  1582. StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
  1583. }
  1584. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1585. Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
  1586. StringOffsetsSection, /* UseRelativeOffsets = */ true);
  1587. }
  1588. void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
  1589. const DebugLocStream::Entry &Entry) {
  1590. auto &&Comments = DebugLocs.getComments(Entry);
  1591. auto Comment = Comments.begin();
  1592. auto End = Comments.end();
  1593. for (uint8_t Byte : DebugLocs.getBytes(Entry))
  1594. Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
  1595. }
  1596. static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
  1597. const DebugLocEntry::Value &Value,
  1598. DwarfExpression &DwarfExpr) {
  1599. auto *DIExpr = Value.getExpression();
  1600. DIExpressionCursor ExprCursor(DIExpr);
  1601. DwarfExpr.addFragmentOffset(DIExpr);
  1602. // Regular entry.
  1603. if (Value.isInt()) {
  1604. if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
  1605. BT->getEncoding() == dwarf::DW_ATE_signed_char))
  1606. DwarfExpr.addSignedConstant(Value.getInt());
  1607. else
  1608. DwarfExpr.addUnsignedConstant(Value.getInt());
  1609. } else if (Value.isLocation()) {
  1610. MachineLocation Location = Value.getLoc();
  1611. if (Location.isIndirect())
  1612. DwarfExpr.setMemoryLocationKind();
  1613. DIExpressionCursor Cursor(DIExpr);
  1614. const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
  1615. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
  1616. return;
  1617. return DwarfExpr.addExpression(std::move(Cursor));
  1618. } else if (Value.isConstantFP()) {
  1619. APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
  1620. DwarfExpr.addUnsignedConstant(RawBytes);
  1621. }
  1622. DwarfExpr.addExpression(std::move(ExprCursor));
  1623. }
  1624. void DebugLocEntry::finalize(const AsmPrinter &AP,
  1625. DebugLocStream::ListBuilder &List,
  1626. const DIBasicType *BT) {
  1627. DebugLocStream::EntryBuilder Entry(List, Begin, End);
  1628. BufferByteStreamer Streamer = Entry.getStreamer();
  1629. DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
  1630. const DebugLocEntry::Value &Value = Values[0];
  1631. if (Value.isFragment()) {
  1632. // Emit all fragments that belong to the same variable and range.
  1633. assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
  1634. return P.isFragment();
  1635. }) && "all values are expected to be fragments");
  1636. assert(std::is_sorted(Values.begin(), Values.end()) &&
  1637. "fragments are expected to be sorted");
  1638. for (auto Fragment : Values)
  1639. emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
  1640. } else {
  1641. assert(Values.size() == 1 && "only fragments may have >1 value");
  1642. emitDebugLocValue(AP, BT, Value, DwarfExpr);
  1643. }
  1644. DwarfExpr.finalize();
  1645. }
  1646. void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
  1647. // Emit the size.
  1648. Asm->OutStreamer->AddComment("Loc expr size");
  1649. Asm->emitInt16(DebugLocs.getBytes(Entry).size());
  1650. // Emit the entry.
  1651. APByteStreamer Streamer(*Asm);
  1652. emitDebugLocEntry(Streamer, Entry);
  1653. }
  1654. // Emit locations into the debug loc section.
  1655. void DwarfDebug::emitDebugLoc() {
  1656. if (DebugLocs.getLists().empty())
  1657. return;
  1658. // Start the dwarf loc section.
  1659. Asm->OutStreamer->SwitchSection(
  1660. Asm->getObjFileLowering().getDwarfLocSection());
  1661. unsigned char Size = Asm->MAI->getCodePointerSize();
  1662. for (const auto &List : DebugLocs.getLists()) {
  1663. Asm->OutStreamer->EmitLabel(List.Label);
  1664. const DwarfCompileUnit *CU = List.CU;
  1665. for (const auto &Entry : DebugLocs.getEntries(List)) {
  1666. // Set up the range. This range is relative to the entry point of the
  1667. // compile unit. This is a hard coded 0 for low_pc when we're emitting
  1668. // ranges, or the DW_AT_low_pc on the compile unit otherwise.
  1669. if (auto *Base = CU->getBaseAddress()) {
  1670. Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
  1671. Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
  1672. } else {
  1673. Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
  1674. Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
  1675. }
  1676. emitDebugLocEntryLocation(Entry);
  1677. }
  1678. Asm->OutStreamer->EmitIntValue(0, Size);
  1679. Asm->OutStreamer->EmitIntValue(0, Size);
  1680. }
  1681. }
  1682. void DwarfDebug::emitDebugLocDWO() {
  1683. Asm->OutStreamer->SwitchSection(
  1684. Asm->getObjFileLowering().getDwarfLocDWOSection());
  1685. for (const auto &List : DebugLocs.getLists()) {
  1686. Asm->OutStreamer->EmitLabel(List.Label);
  1687. for (const auto &Entry : DebugLocs.getEntries(List)) {
  1688. // Just always use start_length for now - at least that's one address
  1689. // rather than two. We could get fancier and try to, say, reuse an
  1690. // address we know we've emitted elsewhere (the start of the function?
  1691. // The start of the CU or CU subrange that encloses this range?)
  1692. Asm->emitInt8(dwarf::DW_LLE_startx_length);
  1693. unsigned idx = AddrPool.getIndex(Entry.BeginSym);
  1694. Asm->EmitULEB128(idx);
  1695. Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
  1696. emitDebugLocEntryLocation(Entry);
  1697. }
  1698. Asm->emitInt8(dwarf::DW_LLE_end_of_list);
  1699. }
  1700. }
  1701. struct ArangeSpan {
  1702. const MCSymbol *Start, *End;
  1703. };
  1704. // Emit a debug aranges section, containing a CU lookup for any
  1705. // address we can tie back to a CU.
  1706. void DwarfDebug::emitDebugARanges() {
  1707. // Provides a unique id per text section.
  1708. MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
  1709. // Filter labels by section.
  1710. for (const SymbolCU &SCU : ArangeLabels) {
  1711. if (SCU.Sym->isInSection()) {
  1712. // Make a note of this symbol and it's section.
  1713. MCSection *Section = &SCU.Sym->getSection();
  1714. if (!Section->getKind().isMetadata())
  1715. SectionMap[Section].push_back(SCU);
  1716. } else {
  1717. // Some symbols (e.g. common/bss on mach-o) can have no section but still
  1718. // appear in the output. This sucks as we rely on sections to build
  1719. // arange spans. We can do it without, but it's icky.
  1720. SectionMap[nullptr].push_back(SCU);
  1721. }
  1722. }
  1723. DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
  1724. for (auto &I : SectionMap) {
  1725. MCSection *Section = I.first;
  1726. SmallVector<SymbolCU, 8> &List = I.second;
  1727. if (List.size() < 1)
  1728. continue;
  1729. // If we have no section (e.g. common), just write out
  1730. // individual spans for each symbol.
  1731. if (!Section) {
  1732. for (const SymbolCU &Cur : List) {
  1733. ArangeSpan Span;
  1734. Span.Start = Cur.Sym;
  1735. Span.End = nullptr;
  1736. assert(Cur.CU);
  1737. Spans[Cur.CU].push_back(Span);
  1738. }
  1739. continue;
  1740. }
  1741. // Sort the symbols by offset within the section.
  1742. std::stable_sort(
  1743. List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
  1744. unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
  1745. unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
  1746. // Symbols with no order assigned should be placed at the end.
  1747. // (e.g. section end labels)
  1748. if (IA == 0)
  1749. return false;
  1750. if (IB == 0)
  1751. return true;
  1752. return IA < IB;
  1753. });
  1754. // Insert a final terminator.
  1755. List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
  1756. // Build spans between each label.
  1757. const MCSymbol *StartSym = List[0].Sym;
  1758. for (size_t n = 1, e = List.size(); n < e; n++) {
  1759. const SymbolCU &Prev = List[n - 1];
  1760. const SymbolCU &Cur = List[n];
  1761. // Try and build the longest span we can within the same CU.
  1762. if (Cur.CU != Prev.CU) {
  1763. ArangeSpan Span;
  1764. Span.Start = StartSym;
  1765. Span.End = Cur.Sym;
  1766. assert(Prev.CU);
  1767. Spans[Prev.CU].push_back(Span);
  1768. StartSym = Cur.Sym;
  1769. }
  1770. }
  1771. }
  1772. // Start the dwarf aranges section.
  1773. Asm->OutStreamer->SwitchSection(
  1774. Asm->getObjFileLowering().getDwarfARangesSection());
  1775. unsigned PtrSize = Asm->MAI->getCodePointerSize();
  1776. // Build a list of CUs used.
  1777. std::vector<DwarfCompileUnit *> CUs;
  1778. for (const auto &it : Spans) {
  1779. DwarfCompileUnit *CU = it.first;
  1780. CUs.push_back(CU);
  1781. }
  1782. // Sort the CU list (again, to ensure consistent output order).
  1783. llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
  1784. return A->getUniqueID() < B->getUniqueID();
  1785. });
  1786. // Emit an arange table for each CU we used.
  1787. for (DwarfCompileUnit *CU : CUs) {
  1788. std::vector<ArangeSpan> &List = Spans[CU];
  1789. // Describe the skeleton CU's offset and length, not the dwo file's.
  1790. if (auto *Skel = CU->getSkeleton())
  1791. CU = Skel;
  1792. // Emit size of content not including length itself.
  1793. unsigned ContentSize =
  1794. sizeof(int16_t) + // DWARF ARange version number
  1795. sizeof(int32_t) + // Offset of CU in the .debug_info section
  1796. sizeof(int8_t) + // Pointer Size (in bytes)
  1797. sizeof(int8_t); // Segment Size (in bytes)
  1798. unsigned TupleSize = PtrSize * 2;
  1799. // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
  1800. unsigned Padding =
  1801. OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
  1802. ContentSize += Padding;
  1803. ContentSize += (List.size() + 1) * TupleSize;
  1804. // For each compile unit, write the list of spans it covers.
  1805. Asm->OutStreamer->AddComment("Length of ARange Set");
  1806. Asm->emitInt32(ContentSize);
  1807. Asm->OutStreamer->AddComment("DWARF Arange version number");
  1808. Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
  1809. Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
  1810. emitSectionReference(*CU);
  1811. Asm->OutStreamer->AddComment("Address Size (in bytes)");
  1812. Asm->emitInt8(PtrSize);
  1813. Asm->OutStreamer->AddComment("Segment Size (in bytes)");
  1814. Asm->emitInt8(0);
  1815. Asm->OutStreamer->emitFill(Padding, 0xff);
  1816. for (const ArangeSpan &Span : List) {
  1817. Asm->EmitLabelReference(Span.Start, PtrSize);
  1818. // Calculate the size as being from the span start to it's end.
  1819. if (Span.End) {
  1820. Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
  1821. } else {
  1822. // For symbols without an end marker (e.g. common), we
  1823. // write a single arange entry containing just that one symbol.
  1824. uint64_t Size = SymSize[Span.Start];
  1825. if (Size == 0)
  1826. Size = 1;
  1827. Asm->OutStreamer->EmitIntValue(Size, PtrSize);
  1828. }
  1829. }
  1830. Asm->OutStreamer->AddComment("ARange terminator");
  1831. Asm->OutStreamer->EmitIntValue(0, PtrSize);
  1832. Asm->OutStreamer->EmitIntValue(0, PtrSize);
  1833. }
  1834. }
  1835. /// Emit a single range list. We handle both DWARF v5 and earlier.
  1836. static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
  1837. const RangeSpanList &List) {
  1838. auto DwarfVersion = DD.getDwarfVersion();
  1839. // Emit our symbol so we can find the beginning of the range.
  1840. Asm->OutStreamer->EmitLabel(List.getSym());
  1841. // Gather all the ranges that apply to the same section so they can share
  1842. // a base address entry.
  1843. MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges;
  1844. // Size for our labels.
  1845. auto Size = Asm->MAI->getCodePointerSize();
  1846. for (const RangeSpan &Range : List.getRanges())
  1847. SectionRanges[&Range.getStart()->getSection()].push_back(&Range);
  1848. const MCSymbol *CUBase = List.getBaseAddress();
  1849. bool BaseIsSet = false;
  1850. for (const auto &P : SectionRanges) {
  1851. // Don't bother with a base address entry if there's only one range in
  1852. // this section in this range list - for example ranges for a CU will
  1853. // usually consist of single regions from each of many sections
  1854. // (-ffunction-sections, or just C++ inline functions) except under LTO
  1855. // or optnone where there may be holes in a single CU's section
  1856. // contributions.
  1857. auto *Base = CUBase;
  1858. if (!Base && P.second.size() > 1 &&
  1859. (UseDwarfRangesBaseAddressSpecifier || DwarfVersion >= 5)) {
  1860. BaseIsSet = true;
  1861. // FIXME/use care: This may not be a useful base address if it's not
  1862. // the lowest address/range in this object.
  1863. Base = P.second.front()->getStart();
  1864. if (DwarfVersion >= 5) {
  1865. Asm->OutStreamer->AddComment("DW_RLE_base_addressx");
  1866. Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1);
  1867. Asm->OutStreamer->AddComment(" base address index");
  1868. Asm->EmitULEB128(DD.getAddressPool().getIndex(Base));
  1869. } else {
  1870. Asm->OutStreamer->EmitIntValue(-1, Size);
  1871. Asm->OutStreamer->AddComment(" base address");
  1872. Asm->OutStreamer->EmitSymbolValue(Base, Size);
  1873. }
  1874. } else if (BaseIsSet && DwarfVersion < 5) {
  1875. BaseIsSet = false;
  1876. assert(!Base);
  1877. Asm->OutStreamer->EmitIntValue(-1, Size);
  1878. Asm->OutStreamer->EmitIntValue(0, Size);
  1879. }
  1880. for (const auto *RS : P.second) {
  1881. const MCSymbol *Begin = RS->getStart();
  1882. const MCSymbol *End = RS->getEnd();
  1883. assert(Begin && "Range without a begin symbol?");
  1884. assert(End && "Range without an end symbol?");
  1885. if (Base) {
  1886. if (DwarfVersion >= 5) {
  1887. // Emit DW_RLE_offset_pair when we have a base.
  1888. Asm->OutStreamer->AddComment("DW_RLE_offset_pair");
  1889. Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1);
  1890. Asm->OutStreamer->AddComment(" starting offset");
  1891. Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
  1892. Asm->OutStreamer->AddComment(" ending offset");
  1893. Asm->EmitLabelDifferenceAsULEB128(End, Base);
  1894. } else {
  1895. Asm->EmitLabelDifference(Begin, Base, Size);
  1896. Asm->EmitLabelDifference(End, Base, Size);
  1897. }
  1898. } else if (DwarfVersion >= 5) {
  1899. Asm->OutStreamer->AddComment("DW_RLE_startx_length");
  1900. Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1);
  1901. Asm->OutStreamer->AddComment(" start index");
  1902. Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin));
  1903. Asm->OutStreamer->AddComment(" length");
  1904. Asm->EmitLabelDifferenceAsULEB128(End, Begin);
  1905. } else {
  1906. Asm->OutStreamer->EmitSymbolValue(Begin, Size);
  1907. Asm->OutStreamer->EmitSymbolValue(End, Size);
  1908. }
  1909. }
  1910. }
  1911. if (DwarfVersion >= 5) {
  1912. Asm->OutStreamer->AddComment("DW_RLE_end_of_list");
  1913. Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1);
  1914. } else {
  1915. // Terminate the list with two 0 values.
  1916. Asm->OutStreamer->EmitIntValue(0, Size);
  1917. Asm->OutStreamer->EmitIntValue(0, Size);
  1918. }
  1919. }
  1920. // Emit the header of a DWARF 5 range list table. Returns the symbol that
  1921. // designates the end of the table for the caller to emit when the table is
  1922. // complete.
  1923. static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
  1924. const DwarfFile &Holder) {
  1925. // The length is described by a starting label right after the length field
  1926. // and an end label.
  1927. MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
  1928. MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
  1929. // Build the range table header, which starts with the length field.
  1930. Asm->OutStreamer->AddComment("Length");
  1931. Asm->EmitLabelDifference(TableEnd, TableStart, 4);
  1932. Asm->OutStreamer->EmitLabel(TableStart);
  1933. // Version number (DWARF v5 and later).
  1934. Asm->OutStreamer->AddComment("Version");
  1935. Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
  1936. Asm->OutStreamer->AddComment("Address size");
  1937. Asm->emitInt8(Asm->MAI->getCodePointerSize());
  1938. Asm->OutStreamer->AddComment("Segment selector size");
  1939. Asm->emitInt8(0);
  1940. MCSymbol *RnglistsTableBaseSym = Holder.getRnglistsTableBaseSym();
  1941. // FIXME: Generate the offsets table and use DW_FORM_rnglistx with the
  1942. // DW_AT_ranges attribute. Until then set the number of offsets to 0.
  1943. Asm->OutStreamer->AddComment("Offset entry count");
  1944. Asm->emitInt32(Holder.getRangeLists().size());
  1945. Asm->OutStreamer->EmitLabel(RnglistsTableBaseSym);
  1946. for (const RangeSpanList &List : Holder.getRangeLists())
  1947. Asm->EmitLabelDifference(List.getSym(), RnglistsTableBaseSym, 4);
  1948. return TableEnd;
  1949. }
  1950. void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm,
  1951. const DwarfFile &Holder, MCSymbol *TableEnd) {
  1952. for (const RangeSpanList &List : Holder.getRangeLists())
  1953. emitRangeList(DD, Asm, List);
  1954. if (TableEnd)
  1955. Asm->OutStreamer->EmitLabel(TableEnd);
  1956. }
  1957. /// Emit address ranges into the .debug_ranges section or into the DWARF v5
  1958. /// .debug_rnglists section.
  1959. void DwarfDebug::emitDebugRanges() {
  1960. if (CUMap.empty())
  1961. return;
  1962. const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1963. if (Holder.getRangeLists().empty())
  1964. return;
  1965. assert(useRangesSection());
  1966. assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
  1967. return Pair.second->getCUNode()->isDebugDirectivesOnly();
  1968. }));
  1969. // Start the dwarf ranges section.
  1970. MCSymbol *TableEnd = nullptr;
  1971. if (getDwarfVersion() >= 5) {
  1972. Asm->OutStreamer->SwitchSection(
  1973. Asm->getObjFileLowering().getDwarfRnglistsSection());
  1974. TableEnd = emitRnglistsTableHeader(Asm, Holder);
  1975. } else
  1976. Asm->OutStreamer->SwitchSection(
  1977. Asm->getObjFileLowering().getDwarfRangesSection());
  1978. emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
  1979. }
  1980. void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
  1981. for (auto *MN : Nodes) {
  1982. if (auto *M = dyn_cast<DIMacro>(MN))
  1983. emitMacro(*M);
  1984. else if (auto *F = dyn_cast<DIMacroFile>(MN))
  1985. emitMacroFile(*F, U);
  1986. else
  1987. llvm_unreachable("Unexpected DI type!");
  1988. }
  1989. }
  1990. void DwarfDebug::emitMacro(DIMacro &M) {
  1991. Asm->EmitULEB128(M.getMacinfoType());
  1992. Asm->EmitULEB128(M.getLine());
  1993. StringRef Name = M.getName();
  1994. StringRef Value = M.getValue();
  1995. Asm->OutStreamer->EmitBytes(Name);
  1996. if (!Value.empty()) {
  1997. // There should be one space between macro name and macro value.
  1998. Asm->emitInt8(' ');
  1999. Asm->OutStreamer->EmitBytes(Value);
  2000. }
  2001. Asm->emitInt8('\0');
  2002. }
  2003. void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
  2004. assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
  2005. Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
  2006. Asm->EmitULEB128(F.getLine());
  2007. Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
  2008. handleMacroNodes(F.getElements(), U);
  2009. Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
  2010. }
  2011. /// Emit macros into a debug macinfo section.
  2012. void DwarfDebug::emitDebugMacinfo() {
  2013. if (CUMap.empty())
  2014. return;
  2015. if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
  2016. return Pair.second->getCUNode()->isDebugDirectivesOnly();
  2017. }))
  2018. return;
  2019. // Start the dwarf macinfo section.
  2020. Asm->OutStreamer->SwitchSection(
  2021. Asm->getObjFileLowering().getDwarfMacinfoSection());
  2022. for (const auto &P : CUMap) {
  2023. auto &TheCU = *P.second;
  2024. if (TheCU.getCUNode()->isDebugDirectivesOnly())
  2025. continue;
  2026. auto *SkCU = TheCU.getSkeleton();
  2027. DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
  2028. auto *CUNode = cast<DICompileUnit>(P.first);
  2029. DIMacroNodeArray Macros = CUNode->getMacros();
  2030. if (!Macros.empty()) {
  2031. Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
  2032. handleMacroNodes(Macros, U);
  2033. }
  2034. }
  2035. Asm->OutStreamer->AddComment("End Of Macro List Mark");
  2036. Asm->emitInt8(0);
  2037. }
  2038. // DWARF5 Experimental Separate Dwarf emitters.
  2039. void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
  2040. std::unique_ptr<DwarfCompileUnit> NewU) {
  2041. NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
  2042. Asm->TM.Options.MCOptions.SplitDwarfFile);
  2043. if (!CompilationDir.empty())
  2044. NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  2045. addGnuPubAttributes(*NewU, Die);
  2046. SkeletonHolder.addUnit(std::move(NewU));
  2047. }
  2048. DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
  2049. auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
  2050. CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
  2051. DwarfCompileUnit &NewCU = *OwnedUnit;
  2052. NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
  2053. NewCU.initStmtList();
  2054. if (useSegmentedStringOffsetsTable())
  2055. NewCU.addStringOffsetsStart();
  2056. initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
  2057. return NewCU;
  2058. }
  2059. // Emit the .debug_info.dwo section for separated dwarf. This contains the
  2060. // compile units that would normally be in debug_info.
  2061. void DwarfDebug::emitDebugInfoDWO() {
  2062. assert(useSplitDwarf() && "No split dwarf debug info?");
  2063. // Don't emit relocations into the dwo file.
  2064. InfoHolder.emitUnits(/* UseOffsets */ true);
  2065. }
  2066. // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
  2067. // abbreviations for the .debug_info.dwo section.
  2068. void DwarfDebug::emitDebugAbbrevDWO() {
  2069. assert(useSplitDwarf() && "No split dwarf?");
  2070. InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
  2071. }
  2072. void DwarfDebug::emitDebugLineDWO() {
  2073. assert(useSplitDwarf() && "No split dwarf?");
  2074. SplitTypeUnitFileTable.Emit(
  2075. *Asm->OutStreamer, MCDwarfLineTableParams(),
  2076. Asm->getObjFileLowering().getDwarfLineDWOSection());
  2077. }
  2078. void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
  2079. assert(useSplitDwarf() && "No split dwarf?");
  2080. InfoHolder.getStringPool().emitStringOffsetsTableHeader(
  2081. *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
  2082. InfoHolder.getStringOffsetsStartSym());
  2083. }
  2084. // Emit the .debug_str.dwo section for separated dwarf. This contains the
  2085. // string section and is identical in format to traditional .debug_str
  2086. // sections.
  2087. void DwarfDebug::emitDebugStrDWO() {
  2088. if (useSegmentedStringOffsetsTable())
  2089. emitStringOffsetsTableHeaderDWO();
  2090. assert(useSplitDwarf() && "No split dwarf?");
  2091. MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
  2092. InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
  2093. OffSec, /* UseRelativeOffsets = */ false);
  2094. }
  2095. // Emit address pool.
  2096. void DwarfDebug::emitDebugAddr() {
  2097. AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
  2098. }
  2099. MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
  2100. if (!useSplitDwarf())
  2101. return nullptr;
  2102. const DICompileUnit *DIUnit = CU.getCUNode();
  2103. SplitTypeUnitFileTable.maybeSetRootFile(
  2104. DIUnit->getDirectory(), DIUnit->getFilename(),
  2105. CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
  2106. return &SplitTypeUnitFileTable;
  2107. }
  2108. uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
  2109. MD5 Hash;
  2110. Hash.update(Identifier);
  2111. // ... take the least significant 8 bytes and return those. Our MD5
  2112. // implementation always returns its results in little endian, so we actually
  2113. // need the "high" word.
  2114. MD5::MD5Result Result;
  2115. Hash.final(Result);
  2116. return Result.high();
  2117. }
  2118. void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
  2119. StringRef Identifier, DIE &RefDie,
  2120. const DICompositeType *CTy) {
  2121. // Fast path if we're building some type units and one has already used the
  2122. // address pool we know we're going to throw away all this work anyway, so
  2123. // don't bother building dependent types.
  2124. if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
  2125. return;
  2126. auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
  2127. if (!Ins.second) {
  2128. CU.addDIETypeSignature(RefDie, Ins.first->second);
  2129. return;
  2130. }
  2131. bool TopLevelType = TypeUnitsUnderConstruction.empty();
  2132. AddrPool.resetUsedFlag();
  2133. auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
  2134. getDwoLineTable(CU));
  2135. DwarfTypeUnit &NewTU = *OwnedUnit;
  2136. DIE &UnitDie = NewTU.getUnitDie();
  2137. TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
  2138. NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  2139. CU.getLanguage());
  2140. uint64_t Signature = makeTypeSignature(Identifier);
  2141. NewTU.setTypeSignature(Signature);
  2142. Ins.first->second = Signature;
  2143. if (useSplitDwarf())
  2144. NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
  2145. else {
  2146. NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature));
  2147. // Non-split type units reuse the compile unit's line table.
  2148. CU.applyStmtList(UnitDie);
  2149. }
  2150. // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
  2151. // units.
  2152. if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
  2153. NewTU.addStringOffsetsStart();
  2154. NewTU.setType(NewTU.createTypeDIE(CTy));
  2155. if (TopLevelType) {
  2156. auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
  2157. TypeUnitsUnderConstruction.clear();
  2158. // Types referencing entries in the address table cannot be placed in type
  2159. // units.
  2160. if (AddrPool.hasBeenUsed()) {
  2161. // Remove all the types built while building this type.
  2162. // This is pessimistic as some of these types might not be dependent on
  2163. // the type that used an address.
  2164. for (const auto &TU : TypeUnitsToAdd)
  2165. TypeSignatures.erase(TU.second);
  2166. // Construct this type in the CU directly.
  2167. // This is inefficient because all the dependent types will be rebuilt
  2168. // from scratch, including building them in type units, discovering that
  2169. // they depend on addresses, throwing them out and rebuilding them.
  2170. CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
  2171. return;
  2172. }
  2173. // If the type wasn't dependent on fission addresses, finish adding the type
  2174. // and all its dependent types.
  2175. for (auto &TU : TypeUnitsToAdd) {
  2176. InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
  2177. InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
  2178. }
  2179. }
  2180. CU.addDIETypeSignature(RefDie, Signature);
  2181. }
  2182. // Add the Name along with its companion DIE to the appropriate accelerator
  2183. // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
  2184. // AccelTableKind::Apple, we use the table we got as an argument). If
  2185. // accelerator tables are disabled, this function does nothing.
  2186. template <typename DataT>
  2187. void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
  2188. AccelTable<DataT> &AppleAccel, StringRef Name,
  2189. const DIE &Die) {
  2190. if (getAccelTableKind() == AccelTableKind::None)
  2191. return;
  2192. if (getAccelTableKind() != AccelTableKind::Apple &&
  2193. CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
  2194. return;
  2195. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  2196. DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
  2197. switch (getAccelTableKind()) {
  2198. case AccelTableKind::Apple:
  2199. AppleAccel.addName(Ref, Die);
  2200. break;
  2201. case AccelTableKind::Dwarf:
  2202. AccelDebugNames.addName(Ref, Die);
  2203. break;
  2204. case AccelTableKind::Default:
  2205. llvm_unreachable("Default should have already been resolved.");
  2206. case AccelTableKind::None:
  2207. llvm_unreachable("None handled above");
  2208. }
  2209. }
  2210. void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
  2211. const DIE &Die) {
  2212. addAccelNameImpl(CU, AccelNames, Name, Die);
  2213. }
  2214. void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
  2215. const DIE &Die) {
  2216. // ObjC names go only into the Apple accelerator tables.
  2217. if (getAccelTableKind() == AccelTableKind::Apple)
  2218. addAccelNameImpl(CU, AccelObjC, Name, Die);
  2219. }
  2220. void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
  2221. const DIE &Die) {
  2222. addAccelNameImpl(CU, AccelNamespace, Name, Die);
  2223. }
  2224. void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
  2225. const DIE &Die, char Flags) {
  2226. addAccelNameImpl(CU, AccelTypes, Name, Die);
  2227. }
  2228. uint16_t DwarfDebug::getDwarfVersion() const {
  2229. return Asm->OutStreamer->getContext().getDwarfVersion();
  2230. }