DwarfDebug.cpp 136 KB

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