DwarfDebug.cpp 115 KB

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