DwarfDebug.cpp 109 KB

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