RewriteStatepointsForGC.cpp 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401
  1. //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
  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. // Rewrite call/invoke instructions so as to make potential relocations
  10. // performed by the garbage collector explicit in the IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/DenseSet.h"
  17. #include "llvm/ADT/MapVector.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SetVector.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/ADT/iterator_range.h"
  24. #include "llvm/Analysis/DomTreeUpdater.h"
  25. #include "llvm/Analysis/TargetLibraryInfo.h"
  26. #include "llvm/Analysis/TargetTransformInfo.h"
  27. #include "llvm/IR/Argument.h"
  28. #include "llvm/IR/Attributes.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/CallingConv.h"
  31. #include "llvm/IR/Constant.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/DerivedTypes.h"
  35. #include "llvm/IR/Dominators.h"
  36. #include "llvm/IR/Function.h"
  37. #include "llvm/IR/IRBuilder.h"
  38. #include "llvm/IR/InstIterator.h"
  39. #include "llvm/IR/InstrTypes.h"
  40. #include "llvm/IR/Instruction.h"
  41. #include "llvm/IR/Instructions.h"
  42. #include "llvm/IR/IntrinsicInst.h"
  43. #include "llvm/IR/Intrinsics.h"
  44. #include "llvm/IR/LLVMContext.h"
  45. #include "llvm/IR/MDBuilder.h"
  46. #include "llvm/IR/Metadata.h"
  47. #include "llvm/IR/Module.h"
  48. #include "llvm/IR/Statepoint.h"
  49. #include "llvm/IR/Type.h"
  50. #include "llvm/IR/User.h"
  51. #include "llvm/IR/Value.h"
  52. #include "llvm/IR/ValueHandle.h"
  53. #include "llvm/InitializePasses.h"
  54. #include "llvm/Pass.h"
  55. #include "llvm/Support/Casting.h"
  56. #include "llvm/Support/CommandLine.h"
  57. #include "llvm/Support/Compiler.h"
  58. #include "llvm/Support/Debug.h"
  59. #include "llvm/Support/ErrorHandling.h"
  60. #include "llvm/Support/raw_ostream.h"
  61. #include "llvm/Transforms/Scalar.h"
  62. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  63. #include "llvm/Transforms/Utils/Local.h"
  64. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  65. #include <algorithm>
  66. #include <cassert>
  67. #include <cstddef>
  68. #include <cstdint>
  69. #include <iterator>
  70. #include <optional>
  71. #include <set>
  72. #include <string>
  73. #include <utility>
  74. #include <vector>
  75. #define DEBUG_TYPE "rewrite-statepoints-for-gc"
  76. using namespace llvm;
  77. // Print the liveset found at the insert location
  78. static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
  79. cl::init(false));
  80. static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
  81. cl::init(false));
  82. // Print out the base pointers for debugging
  83. static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
  84. cl::init(false));
  85. // Cost threshold measuring when it is profitable to rematerialize value instead
  86. // of relocating it
  87. static cl::opt<unsigned>
  88. RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
  89. cl::init(6));
  90. #ifdef EXPENSIVE_CHECKS
  91. static bool ClobberNonLive = true;
  92. #else
  93. static bool ClobberNonLive = false;
  94. #endif
  95. static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
  96. cl::location(ClobberNonLive),
  97. cl::Hidden);
  98. static cl::opt<bool>
  99. AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
  100. cl::Hidden, cl::init(true));
  101. static cl::opt<bool> RematDerivedAtUses("rs4gc-remat-derived-at-uses",
  102. cl::Hidden, cl::init(true));
  103. /// The IR fed into RewriteStatepointsForGC may have had attributes and
  104. /// metadata implying dereferenceability that are no longer valid/correct after
  105. /// RewriteStatepointsForGC has run. This is because semantically, after
  106. /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
  107. /// heap. stripNonValidData (conservatively) restores
  108. /// correctness by erasing all attributes in the module that externally imply
  109. /// dereferenceability. Similar reasoning also applies to the noalias
  110. /// attributes and metadata. gc.statepoint can touch the entire heap including
  111. /// noalias objects.
  112. /// Apart from attributes and metadata, we also remove instructions that imply
  113. /// constant physical memory: llvm.invariant.start.
  114. static void stripNonValidData(Module &M);
  115. static bool shouldRewriteStatepointsIn(Function &F);
  116. PreservedAnalyses RewriteStatepointsForGC::run(Module &M,
  117. ModuleAnalysisManager &AM) {
  118. bool Changed = false;
  119. auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  120. for (Function &F : M) {
  121. // Nothing to do for declarations.
  122. if (F.isDeclaration() || F.empty())
  123. continue;
  124. // Policy choice says not to rewrite - the most common reason is that we're
  125. // compiling code without a GCStrategy.
  126. if (!shouldRewriteStatepointsIn(F))
  127. continue;
  128. auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
  129. auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
  130. auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
  131. Changed |= runOnFunction(F, DT, TTI, TLI);
  132. }
  133. if (!Changed)
  134. return PreservedAnalyses::all();
  135. // stripNonValidData asserts that shouldRewriteStatepointsIn
  136. // returns true for at least one function in the module. Since at least
  137. // one function changed, we know that the precondition is satisfied.
  138. stripNonValidData(M);
  139. PreservedAnalyses PA;
  140. PA.preserve<TargetIRAnalysis>();
  141. PA.preserve<TargetLibraryAnalysis>();
  142. return PA;
  143. }
  144. namespace {
  145. class RewriteStatepointsForGCLegacyPass : public ModulePass {
  146. RewriteStatepointsForGC Impl;
  147. public:
  148. static char ID; // Pass identification, replacement for typeid
  149. RewriteStatepointsForGCLegacyPass() : ModulePass(ID), Impl() {
  150. initializeRewriteStatepointsForGCLegacyPassPass(
  151. *PassRegistry::getPassRegistry());
  152. }
  153. bool runOnModule(Module &M) override {
  154. bool Changed = false;
  155. for (Function &F : M) {
  156. // Nothing to do for declarations.
  157. if (F.isDeclaration() || F.empty())
  158. continue;
  159. // Policy choice says not to rewrite - the most common reason is that
  160. // we're compiling code without a GCStrategy.
  161. if (!shouldRewriteStatepointsIn(F))
  162. continue;
  163. TargetTransformInfo &TTI =
  164. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  165. const TargetLibraryInfo &TLI =
  166. getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  167. auto &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
  168. Changed |= Impl.runOnFunction(F, DT, TTI, TLI);
  169. }
  170. if (!Changed)
  171. return false;
  172. // stripNonValidData asserts that shouldRewriteStatepointsIn
  173. // returns true for at least one function in the module. Since at least
  174. // one function changed, we know that the precondition is satisfied.
  175. stripNonValidData(M);
  176. return true;
  177. }
  178. void getAnalysisUsage(AnalysisUsage &AU) const override {
  179. // We add and rewrite a bunch of instructions, but don't really do much
  180. // else. We could in theory preserve a lot more analyses here.
  181. AU.addRequired<DominatorTreeWrapperPass>();
  182. AU.addRequired<TargetTransformInfoWrapperPass>();
  183. AU.addRequired<TargetLibraryInfoWrapperPass>();
  184. }
  185. };
  186. } // end anonymous namespace
  187. char RewriteStatepointsForGCLegacyPass::ID = 0;
  188. ModulePass *llvm::createRewriteStatepointsForGCLegacyPass() {
  189. return new RewriteStatepointsForGCLegacyPass();
  190. }
  191. INITIALIZE_PASS_BEGIN(RewriteStatepointsForGCLegacyPass,
  192. "rewrite-statepoints-for-gc",
  193. "Make relocations explicit at statepoints", false, false)
  194. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  195. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  196. INITIALIZE_PASS_END(RewriteStatepointsForGCLegacyPass,
  197. "rewrite-statepoints-for-gc",
  198. "Make relocations explicit at statepoints", false, false)
  199. namespace {
  200. struct GCPtrLivenessData {
  201. /// Values defined in this block.
  202. MapVector<BasicBlock *, SetVector<Value *>> KillSet;
  203. /// Values used in this block (and thus live); does not included values
  204. /// killed within this block.
  205. MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
  206. /// Values live into this basic block (i.e. used by any
  207. /// instruction in this basic block or ones reachable from here)
  208. MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
  209. /// Values live out of this basic block (i.e. live into
  210. /// any successor block)
  211. MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
  212. };
  213. // The type of the internal cache used inside the findBasePointers family
  214. // of functions. From the callers perspective, this is an opaque type and
  215. // should not be inspected.
  216. //
  217. // In the actual implementation this caches two relations:
  218. // - The base relation itself (i.e. this pointer is based on that one)
  219. // - The base defining value relation (i.e. before base_phi insertion)
  220. // Generally, after the execution of a full findBasePointer call, only the
  221. // base relation will remain. Internally, we add a mixture of the two
  222. // types, then update all the second type to the first type
  223. using DefiningValueMapTy = MapVector<Value *, Value *>;
  224. using IsKnownBaseMapTy = MapVector<Value *, bool>;
  225. using PointerToBaseTy = MapVector<Value *, Value *>;
  226. using StatepointLiveSetTy = SetVector<Value *>;
  227. using RematerializedValueMapTy =
  228. MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
  229. struct PartiallyConstructedSafepointRecord {
  230. /// The set of values known to be live across this safepoint
  231. StatepointLiveSetTy LiveSet;
  232. /// The *new* gc.statepoint instruction itself. This produces the token
  233. /// that normal path gc.relocates and the gc.result are tied to.
  234. GCStatepointInst *StatepointToken;
  235. /// Instruction to which exceptional gc relocates are attached
  236. /// Makes it easier to iterate through them during relocationViaAlloca.
  237. Instruction *UnwindToken;
  238. /// Record live values we are rematerialized instead of relocating.
  239. /// They are not included into 'LiveSet' field.
  240. /// Maps rematerialized copy to it's original value.
  241. RematerializedValueMapTy RematerializedValues;
  242. };
  243. struct RematerizlizationCandidateRecord {
  244. // Chain from derived pointer to base.
  245. SmallVector<Instruction *, 3> ChainToBase;
  246. // Original base.
  247. Value *RootOfChain;
  248. // Cost of chain.
  249. InstructionCost Cost;
  250. };
  251. using RematCandTy = MapVector<Value *, RematerizlizationCandidateRecord>;
  252. } // end anonymous namespace
  253. static ArrayRef<Use> GetDeoptBundleOperands(const CallBase *Call) {
  254. std::optional<OperandBundleUse> DeoptBundle =
  255. Call->getOperandBundle(LLVMContext::OB_deopt);
  256. if (!DeoptBundle) {
  257. assert(AllowStatepointWithNoDeoptInfo &&
  258. "Found non-leaf call without deopt info!");
  259. return std::nullopt;
  260. }
  261. return DeoptBundle->Inputs;
  262. }
  263. /// Compute the live-in set for every basic block in the function
  264. static void computeLiveInValues(DominatorTree &DT, Function &F,
  265. GCPtrLivenessData &Data);
  266. /// Given results from the dataflow liveness computation, find the set of live
  267. /// Values at a particular instruction.
  268. static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
  269. StatepointLiveSetTy &out);
  270. // TODO: Once we can get to the GCStrategy, this becomes
  271. // std::optional<bool> isGCManagedPointer(const Type *Ty) const override {
  272. static bool isGCPointerType(Type *T) {
  273. if (auto *PT = dyn_cast<PointerType>(T))
  274. // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
  275. // GC managed heap. We know that a pointer into this heap needs to be
  276. // updated and that no other pointer does.
  277. return PT->getAddressSpace() == 1;
  278. return false;
  279. }
  280. // Return true if this type is one which a) is a gc pointer or contains a GC
  281. // pointer and b) is of a type this code expects to encounter as a live value.
  282. // (The insertion code will assert that a type which matches (a) and not (b)
  283. // is not encountered.)
  284. static bool isHandledGCPointerType(Type *T) {
  285. // We fully support gc pointers
  286. if (isGCPointerType(T))
  287. return true;
  288. // We partially support vectors of gc pointers. The code will assert if it
  289. // can't handle something.
  290. if (auto VT = dyn_cast<VectorType>(T))
  291. if (isGCPointerType(VT->getElementType()))
  292. return true;
  293. return false;
  294. }
  295. #ifndef NDEBUG
  296. /// Returns true if this type contains a gc pointer whether we know how to
  297. /// handle that type or not.
  298. static bool containsGCPtrType(Type *Ty) {
  299. if (isGCPointerType(Ty))
  300. return true;
  301. if (VectorType *VT = dyn_cast<VectorType>(Ty))
  302. return isGCPointerType(VT->getScalarType());
  303. if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
  304. return containsGCPtrType(AT->getElementType());
  305. if (StructType *ST = dyn_cast<StructType>(Ty))
  306. return llvm::any_of(ST->elements(), containsGCPtrType);
  307. return false;
  308. }
  309. // Returns true if this is a type which a) is a gc pointer or contains a GC
  310. // pointer and b) is of a type which the code doesn't expect (i.e. first class
  311. // aggregates). Used to trip assertions.
  312. static bool isUnhandledGCPointerType(Type *Ty) {
  313. return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
  314. }
  315. #endif
  316. // Return the name of the value suffixed with the provided value, or if the
  317. // value didn't have a name, the default value specified.
  318. static std::string suffixed_name_or(Value *V, StringRef Suffix,
  319. StringRef DefaultName) {
  320. return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
  321. }
  322. // Conservatively identifies any definitions which might be live at the
  323. // given instruction. The analysis is performed immediately before the
  324. // given instruction. Values defined by that instruction are not considered
  325. // live. Values used by that instruction are considered live.
  326. static void analyzeParsePointLiveness(
  327. DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallBase *Call,
  328. PartiallyConstructedSafepointRecord &Result) {
  329. StatepointLiveSetTy LiveSet;
  330. findLiveSetAtInst(Call, OriginalLivenessData, LiveSet);
  331. if (PrintLiveSet) {
  332. dbgs() << "Live Variables:\n";
  333. for (Value *V : LiveSet)
  334. dbgs() << " " << V->getName() << " " << *V << "\n";
  335. }
  336. if (PrintLiveSetSize) {
  337. dbgs() << "Safepoint For: " << Call->getCalledOperand()->getName() << "\n";
  338. dbgs() << "Number live values: " << LiveSet.size() << "\n";
  339. }
  340. Result.LiveSet = LiveSet;
  341. }
  342. /// Returns true if V is a known base.
  343. static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases);
  344. /// Caches the IsKnownBase flag for a value and asserts that it wasn't present
  345. /// in the cache before.
  346. static void setKnownBase(Value *V, bool IsKnownBase,
  347. IsKnownBaseMapTy &KnownBases);
  348. static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
  349. IsKnownBaseMapTy &KnownBases);
  350. /// Return a base defining value for the 'Index' element of the given vector
  351. /// instruction 'I'. If Index is null, returns a BDV for the entire vector
  352. /// 'I'. As an optimization, this method will try to determine when the
  353. /// element is known to already be a base pointer. If this can be established,
  354. /// the second value in the returned pair will be true. Note that either a
  355. /// vector or a pointer typed value can be returned. For the former, the
  356. /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
  357. /// If the later, the return pointer is a BDV (or possibly a base) for the
  358. /// particular element in 'I'.
  359. static Value *findBaseDefiningValueOfVector(Value *I, DefiningValueMapTy &Cache,
  360. IsKnownBaseMapTy &KnownBases) {
  361. // Each case parallels findBaseDefiningValue below, see that code for
  362. // detailed motivation.
  363. auto Cached = Cache.find(I);
  364. if (Cached != Cache.end())
  365. return Cached->second;
  366. if (isa<Argument>(I)) {
  367. // An incoming argument to the function is a base pointer
  368. Cache[I] = I;
  369. setKnownBase(I, /* IsKnownBase */true, KnownBases);
  370. return I;
  371. }
  372. if (isa<Constant>(I)) {
  373. // Base of constant vector consists only of constant null pointers.
  374. // For reasoning see similar case inside 'findBaseDefiningValue' function.
  375. auto *CAZ = ConstantAggregateZero::get(I->getType());
  376. Cache[I] = CAZ;
  377. setKnownBase(CAZ, /* IsKnownBase */true, KnownBases);
  378. return CAZ;
  379. }
  380. if (isa<LoadInst>(I)) {
  381. Cache[I] = I;
  382. setKnownBase(I, /* IsKnownBase */true, KnownBases);
  383. return I;
  384. }
  385. if (isa<InsertElementInst>(I)) {
  386. // We don't know whether this vector contains entirely base pointers or
  387. // not. To be conservatively correct, we treat it as a BDV and will
  388. // duplicate code as needed to construct a parallel vector of bases.
  389. Cache[I] = I;
  390. setKnownBase(I, /* IsKnownBase */false, KnownBases);
  391. return I;
  392. }
  393. if (isa<ShuffleVectorInst>(I)) {
  394. // We don't know whether this vector contains entirely base pointers or
  395. // not. To be conservatively correct, we treat it as a BDV and will
  396. // duplicate code as needed to construct a parallel vector of bases.
  397. // TODO: There a number of local optimizations which could be applied here
  398. // for particular sufflevector patterns.
  399. Cache[I] = I;
  400. setKnownBase(I, /* IsKnownBase */false, KnownBases);
  401. return I;
  402. }
  403. // The behavior of getelementptr instructions is the same for vector and
  404. // non-vector data types.
  405. if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
  406. auto *BDV =
  407. findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
  408. Cache[GEP] = BDV;
  409. return BDV;
  410. }
  411. // The behavior of freeze instructions is the same for vector and
  412. // non-vector data types.
  413. if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
  414. auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
  415. Cache[Freeze] = BDV;
  416. return BDV;
  417. }
  418. // If the pointer comes through a bitcast of a vector of pointers to
  419. // a vector of another type of pointer, then look through the bitcast
  420. if (auto *BC = dyn_cast<BitCastInst>(I)) {
  421. auto *BDV = findBaseDefiningValue(BC->getOperand(0), Cache, KnownBases);
  422. Cache[BC] = BDV;
  423. return BDV;
  424. }
  425. // We assume that functions in the source language only return base
  426. // pointers. This should probably be generalized via attributes to support
  427. // both source language and internal functions.
  428. if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
  429. Cache[I] = I;
  430. setKnownBase(I, /* IsKnownBase */true, KnownBases);
  431. return I;
  432. }
  433. // A PHI or Select is a base defining value. The outer findBasePointer
  434. // algorithm is responsible for constructing a base value for this BDV.
  435. assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
  436. "unknown vector instruction - no base found for vector element");
  437. Cache[I] = I;
  438. setKnownBase(I, /* IsKnownBase */false, KnownBases);
  439. return I;
  440. }
  441. /// Helper function for findBasePointer - Will return a value which either a)
  442. /// defines the base pointer for the input, b) blocks the simple search
  443. /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
  444. /// from pointer to vector type or back.
  445. static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
  446. IsKnownBaseMapTy &KnownBases) {
  447. assert(I->getType()->isPtrOrPtrVectorTy() &&
  448. "Illegal to ask for the base pointer of a non-pointer type");
  449. auto Cached = Cache.find(I);
  450. if (Cached != Cache.end())
  451. return Cached->second;
  452. if (I->getType()->isVectorTy())
  453. return findBaseDefiningValueOfVector(I, Cache, KnownBases);
  454. if (isa<Argument>(I)) {
  455. // An incoming argument to the function is a base pointer
  456. // We should have never reached here if this argument isn't an gc value
  457. Cache[I] = I;
  458. setKnownBase(I, /* IsKnownBase */true, KnownBases);
  459. return I;
  460. }
  461. if (isa<Constant>(I)) {
  462. // We assume that objects with a constant base (e.g. a global) can't move
  463. // and don't need to be reported to the collector because they are always
  464. // live. Besides global references, all kinds of constants (e.g. undef,
  465. // constant expressions, null pointers) can be introduced by the inliner or
  466. // the optimizer, especially on dynamically dead paths.
  467. // Here we treat all of them as having single null base. By doing this we
  468. // trying to avoid problems reporting various conflicts in a form of
  469. // "phi (const1, const2)" or "phi (const, regular gc ptr)".
  470. // See constant.ll file for relevant test cases.
  471. auto *CPN = ConstantPointerNull::get(cast<PointerType>(I->getType()));
  472. Cache[I] = CPN;
  473. setKnownBase(CPN, /* IsKnownBase */true, KnownBases);
  474. return CPN;
  475. }
  476. // inttoptrs in an integral address space are currently ill-defined. We
  477. // treat them as defining base pointers here for consistency with the
  478. // constant rule above and because we don't really have a better semantic
  479. // to give them. Note that the optimizer is always free to insert undefined
  480. // behavior on dynamically dead paths as well.
  481. if (isa<IntToPtrInst>(I)) {
  482. Cache[I] = I;
  483. setKnownBase(I, /* IsKnownBase */true, KnownBases);
  484. return I;
  485. }
  486. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  487. Value *Def = CI->stripPointerCasts();
  488. // If stripping pointer casts changes the address space there is an
  489. // addrspacecast in between.
  490. assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
  491. cast<PointerType>(CI->getType())->getAddressSpace() &&
  492. "unsupported addrspacecast");
  493. // If we find a cast instruction here, it means we've found a cast which is
  494. // not simply a pointer cast (i.e. an inttoptr). We don't know how to
  495. // handle int->ptr conversion.
  496. assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
  497. auto *BDV = findBaseDefiningValue(Def, Cache, KnownBases);
  498. Cache[CI] = BDV;
  499. return BDV;
  500. }
  501. if (isa<LoadInst>(I)) {
  502. // The value loaded is an gc base itself
  503. Cache[I] = I;
  504. setKnownBase(I, /* IsKnownBase */true, KnownBases);
  505. return I;
  506. }
  507. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
  508. // The base of this GEP is the base
  509. auto *BDV =
  510. findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
  511. Cache[GEP] = BDV;
  512. return BDV;
  513. }
  514. if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
  515. auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
  516. Cache[Freeze] = BDV;
  517. return BDV;
  518. }
  519. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  520. switch (II->getIntrinsicID()) {
  521. default:
  522. // fall through to general call handling
  523. break;
  524. case Intrinsic::experimental_gc_statepoint:
  525. llvm_unreachable("statepoints don't produce pointers");
  526. case Intrinsic::experimental_gc_relocate:
  527. // Rerunning safepoint insertion after safepoints are already
  528. // inserted is not supported. It could probably be made to work,
  529. // but why are you doing this? There's no good reason.
  530. llvm_unreachable("repeat safepoint insertion is not supported");
  531. case Intrinsic::gcroot:
  532. // Currently, this mechanism hasn't been extended to work with gcroot.
  533. // There's no reason it couldn't be, but I haven't thought about the
  534. // implications much.
  535. llvm_unreachable(
  536. "interaction with the gcroot mechanism is not supported");
  537. case Intrinsic::experimental_gc_get_pointer_base:
  538. auto *BDV = findBaseDefiningValue(II->getOperand(0), Cache, KnownBases);
  539. Cache[II] = BDV;
  540. return BDV;
  541. }
  542. }
  543. // We assume that functions in the source language only return base
  544. // pointers. This should probably be generalized via attributes to support
  545. // both source language and internal functions.
  546. if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
  547. Cache[I] = I;
  548. setKnownBase(I, /* IsKnownBase */true, KnownBases);
  549. return I;
  550. }
  551. // TODO: I have absolutely no idea how to implement this part yet. It's not
  552. // necessarily hard, I just haven't really looked at it yet.
  553. assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
  554. if (isa<AtomicCmpXchgInst>(I)) {
  555. // A CAS is effectively a atomic store and load combined under a
  556. // predicate. From the perspective of base pointers, we just treat it
  557. // like a load.
  558. Cache[I] = I;
  559. setKnownBase(I, /* IsKnownBase */true, KnownBases);
  560. return I;
  561. }
  562. assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
  563. "binary ops which don't apply to pointers");
  564. // The aggregate ops. Aggregates can either be in the heap or on the
  565. // stack, but in either case, this is simply a field load. As a result,
  566. // this is a defining definition of the base just like a load is.
  567. if (isa<ExtractValueInst>(I)) {
  568. Cache[I] = I;
  569. setKnownBase(I, /* IsKnownBase */true, KnownBases);
  570. return I;
  571. }
  572. // We should never see an insert vector since that would require we be
  573. // tracing back a struct value not a pointer value.
  574. assert(!isa<InsertValueInst>(I) &&
  575. "Base pointer for a struct is meaningless");
  576. // This value might have been generated by findBasePointer() called when
  577. // substituting gc.get.pointer.base() intrinsic.
  578. bool IsKnownBase =
  579. isa<Instruction>(I) && cast<Instruction>(I)->getMetadata("is_base_value");
  580. setKnownBase(I, /* IsKnownBase */IsKnownBase, KnownBases);
  581. Cache[I] = I;
  582. // An extractelement produces a base result exactly when it's input does.
  583. // We may need to insert a parallel instruction to extract the appropriate
  584. // element out of the base vector corresponding to the input. Given this,
  585. // it's analogous to the phi and select case even though it's not a merge.
  586. if (isa<ExtractElementInst>(I))
  587. // Note: There a lot of obvious peephole cases here. This are deliberately
  588. // handled after the main base pointer inference algorithm to make writing
  589. // test cases to exercise that code easier.
  590. return I;
  591. // The last two cases here don't return a base pointer. Instead, they
  592. // return a value which dynamically selects from among several base
  593. // derived pointers (each with it's own base potentially). It's the job of
  594. // the caller to resolve these.
  595. assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
  596. "missing instruction case in findBaseDefiningValue");
  597. return I;
  598. }
  599. /// Returns the base defining value for this value.
  600. static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache,
  601. IsKnownBaseMapTy &KnownBases) {
  602. if (Cache.find(I) == Cache.end()) {
  603. auto *BDV = findBaseDefiningValue(I, Cache, KnownBases);
  604. Cache[I] = BDV;
  605. LLVM_DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
  606. << Cache[I]->getName() << ", is known base = "
  607. << KnownBases[I] << "\n");
  608. }
  609. assert(Cache[I] != nullptr);
  610. assert(KnownBases.find(Cache[I]) != KnownBases.end() &&
  611. "Cached value must be present in known bases map");
  612. return Cache[I];
  613. }
  614. /// Return a base pointer for this value if known. Otherwise, return it's
  615. /// base defining value.
  616. static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache,
  617. IsKnownBaseMapTy &KnownBases) {
  618. Value *Def = findBaseDefiningValueCached(I, Cache, KnownBases);
  619. auto Found = Cache.find(Def);
  620. if (Found != Cache.end()) {
  621. // Either a base-of relation, or a self reference. Caller must check.
  622. return Found->second;
  623. }
  624. // Only a BDV available
  625. return Def;
  626. }
  627. #ifndef NDEBUG
  628. /// This value is a base pointer that is not generated by RS4GC, i.e. it already
  629. /// exists in the code.
  630. static bool isOriginalBaseResult(Value *V) {
  631. // no recursion possible
  632. return !isa<PHINode>(V) && !isa<SelectInst>(V) &&
  633. !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
  634. !isa<ShuffleVectorInst>(V);
  635. }
  636. #endif
  637. static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases) {
  638. auto It = KnownBases.find(V);
  639. assert(It != KnownBases.end() && "Value not present in the map");
  640. return It->second;
  641. }
  642. static void setKnownBase(Value *V, bool IsKnownBase,
  643. IsKnownBaseMapTy &KnownBases) {
  644. #ifndef NDEBUG
  645. auto It = KnownBases.find(V);
  646. if (It != KnownBases.end())
  647. assert(It->second == IsKnownBase && "Changing already present value");
  648. #endif
  649. KnownBases[V] = IsKnownBase;
  650. }
  651. // Returns true if First and Second values are both scalar or both vector.
  652. static bool areBothVectorOrScalar(Value *First, Value *Second) {
  653. return isa<VectorType>(First->getType()) ==
  654. isa<VectorType>(Second->getType());
  655. }
  656. namespace {
  657. /// Models the state of a single base defining value in the findBasePointer
  658. /// algorithm for determining where a new instruction is needed to propagate
  659. /// the base of this BDV.
  660. class BDVState {
  661. public:
  662. enum StatusTy {
  663. // Starting state of lattice
  664. Unknown,
  665. // Some specific base value -- does *not* mean that instruction
  666. // propagates the base of the object
  667. // ex: gep %arg, 16 -> %arg is the base value
  668. Base,
  669. // Need to insert a node to represent a merge.
  670. Conflict
  671. };
  672. BDVState() {
  673. llvm_unreachable("missing state in map");
  674. }
  675. explicit BDVState(Value *OriginalValue)
  676. : OriginalValue(OriginalValue) {}
  677. explicit BDVState(Value *OriginalValue, StatusTy Status, Value *BaseValue = nullptr)
  678. : OriginalValue(OriginalValue), Status(Status), BaseValue(BaseValue) {
  679. assert(Status != Base || BaseValue);
  680. }
  681. StatusTy getStatus() const { return Status; }
  682. Value *getOriginalValue() const { return OriginalValue; }
  683. Value *getBaseValue() const { return BaseValue; }
  684. bool isBase() const { return getStatus() == Base; }
  685. bool isUnknown() const { return getStatus() == Unknown; }
  686. bool isConflict() const { return getStatus() == Conflict; }
  687. // Values of type BDVState form a lattice, and this function implements the
  688. // meet
  689. // operation.
  690. void meet(const BDVState &Other) {
  691. auto markConflict = [&]() {
  692. Status = BDVState::Conflict;
  693. BaseValue = nullptr;
  694. };
  695. // Conflict is a final state.
  696. if (isConflict())
  697. return;
  698. // if we are not known - just take other state.
  699. if (isUnknown()) {
  700. Status = Other.getStatus();
  701. BaseValue = Other.getBaseValue();
  702. return;
  703. }
  704. // We are base.
  705. assert(isBase() && "Unknown state");
  706. // If other is unknown - just keep our state.
  707. if (Other.isUnknown())
  708. return;
  709. // If other is conflict - it is a final state.
  710. if (Other.isConflict())
  711. return markConflict();
  712. // Other is base as well.
  713. assert(Other.isBase() && "Unknown state");
  714. // If bases are different - Conflict.
  715. if (getBaseValue() != Other.getBaseValue())
  716. return markConflict();
  717. // We are identical, do nothing.
  718. }
  719. bool operator==(const BDVState &Other) const {
  720. return OriginalValue == Other.OriginalValue && BaseValue == Other.BaseValue &&
  721. Status == Other.Status;
  722. }
  723. bool operator!=(const BDVState &other) const { return !(*this == other); }
  724. LLVM_DUMP_METHOD
  725. void dump() const {
  726. print(dbgs());
  727. dbgs() << '\n';
  728. }
  729. void print(raw_ostream &OS) const {
  730. switch (getStatus()) {
  731. case Unknown:
  732. OS << "U";
  733. break;
  734. case Base:
  735. OS << "B";
  736. break;
  737. case Conflict:
  738. OS << "C";
  739. break;
  740. }
  741. OS << " (base " << getBaseValue() << " - "
  742. << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << ")"
  743. << " for " << OriginalValue->getName() << ":";
  744. }
  745. private:
  746. AssertingVH<Value> OriginalValue; // instruction this state corresponds to
  747. StatusTy Status = Unknown;
  748. AssertingVH<Value> BaseValue = nullptr; // Non-null only if Status == Base.
  749. };
  750. } // end anonymous namespace
  751. #ifndef NDEBUG
  752. static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
  753. State.print(OS);
  754. return OS;
  755. }
  756. #endif
  757. /// For a given value or instruction, figure out what base ptr its derived from.
  758. /// For gc objects, this is simply itself. On success, returns a value which is
  759. /// the base pointer. (This is reliable and can be used for relocation.) On
  760. /// failure, returns nullptr.
  761. static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache,
  762. IsKnownBaseMapTy &KnownBases) {
  763. Value *Def = findBaseOrBDV(I, Cache, KnownBases);
  764. if (isKnownBase(Def, KnownBases) && areBothVectorOrScalar(Def, I))
  765. return Def;
  766. // Here's the rough algorithm:
  767. // - For every SSA value, construct a mapping to either an actual base
  768. // pointer or a PHI which obscures the base pointer.
  769. // - Construct a mapping from PHI to unknown TOP state. Use an
  770. // optimistic algorithm to propagate base pointer information. Lattice
  771. // looks like:
  772. // UNKNOWN
  773. // b1 b2 b3 b4
  774. // CONFLICT
  775. // When algorithm terminates, all PHIs will either have a single concrete
  776. // base or be in a conflict state.
  777. // - For every conflict, insert a dummy PHI node without arguments. Add
  778. // these to the base[Instruction] = BasePtr mapping. For every
  779. // non-conflict, add the actual base.
  780. // - For every conflict, add arguments for the base[a] of each input
  781. // arguments.
  782. //
  783. // Note: A simpler form of this would be to add the conflict form of all
  784. // PHIs without running the optimistic algorithm. This would be
  785. // analogous to pessimistic data flow and would likely lead to an
  786. // overall worse solution.
  787. #ifndef NDEBUG
  788. auto isExpectedBDVType = [](Value *BDV) {
  789. return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
  790. isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
  791. isa<ShuffleVectorInst>(BDV);
  792. };
  793. #endif
  794. // Once populated, will contain a mapping from each potentially non-base BDV
  795. // to a lattice value (described above) which corresponds to that BDV.
  796. // We use the order of insertion (DFS over the def/use graph) to provide a
  797. // stable deterministic ordering for visiting DenseMaps (which are unordered)
  798. // below. This is important for deterministic compilation.
  799. MapVector<Value *, BDVState> States;
  800. #ifndef NDEBUG
  801. auto VerifyStates = [&]() {
  802. for (auto &Entry : States) {
  803. assert(Entry.first == Entry.second.getOriginalValue());
  804. }
  805. };
  806. #endif
  807. auto visitBDVOperands = [](Value *BDV, std::function<void (Value*)> F) {
  808. if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
  809. for (Value *InVal : PN->incoming_values())
  810. F(InVal);
  811. } else if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
  812. F(SI->getTrueValue());
  813. F(SI->getFalseValue());
  814. } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
  815. F(EE->getVectorOperand());
  816. } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)) {
  817. F(IE->getOperand(0));
  818. F(IE->getOperand(1));
  819. } else if (auto *SV = dyn_cast<ShuffleVectorInst>(BDV)) {
  820. // For a canonical broadcast, ignore the undef argument
  821. // (without this, we insert a parallel base shuffle for every broadcast)
  822. F(SV->getOperand(0));
  823. if (!SV->isZeroEltSplat())
  824. F(SV->getOperand(1));
  825. } else {
  826. llvm_unreachable("unexpected BDV type");
  827. }
  828. };
  829. // Recursively fill in all base defining values reachable from the initial
  830. // one for which we don't already know a definite base value for
  831. /* scope */ {
  832. SmallVector<Value*, 16> Worklist;
  833. Worklist.push_back(Def);
  834. States.insert({Def, BDVState(Def)});
  835. while (!Worklist.empty()) {
  836. Value *Current = Worklist.pop_back_val();
  837. assert(!isOriginalBaseResult(Current) && "why did it get added?");
  838. auto visitIncomingValue = [&](Value *InVal) {
  839. Value *Base = findBaseOrBDV(InVal, Cache, KnownBases);
  840. if (isKnownBase(Base, KnownBases) && areBothVectorOrScalar(Base, InVal))
  841. // Known bases won't need new instructions introduced and can be
  842. // ignored safely. However, this can only be done when InVal and Base
  843. // are both scalar or both vector. Otherwise, we need to find a
  844. // correct BDV for InVal, by creating an entry in the lattice
  845. // (States).
  846. return;
  847. assert(isExpectedBDVType(Base) && "the only non-base values "
  848. "we see should be base defining values");
  849. if (States.insert(std::make_pair(Base, BDVState(Base))).second)
  850. Worklist.push_back(Base);
  851. };
  852. visitBDVOperands(Current, visitIncomingValue);
  853. }
  854. }
  855. #ifndef NDEBUG
  856. VerifyStates();
  857. LLVM_DEBUG(dbgs() << "States after initialization:\n");
  858. for (const auto &Pair : States) {
  859. LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
  860. }
  861. #endif
  862. // Iterate forward through the value graph pruning any node from the state
  863. // list where all of the inputs are base pointers. The purpose of this is to
  864. // reuse existing values when the derived pointer we were asked to materialize
  865. // a base pointer for happens to be a base pointer itself. (Or a sub-graph
  866. // feeding it does.)
  867. SmallVector<Value *> ToRemove;
  868. do {
  869. ToRemove.clear();
  870. for (auto Pair : States) {
  871. Value *BDV = Pair.first;
  872. auto canPruneInput = [&](Value *V) {
  873. // If the input of the BDV is the BDV itself we can prune it. This is
  874. // only possible if the BDV is a PHI node.
  875. if (V->stripPointerCasts() == BDV)
  876. return true;
  877. Value *VBDV = findBaseOrBDV(V, Cache, KnownBases);
  878. if (V->stripPointerCasts() != VBDV)
  879. return false;
  880. // The assumption is that anything not in the state list is
  881. // propagates a base pointer.
  882. return States.count(VBDV) == 0;
  883. };
  884. bool CanPrune = true;
  885. visitBDVOperands(BDV, [&](Value *Op) {
  886. CanPrune = CanPrune && canPruneInput(Op);
  887. });
  888. if (CanPrune)
  889. ToRemove.push_back(BDV);
  890. }
  891. for (Value *V : ToRemove) {
  892. States.erase(V);
  893. // Cache the fact V is it's own base for later usage.
  894. Cache[V] = V;
  895. }
  896. } while (!ToRemove.empty());
  897. // Did we manage to prove that Def itself must be a base pointer?
  898. if (!States.count(Def))
  899. return Def;
  900. // Return a phi state for a base defining value. We'll generate a new
  901. // base state for known bases and expect to find a cached state otherwise.
  902. auto GetStateForBDV = [&](Value *BaseValue, Value *Input) {
  903. auto I = States.find(BaseValue);
  904. if (I != States.end())
  905. return I->second;
  906. assert(areBothVectorOrScalar(BaseValue, Input));
  907. return BDVState(BaseValue, BDVState::Base, BaseValue);
  908. };
  909. bool Progress = true;
  910. while (Progress) {
  911. #ifndef NDEBUG
  912. const size_t OldSize = States.size();
  913. #endif
  914. Progress = false;
  915. // We're only changing values in this loop, thus safe to keep iterators.
  916. // Since this is computing a fixed point, the order of visit does not
  917. // effect the result. TODO: We could use a worklist here and make this run
  918. // much faster.
  919. for (auto Pair : States) {
  920. Value *BDV = Pair.first;
  921. // Only values that do not have known bases or those that have differing
  922. // type (scalar versus vector) from a possible known base should be in the
  923. // lattice.
  924. assert((!isKnownBase(BDV, KnownBases) ||
  925. !areBothVectorOrScalar(BDV, Pair.second.getBaseValue())) &&
  926. "why did it get added?");
  927. BDVState NewState(BDV);
  928. visitBDVOperands(BDV, [&](Value *Op) {
  929. Value *BDV = findBaseOrBDV(Op, Cache, KnownBases);
  930. auto OpState = GetStateForBDV(BDV, Op);
  931. NewState.meet(OpState);
  932. });
  933. BDVState OldState = States[BDV];
  934. if (OldState != NewState) {
  935. Progress = true;
  936. States[BDV] = NewState;
  937. }
  938. }
  939. assert(OldSize == States.size() &&
  940. "fixed point shouldn't be adding any new nodes to state");
  941. }
  942. #ifndef NDEBUG
  943. VerifyStates();
  944. LLVM_DEBUG(dbgs() << "States after meet iteration:\n");
  945. for (const auto &Pair : States) {
  946. LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
  947. }
  948. #endif
  949. // Handle all instructions that have a vector BDV, but the instruction itself
  950. // is of scalar type.
  951. for (auto Pair : States) {
  952. Instruction *I = cast<Instruction>(Pair.first);
  953. BDVState State = Pair.second;
  954. auto *BaseValue = State.getBaseValue();
  955. // Only values that do not have known bases or those that have differing
  956. // type (scalar versus vector) from a possible known base should be in the
  957. // lattice.
  958. assert(
  959. (!isKnownBase(I, KnownBases) || !areBothVectorOrScalar(I, BaseValue)) &&
  960. "why did it get added?");
  961. assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
  962. if (!State.isBase() || !isa<VectorType>(BaseValue->getType()))
  963. continue;
  964. // extractelement instructions are a bit special in that we may need to
  965. // insert an extract even when we know an exact base for the instruction.
  966. // The problem is that we need to convert from a vector base to a scalar
  967. // base for the particular indice we're interested in.
  968. if (isa<ExtractElementInst>(I)) {
  969. auto *EE = cast<ExtractElementInst>(I);
  970. // TODO: In many cases, the new instruction is just EE itself. We should
  971. // exploit this, but can't do it here since it would break the invariant
  972. // about the BDV not being known to be a base.
  973. auto *BaseInst = ExtractElementInst::Create(
  974. State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
  975. BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
  976. States[I] = BDVState(I, BDVState::Base, BaseInst);
  977. setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
  978. } else if (!isa<VectorType>(I->getType())) {
  979. // We need to handle cases that have a vector base but the instruction is
  980. // a scalar type (these could be phis or selects or any instruction that
  981. // are of scalar type, but the base can be a vector type). We
  982. // conservatively set this as conflict. Setting the base value for these
  983. // conflicts is handled in the next loop which traverses States.
  984. States[I] = BDVState(I, BDVState::Conflict);
  985. }
  986. }
  987. #ifndef NDEBUG
  988. VerifyStates();
  989. #endif
  990. // Insert Phis for all conflicts
  991. // TODO: adjust naming patterns to avoid this order of iteration dependency
  992. for (auto Pair : States) {
  993. Instruction *I = cast<Instruction>(Pair.first);
  994. BDVState State = Pair.second;
  995. // Only values that do not have known bases or those that have differing
  996. // type (scalar versus vector) from a possible known base should be in the
  997. // lattice.
  998. assert((!isKnownBase(I, KnownBases) ||
  999. !areBothVectorOrScalar(I, State.getBaseValue())) &&
  1000. "why did it get added?");
  1001. assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
  1002. // Since we're joining a vector and scalar base, they can never be the
  1003. // same. As a result, we should always see insert element having reached
  1004. // the conflict state.
  1005. assert(!isa<InsertElementInst>(I) || State.isConflict());
  1006. if (!State.isConflict())
  1007. continue;
  1008. auto getMangledName = [](Instruction *I) -> std::string {
  1009. if (isa<PHINode>(I)) {
  1010. return suffixed_name_or(I, ".base", "base_phi");
  1011. } else if (isa<SelectInst>(I)) {
  1012. return suffixed_name_or(I, ".base", "base_select");
  1013. } else if (isa<ExtractElementInst>(I)) {
  1014. return suffixed_name_or(I, ".base", "base_ee");
  1015. } else if (isa<InsertElementInst>(I)) {
  1016. return suffixed_name_or(I, ".base", "base_ie");
  1017. } else {
  1018. return suffixed_name_or(I, ".base", "base_sv");
  1019. }
  1020. };
  1021. Instruction *BaseInst = I->clone();
  1022. BaseInst->insertBefore(I);
  1023. BaseInst->setName(getMangledName(I));
  1024. // Add metadata marking this as a base value
  1025. BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
  1026. States[I] = BDVState(I, BDVState::Conflict, BaseInst);
  1027. setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
  1028. }
  1029. #ifndef NDEBUG
  1030. VerifyStates();
  1031. #endif
  1032. // Returns a instruction which produces the base pointer for a given
  1033. // instruction. The instruction is assumed to be an input to one of the BDVs
  1034. // seen in the inference algorithm above. As such, we must either already
  1035. // know it's base defining value is a base, or have inserted a new
  1036. // instruction to propagate the base of it's BDV and have entered that newly
  1037. // introduced instruction into the state table. In either case, we are
  1038. // assured to be able to determine an instruction which produces it's base
  1039. // pointer.
  1040. auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
  1041. Value *BDV = findBaseOrBDV(Input, Cache, KnownBases);
  1042. Value *Base = nullptr;
  1043. if (!States.count(BDV)) {
  1044. assert(areBothVectorOrScalar(BDV, Input));
  1045. Base = BDV;
  1046. } else {
  1047. // Either conflict or base.
  1048. assert(States.count(BDV));
  1049. Base = States[BDV].getBaseValue();
  1050. }
  1051. assert(Base && "Can't be null");
  1052. // The cast is needed since base traversal may strip away bitcasts
  1053. if (Base->getType() != Input->getType() && InsertPt)
  1054. Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
  1055. return Base;
  1056. };
  1057. // Fixup all the inputs of the new PHIs. Visit order needs to be
  1058. // deterministic and predictable because we're naming newly created
  1059. // instructions.
  1060. for (auto Pair : States) {
  1061. Instruction *BDV = cast<Instruction>(Pair.first);
  1062. BDVState State = Pair.second;
  1063. // Only values that do not have known bases or those that have differing
  1064. // type (scalar versus vector) from a possible known base should be in the
  1065. // lattice.
  1066. assert((!isKnownBase(BDV, KnownBases) ||
  1067. !areBothVectorOrScalar(BDV, State.getBaseValue())) &&
  1068. "why did it get added?");
  1069. assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
  1070. if (!State.isConflict())
  1071. continue;
  1072. if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
  1073. PHINode *PN = cast<PHINode>(BDV);
  1074. const unsigned NumPHIValues = PN->getNumIncomingValues();
  1075. // The IR verifier requires phi nodes with multiple entries from the
  1076. // same basic block to have the same incoming value for each of those
  1077. // entries. Since we're inserting bitcasts in the loop, make sure we
  1078. // do so at least once per incoming block.
  1079. DenseMap<BasicBlock *, Value*> BlockToValue;
  1080. for (unsigned i = 0; i < NumPHIValues; i++) {
  1081. Value *InVal = PN->getIncomingValue(i);
  1082. BasicBlock *InBB = PN->getIncomingBlock(i);
  1083. if (!BlockToValue.count(InBB))
  1084. BlockToValue[InBB] = getBaseForInput(InVal, InBB->getTerminator());
  1085. else {
  1086. #ifndef NDEBUG
  1087. Value *OldBase = BlockToValue[InBB];
  1088. Value *Base = getBaseForInput(InVal, nullptr);
  1089. // We can't use `stripPointerCasts` instead of this function because
  1090. // `stripPointerCasts` doesn't handle vectors of pointers.
  1091. auto StripBitCasts = [](Value *V) -> Value * {
  1092. while (auto *BC = dyn_cast<BitCastInst>(V))
  1093. V = BC->getOperand(0);
  1094. return V;
  1095. };
  1096. // In essence this assert states: the only way two values
  1097. // incoming from the same basic block may be different is by
  1098. // being different bitcasts of the same value. A cleanup
  1099. // that remains TODO is changing findBaseOrBDV to return an
  1100. // llvm::Value of the correct type (and still remain pure).
  1101. // This will remove the need to add bitcasts.
  1102. assert(StripBitCasts(Base) == StripBitCasts(OldBase) &&
  1103. "findBaseOrBDV should be pure!");
  1104. #endif
  1105. }
  1106. Value *Base = BlockToValue[InBB];
  1107. BasePHI->setIncomingValue(i, Base);
  1108. }
  1109. } else if (SelectInst *BaseSI =
  1110. dyn_cast<SelectInst>(State.getBaseValue())) {
  1111. SelectInst *SI = cast<SelectInst>(BDV);
  1112. // Find the instruction which produces the base for each input.
  1113. // We may need to insert a bitcast.
  1114. BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
  1115. BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
  1116. } else if (auto *BaseEE =
  1117. dyn_cast<ExtractElementInst>(State.getBaseValue())) {
  1118. Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
  1119. // Find the instruction which produces the base for each input. We may
  1120. // need to insert a bitcast.
  1121. BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
  1122. } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
  1123. auto *BdvIE = cast<InsertElementInst>(BDV);
  1124. auto UpdateOperand = [&](int OperandIdx) {
  1125. Value *InVal = BdvIE->getOperand(OperandIdx);
  1126. Value *Base = getBaseForInput(InVal, BaseIE);
  1127. BaseIE->setOperand(OperandIdx, Base);
  1128. };
  1129. UpdateOperand(0); // vector operand
  1130. UpdateOperand(1); // scalar operand
  1131. } else {
  1132. auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
  1133. auto *BdvSV = cast<ShuffleVectorInst>(BDV);
  1134. auto UpdateOperand = [&](int OperandIdx) {
  1135. Value *InVal = BdvSV->getOperand(OperandIdx);
  1136. Value *Base = getBaseForInput(InVal, BaseSV);
  1137. BaseSV->setOperand(OperandIdx, Base);
  1138. };
  1139. UpdateOperand(0); // vector operand
  1140. if (!BdvSV->isZeroEltSplat())
  1141. UpdateOperand(1); // vector operand
  1142. else {
  1143. // Never read, so just use undef
  1144. Value *InVal = BdvSV->getOperand(1);
  1145. BaseSV->setOperand(1, UndefValue::get(InVal->getType()));
  1146. }
  1147. }
  1148. }
  1149. #ifndef NDEBUG
  1150. VerifyStates();
  1151. #endif
  1152. // Cache all of our results so we can cheaply reuse them
  1153. // NOTE: This is actually two caches: one of the base defining value
  1154. // relation and one of the base pointer relation! FIXME
  1155. for (auto Pair : States) {
  1156. auto *BDV = Pair.first;
  1157. Value *Base = Pair.second.getBaseValue();
  1158. assert(BDV && Base);
  1159. // Only values that do not have known bases or those that have differing
  1160. // type (scalar versus vector) from a possible known base should be in the
  1161. // lattice.
  1162. assert(
  1163. (!isKnownBase(BDV, KnownBases) || !areBothVectorOrScalar(BDV, Base)) &&
  1164. "why did it get added?");
  1165. LLVM_DEBUG(
  1166. dbgs() << "Updating base value cache"
  1167. << " for: " << BDV->getName() << " from: "
  1168. << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
  1169. << " to: " << Base->getName() << "\n");
  1170. Cache[BDV] = Base;
  1171. }
  1172. assert(Cache.count(Def));
  1173. return Cache[Def];
  1174. }
  1175. // For a set of live pointers (base and/or derived), identify the base
  1176. // pointer of the object which they are derived from. This routine will
  1177. // mutate the IR graph as needed to make the 'base' pointer live at the
  1178. // definition site of 'derived'. This ensures that any use of 'derived' can
  1179. // also use 'base'. This may involve the insertion of a number of
  1180. // additional PHI nodes.
  1181. //
  1182. // preconditions: live is a set of pointer type Values
  1183. //
  1184. // side effects: may insert PHI nodes into the existing CFG, will preserve
  1185. // CFG, will not remove or mutate any existing nodes
  1186. //
  1187. // post condition: PointerToBase contains one (derived, base) pair for every
  1188. // pointer in live. Note that derived can be equal to base if the original
  1189. // pointer was a base pointer.
  1190. static void findBasePointers(const StatepointLiveSetTy &live,
  1191. PointerToBaseTy &PointerToBase, DominatorTree *DT,
  1192. DefiningValueMapTy &DVCache,
  1193. IsKnownBaseMapTy &KnownBases) {
  1194. for (Value *ptr : live) {
  1195. Value *base = findBasePointer(ptr, DVCache, KnownBases);
  1196. assert(base && "failed to find base pointer");
  1197. PointerToBase[ptr] = base;
  1198. assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
  1199. DT->dominates(cast<Instruction>(base)->getParent(),
  1200. cast<Instruction>(ptr)->getParent())) &&
  1201. "The base we found better dominate the derived pointer");
  1202. }
  1203. }
  1204. /// Find the required based pointers (and adjust the live set) for the given
  1205. /// parse point.
  1206. static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
  1207. CallBase *Call,
  1208. PartiallyConstructedSafepointRecord &result,
  1209. PointerToBaseTy &PointerToBase,
  1210. IsKnownBaseMapTy &KnownBases) {
  1211. StatepointLiveSetTy PotentiallyDerivedPointers = result.LiveSet;
  1212. // We assume that all pointers passed to deopt are base pointers; as an
  1213. // optimization, we can use this to avoid seperately materializing the base
  1214. // pointer graph. This is only relevant since we're very conservative about
  1215. // generating new conflict nodes during base pointer insertion. If we were
  1216. // smarter there, this would be irrelevant.
  1217. if (auto Opt = Call->getOperandBundle(LLVMContext::OB_deopt))
  1218. for (Value *V : Opt->Inputs) {
  1219. if (!PotentiallyDerivedPointers.count(V))
  1220. continue;
  1221. PotentiallyDerivedPointers.remove(V);
  1222. PointerToBase[V] = V;
  1223. }
  1224. findBasePointers(PotentiallyDerivedPointers, PointerToBase, &DT, DVCache,
  1225. KnownBases);
  1226. }
  1227. /// Given an updated version of the dataflow liveness results, update the
  1228. /// liveset and base pointer maps for the call site CS.
  1229. static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
  1230. CallBase *Call,
  1231. PartiallyConstructedSafepointRecord &result,
  1232. PointerToBaseTy &PointerToBase);
  1233. static void recomputeLiveInValues(
  1234. Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
  1235. MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
  1236. PointerToBaseTy &PointerToBase) {
  1237. // TODO-PERF: reuse the original liveness, then simply run the dataflow
  1238. // again. The old values are still live and will help it stabilize quickly.
  1239. GCPtrLivenessData RevisedLivenessData;
  1240. computeLiveInValues(DT, F, RevisedLivenessData);
  1241. for (size_t i = 0; i < records.size(); i++) {
  1242. struct PartiallyConstructedSafepointRecord &info = records[i];
  1243. recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info,
  1244. PointerToBase);
  1245. }
  1246. }
  1247. // Utility function which clones all instructions from "ChainToBase"
  1248. // and inserts them before "InsertBefore". Returns rematerialized value
  1249. // which should be used after statepoint.
  1250. static Instruction *rematerializeChain(ArrayRef<Instruction *> ChainToBase,
  1251. Instruction *InsertBefore,
  1252. Value *RootOfChain,
  1253. Value *AlternateLiveBase) {
  1254. Instruction *LastClonedValue = nullptr;
  1255. Instruction *LastValue = nullptr;
  1256. // Walk backwards to visit top-most instructions first.
  1257. for (Instruction *Instr :
  1258. make_range(ChainToBase.rbegin(), ChainToBase.rend())) {
  1259. // Only GEP's and casts are supported as we need to be careful to not
  1260. // introduce any new uses of pointers not in the liveset.
  1261. // Note that it's fine to introduce new uses of pointers which were
  1262. // otherwise not used after this statepoint.
  1263. assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
  1264. Instruction *ClonedValue = Instr->clone();
  1265. ClonedValue->insertBefore(InsertBefore);
  1266. ClonedValue->setName(Instr->getName() + ".remat");
  1267. // If it is not first instruction in the chain then it uses previously
  1268. // cloned value. We should update it to use cloned value.
  1269. if (LastClonedValue) {
  1270. assert(LastValue);
  1271. ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
  1272. #ifndef NDEBUG
  1273. for (auto *OpValue : ClonedValue->operand_values()) {
  1274. // Assert that cloned instruction does not use any instructions from
  1275. // this chain other than LastClonedValue
  1276. assert(!is_contained(ChainToBase, OpValue) &&
  1277. "incorrect use in rematerialization chain");
  1278. // Assert that the cloned instruction does not use the RootOfChain
  1279. // or the AlternateLiveBase.
  1280. assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
  1281. }
  1282. #endif
  1283. } else {
  1284. // For the first instruction, replace the use of unrelocated base i.e.
  1285. // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
  1286. // live set. They have been proved to be the same PHI nodes. Note
  1287. // that the *only* use of the RootOfChain in the ChainToBase list is
  1288. // the first Value in the list.
  1289. if (RootOfChain != AlternateLiveBase)
  1290. ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
  1291. }
  1292. LastClonedValue = ClonedValue;
  1293. LastValue = Instr;
  1294. }
  1295. assert(LastClonedValue);
  1296. return LastClonedValue;
  1297. }
  1298. // When inserting gc.relocate and gc.result calls, we need to ensure there are
  1299. // no uses of the original value / return value between the gc.statepoint and
  1300. // the gc.relocate / gc.result call. One case which can arise is a phi node
  1301. // starting one of the successor blocks. We also need to be able to insert the
  1302. // gc.relocates only on the path which goes through the statepoint. We might
  1303. // need to split an edge to make this possible.
  1304. static BasicBlock *
  1305. normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
  1306. DominatorTree &DT) {
  1307. BasicBlock *Ret = BB;
  1308. if (!BB->getUniquePredecessor())
  1309. Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
  1310. // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
  1311. // from it
  1312. FoldSingleEntryPHINodes(Ret);
  1313. assert(!isa<PHINode>(Ret->begin()) &&
  1314. "All PHI nodes should have been removed!");
  1315. // At this point, we can safely insert a gc.relocate or gc.result as the first
  1316. // instruction in Ret if needed.
  1317. return Ret;
  1318. }
  1319. // List of all function attributes which must be stripped when lowering from
  1320. // abstract machine model to physical machine model. Essentially, these are
  1321. // all the effects a safepoint might have which we ignored in the abstract
  1322. // machine model for purposes of optimization. We have to strip these on
  1323. // both function declarations and call sites.
  1324. static constexpr Attribute::AttrKind FnAttrsToStrip[] =
  1325. {Attribute::Memory, Attribute::NoSync, Attribute::NoFree};
  1326. // Create new attribute set containing only attributes which can be transferred
  1327. // from original call to the safepoint.
  1328. static AttributeList legalizeCallAttributes(LLVMContext &Ctx,
  1329. AttributeList OrigAL,
  1330. AttributeList StatepointAL) {
  1331. if (OrigAL.isEmpty())
  1332. return StatepointAL;
  1333. // Remove the readonly, readnone, and statepoint function attributes.
  1334. AttrBuilder FnAttrs(Ctx, OrigAL.getFnAttrs());
  1335. for (auto Attr : FnAttrsToStrip)
  1336. FnAttrs.removeAttribute(Attr);
  1337. for (Attribute A : OrigAL.getFnAttrs()) {
  1338. if (isStatepointDirectiveAttr(A))
  1339. FnAttrs.removeAttribute(A);
  1340. }
  1341. // Just skip parameter and return attributes for now
  1342. return StatepointAL.addFnAttributes(Ctx, FnAttrs);
  1343. }
  1344. /// Helper function to place all gc relocates necessary for the given
  1345. /// statepoint.
  1346. /// Inputs:
  1347. /// liveVariables - list of variables to be relocated.
  1348. /// basePtrs - base pointers.
  1349. /// statepointToken - statepoint instruction to which relocates should be
  1350. /// bound.
  1351. /// Builder - Llvm IR builder to be used to construct new calls.
  1352. static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
  1353. ArrayRef<Value *> BasePtrs,
  1354. Instruction *StatepointToken,
  1355. IRBuilder<> &Builder) {
  1356. if (LiveVariables.empty())
  1357. return;
  1358. auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
  1359. auto ValIt = llvm::find(LiveVec, Val);
  1360. assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
  1361. size_t Index = std::distance(LiveVec.begin(), ValIt);
  1362. assert(Index < LiveVec.size() && "Bug in std::find?");
  1363. return Index;
  1364. };
  1365. Module *M = StatepointToken->getModule();
  1366. // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
  1367. // element type is i8 addrspace(1)*). We originally generated unique
  1368. // declarations for each pointer type, but this proved problematic because
  1369. // the intrinsic mangling code is incomplete and fragile. Since we're moving
  1370. // towards a single unified pointer type anyways, we can just cast everything
  1371. // to an i8* of the right address space. A bitcast is added later to convert
  1372. // gc_relocate to the actual value's type.
  1373. auto getGCRelocateDecl = [&] (Type *Ty) {
  1374. assert(isHandledGCPointerType(Ty));
  1375. auto AS = Ty->getScalarType()->getPointerAddressSpace();
  1376. Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
  1377. if (auto *VT = dyn_cast<VectorType>(Ty))
  1378. NewTy = FixedVectorType::get(NewTy,
  1379. cast<FixedVectorType>(VT)->getNumElements());
  1380. return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
  1381. {NewTy});
  1382. };
  1383. // Lazily populated map from input types to the canonicalized form mentioned
  1384. // in the comment above. This should probably be cached somewhere more
  1385. // broadly.
  1386. DenseMap<Type *, Function *> TypeToDeclMap;
  1387. for (unsigned i = 0; i < LiveVariables.size(); i++) {
  1388. // Generate the gc.relocate call and save the result
  1389. Value *BaseIdx = Builder.getInt32(FindIndex(LiveVariables, BasePtrs[i]));
  1390. Value *LiveIdx = Builder.getInt32(i);
  1391. Type *Ty = LiveVariables[i]->getType();
  1392. if (!TypeToDeclMap.count(Ty))
  1393. TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
  1394. Function *GCRelocateDecl = TypeToDeclMap[Ty];
  1395. // only specify a debug name if we can give a useful one
  1396. CallInst *Reloc = Builder.CreateCall(
  1397. GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
  1398. suffixed_name_or(LiveVariables[i], ".relocated", ""));
  1399. // Trick CodeGen into thinking there are lots of free registers at this
  1400. // fake call.
  1401. Reloc->setCallingConv(CallingConv::Cold);
  1402. }
  1403. }
  1404. namespace {
  1405. /// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
  1406. /// avoids having to worry about keeping around dangling pointers to Values.
  1407. class DeferredReplacement {
  1408. AssertingVH<Instruction> Old;
  1409. AssertingVH<Instruction> New;
  1410. bool IsDeoptimize = false;
  1411. DeferredReplacement() = default;
  1412. public:
  1413. static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
  1414. assert(Old != New && Old && New &&
  1415. "Cannot RAUW equal values or to / from null!");
  1416. DeferredReplacement D;
  1417. D.Old = Old;
  1418. D.New = New;
  1419. return D;
  1420. }
  1421. static DeferredReplacement createDelete(Instruction *ToErase) {
  1422. DeferredReplacement D;
  1423. D.Old = ToErase;
  1424. return D;
  1425. }
  1426. static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
  1427. #ifndef NDEBUG
  1428. auto *F = cast<CallInst>(Old)->getCalledFunction();
  1429. assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
  1430. "Only way to construct a deoptimize deferred replacement");
  1431. #endif
  1432. DeferredReplacement D;
  1433. D.Old = Old;
  1434. D.IsDeoptimize = true;
  1435. return D;
  1436. }
  1437. /// Does the task represented by this instance.
  1438. void doReplacement() {
  1439. Instruction *OldI = Old;
  1440. Instruction *NewI = New;
  1441. assert(OldI != NewI && "Disallowed at construction?!");
  1442. assert((!IsDeoptimize || !New) &&
  1443. "Deoptimize intrinsics are not replaced!");
  1444. Old = nullptr;
  1445. New = nullptr;
  1446. if (NewI)
  1447. OldI->replaceAllUsesWith(NewI);
  1448. if (IsDeoptimize) {
  1449. // Note: we've inserted instructions, so the call to llvm.deoptimize may
  1450. // not necessarily be followed by the matching return.
  1451. auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
  1452. new UnreachableInst(RI->getContext(), RI);
  1453. RI->eraseFromParent();
  1454. }
  1455. OldI->eraseFromParent();
  1456. }
  1457. };
  1458. } // end anonymous namespace
  1459. static StringRef getDeoptLowering(CallBase *Call) {
  1460. const char *DeoptLowering = "deopt-lowering";
  1461. if (Call->hasFnAttr(DeoptLowering)) {
  1462. // FIXME: Calls have a *really* confusing interface around attributes
  1463. // with values.
  1464. const AttributeList &CSAS = Call->getAttributes();
  1465. if (CSAS.hasFnAttr(DeoptLowering))
  1466. return CSAS.getFnAttr(DeoptLowering).getValueAsString();
  1467. Function *F = Call->getCalledFunction();
  1468. assert(F && F->hasFnAttribute(DeoptLowering));
  1469. return F->getFnAttribute(DeoptLowering).getValueAsString();
  1470. }
  1471. return "live-through";
  1472. }
  1473. static void
  1474. makeStatepointExplicitImpl(CallBase *Call, /* to replace */
  1475. const SmallVectorImpl<Value *> &BasePtrs,
  1476. const SmallVectorImpl<Value *> &LiveVariables,
  1477. PartiallyConstructedSafepointRecord &Result,
  1478. std::vector<DeferredReplacement> &Replacements,
  1479. const PointerToBaseTy &PointerToBase) {
  1480. assert(BasePtrs.size() == LiveVariables.size());
  1481. // Then go ahead and use the builder do actually do the inserts. We insert
  1482. // immediately before the previous instruction under the assumption that all
  1483. // arguments will be available here. We can't insert afterwards since we may
  1484. // be replacing a terminator.
  1485. IRBuilder<> Builder(Call);
  1486. ArrayRef<Value *> GCArgs(LiveVariables);
  1487. uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
  1488. uint32_t NumPatchBytes = 0;
  1489. uint32_t Flags = uint32_t(StatepointFlags::None);
  1490. SmallVector<Value *, 8> CallArgs(Call->args());
  1491. std::optional<ArrayRef<Use>> DeoptArgs;
  1492. if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_deopt))
  1493. DeoptArgs = Bundle->Inputs;
  1494. std::optional<ArrayRef<Use>> TransitionArgs;
  1495. if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
  1496. TransitionArgs = Bundle->Inputs;
  1497. // TODO: This flag no longer serves a purpose and can be removed later
  1498. Flags |= uint32_t(StatepointFlags::GCTransition);
  1499. }
  1500. // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
  1501. // with a return value, we lower then as never returning calls to
  1502. // __llvm_deoptimize that are followed by unreachable to get better codegen.
  1503. bool IsDeoptimize = false;
  1504. StatepointDirectives SD =
  1505. parseStatepointDirectivesFromAttrs(Call->getAttributes());
  1506. if (SD.NumPatchBytes)
  1507. NumPatchBytes = *SD.NumPatchBytes;
  1508. if (SD.StatepointID)
  1509. StatepointID = *SD.StatepointID;
  1510. // Pass through the requested lowering if any. The default is live-through.
  1511. StringRef DeoptLowering = getDeoptLowering(Call);
  1512. if (DeoptLowering.equals("live-in"))
  1513. Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
  1514. else {
  1515. assert(DeoptLowering.equals("live-through") && "Unsupported value!");
  1516. }
  1517. FunctionCallee CallTarget(Call->getFunctionType(), Call->getCalledOperand());
  1518. if (Function *F = dyn_cast<Function>(CallTarget.getCallee())) {
  1519. auto IID = F->getIntrinsicID();
  1520. if (IID == Intrinsic::experimental_deoptimize) {
  1521. // Calls to llvm.experimental.deoptimize are lowered to calls to the
  1522. // __llvm_deoptimize symbol. We want to resolve this now, since the
  1523. // verifier does not allow taking the address of an intrinsic function.
  1524. SmallVector<Type *, 8> DomainTy;
  1525. for (Value *Arg : CallArgs)
  1526. DomainTy.push_back(Arg->getType());
  1527. auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
  1528. /* isVarArg = */ false);
  1529. // Note: CallTarget can be a bitcast instruction of a symbol if there are
  1530. // calls to @llvm.experimental.deoptimize with different argument types in
  1531. // the same module. This is fine -- we assume the frontend knew what it
  1532. // was doing when generating this kind of IR.
  1533. CallTarget = F->getParent()
  1534. ->getOrInsertFunction("__llvm_deoptimize", FTy);
  1535. IsDeoptimize = true;
  1536. } else if (IID == Intrinsic::memcpy_element_unordered_atomic ||
  1537. IID == Intrinsic::memmove_element_unordered_atomic) {
  1538. // Unordered atomic memcpy and memmove intrinsics which are not explicitly
  1539. // marked as "gc-leaf-function" should be lowered in a GC parseable way.
  1540. // Specifically, these calls should be lowered to the
  1541. // __llvm_{memcpy|memmove}_element_unordered_atomic_safepoint symbols.
  1542. // Similarly to __llvm_deoptimize we want to resolve this now, since the
  1543. // verifier does not allow taking the address of an intrinsic function.
  1544. //
  1545. // Moreover we need to shuffle the arguments for the call in order to
  1546. // accommodate GC. The underlying source and destination objects might be
  1547. // relocated during copy operation should the GC occur. To relocate the
  1548. // derived source and destination pointers the implementation of the
  1549. // intrinsic should know the corresponding base pointers.
  1550. //
  1551. // To make the base pointers available pass them explicitly as arguments:
  1552. // memcpy(dest_derived, source_derived, ...) =>
  1553. // memcpy(dest_base, dest_offset, source_base, source_offset, ...)
  1554. auto &Context = Call->getContext();
  1555. auto &DL = Call->getModule()->getDataLayout();
  1556. auto GetBaseAndOffset = [&](Value *Derived) {
  1557. Value *Base = nullptr;
  1558. // Optimizations in unreachable code might substitute the real pointer
  1559. // with undef, poison or null-derived constant. Return null base for
  1560. // them to be consistent with the handling in the main algorithm in
  1561. // findBaseDefiningValue.
  1562. if (isa<Constant>(Derived))
  1563. Base =
  1564. ConstantPointerNull::get(cast<PointerType>(Derived->getType()));
  1565. else {
  1566. assert(PointerToBase.count(Derived));
  1567. Base = PointerToBase.find(Derived)->second;
  1568. }
  1569. unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
  1570. unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
  1571. Value *Base_int = Builder.CreatePtrToInt(
  1572. Base, Type::getIntNTy(Context, IntPtrSize));
  1573. Value *Derived_int = Builder.CreatePtrToInt(
  1574. Derived, Type::getIntNTy(Context, IntPtrSize));
  1575. return std::make_pair(Base, Builder.CreateSub(Derived_int, Base_int));
  1576. };
  1577. auto *Dest = CallArgs[0];
  1578. Value *DestBase, *DestOffset;
  1579. std::tie(DestBase, DestOffset) = GetBaseAndOffset(Dest);
  1580. auto *Source = CallArgs[1];
  1581. Value *SourceBase, *SourceOffset;
  1582. std::tie(SourceBase, SourceOffset) = GetBaseAndOffset(Source);
  1583. auto *LengthInBytes = CallArgs[2];
  1584. auto *ElementSizeCI = cast<ConstantInt>(CallArgs[3]);
  1585. CallArgs.clear();
  1586. CallArgs.push_back(DestBase);
  1587. CallArgs.push_back(DestOffset);
  1588. CallArgs.push_back(SourceBase);
  1589. CallArgs.push_back(SourceOffset);
  1590. CallArgs.push_back(LengthInBytes);
  1591. SmallVector<Type *, 8> DomainTy;
  1592. for (Value *Arg : CallArgs)
  1593. DomainTy.push_back(Arg->getType());
  1594. auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
  1595. /* isVarArg = */ false);
  1596. auto GetFunctionName = [](Intrinsic::ID IID, ConstantInt *ElementSizeCI) {
  1597. uint64_t ElementSize = ElementSizeCI->getZExtValue();
  1598. if (IID == Intrinsic::memcpy_element_unordered_atomic) {
  1599. switch (ElementSize) {
  1600. case 1:
  1601. return "__llvm_memcpy_element_unordered_atomic_safepoint_1";
  1602. case 2:
  1603. return "__llvm_memcpy_element_unordered_atomic_safepoint_2";
  1604. case 4:
  1605. return "__llvm_memcpy_element_unordered_atomic_safepoint_4";
  1606. case 8:
  1607. return "__llvm_memcpy_element_unordered_atomic_safepoint_8";
  1608. case 16:
  1609. return "__llvm_memcpy_element_unordered_atomic_safepoint_16";
  1610. default:
  1611. llvm_unreachable("unexpected element size!");
  1612. }
  1613. }
  1614. assert(IID == Intrinsic::memmove_element_unordered_atomic);
  1615. switch (ElementSize) {
  1616. case 1:
  1617. return "__llvm_memmove_element_unordered_atomic_safepoint_1";
  1618. case 2:
  1619. return "__llvm_memmove_element_unordered_atomic_safepoint_2";
  1620. case 4:
  1621. return "__llvm_memmove_element_unordered_atomic_safepoint_4";
  1622. case 8:
  1623. return "__llvm_memmove_element_unordered_atomic_safepoint_8";
  1624. case 16:
  1625. return "__llvm_memmove_element_unordered_atomic_safepoint_16";
  1626. default:
  1627. llvm_unreachable("unexpected element size!");
  1628. }
  1629. };
  1630. CallTarget =
  1631. F->getParent()
  1632. ->getOrInsertFunction(GetFunctionName(IID, ElementSizeCI), FTy);
  1633. }
  1634. }
  1635. // Create the statepoint given all the arguments
  1636. GCStatepointInst *Token = nullptr;
  1637. if (auto *CI = dyn_cast<CallInst>(Call)) {
  1638. CallInst *SPCall = Builder.CreateGCStatepointCall(
  1639. StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
  1640. TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
  1641. SPCall->setTailCallKind(CI->getTailCallKind());
  1642. SPCall->setCallingConv(CI->getCallingConv());
  1643. // Currently we will fail on parameter attributes and on certain
  1644. // function attributes. In case if we can handle this set of attributes -
  1645. // set up function attrs directly on statepoint and return attrs later for
  1646. // gc_result intrinsic.
  1647. SPCall->setAttributes(legalizeCallAttributes(
  1648. CI->getContext(), CI->getAttributes(), SPCall->getAttributes()));
  1649. Token = cast<GCStatepointInst>(SPCall);
  1650. // Put the following gc_result and gc_relocate calls immediately after the
  1651. // the old call (which we're about to delete)
  1652. assert(CI->getNextNode() && "Not a terminator, must have next!");
  1653. Builder.SetInsertPoint(CI->getNextNode());
  1654. Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
  1655. } else {
  1656. auto *II = cast<InvokeInst>(Call);
  1657. // Insert the new invoke into the old block. We'll remove the old one in a
  1658. // moment at which point this will become the new terminator for the
  1659. // original block.
  1660. InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
  1661. StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
  1662. II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs, GCArgs,
  1663. "statepoint_token");
  1664. SPInvoke->setCallingConv(II->getCallingConv());
  1665. // Currently we will fail on parameter attributes and on certain
  1666. // function attributes. In case if we can handle this set of attributes -
  1667. // set up function attrs directly on statepoint and return attrs later for
  1668. // gc_result intrinsic.
  1669. SPInvoke->setAttributes(legalizeCallAttributes(
  1670. II->getContext(), II->getAttributes(), SPInvoke->getAttributes()));
  1671. Token = cast<GCStatepointInst>(SPInvoke);
  1672. // Generate gc relocates in exceptional path
  1673. BasicBlock *UnwindBlock = II->getUnwindDest();
  1674. assert(!isa<PHINode>(UnwindBlock->begin()) &&
  1675. UnwindBlock->getUniquePredecessor() &&
  1676. "can't safely insert in this block!");
  1677. Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
  1678. Builder.SetCurrentDebugLocation(II->getDebugLoc());
  1679. // Attach exceptional gc relocates to the landingpad.
  1680. Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
  1681. Result.UnwindToken = ExceptionalToken;
  1682. CreateGCRelocates(LiveVariables, BasePtrs, ExceptionalToken, Builder);
  1683. // Generate gc relocates and returns for normal block
  1684. BasicBlock *NormalDest = II->getNormalDest();
  1685. assert(!isa<PHINode>(NormalDest->begin()) &&
  1686. NormalDest->getUniquePredecessor() &&
  1687. "can't safely insert in this block!");
  1688. Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
  1689. // gc relocates will be generated later as if it were regular call
  1690. // statepoint
  1691. }
  1692. assert(Token && "Should be set in one of the above branches!");
  1693. if (IsDeoptimize) {
  1694. // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
  1695. // transform the tail-call like structure to a call to a void function
  1696. // followed by unreachable to get better codegen.
  1697. Replacements.push_back(
  1698. DeferredReplacement::createDeoptimizeReplacement(Call));
  1699. } else {
  1700. Token->setName("statepoint_token");
  1701. if (!Call->getType()->isVoidTy() && !Call->use_empty()) {
  1702. StringRef Name = Call->hasName() ? Call->getName() : "";
  1703. CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
  1704. GCResult->setAttributes(
  1705. AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
  1706. Call->getAttributes().getRetAttrs()));
  1707. // We cannot RAUW or delete CS.getInstruction() because it could be in the
  1708. // live set of some other safepoint, in which case that safepoint's
  1709. // PartiallyConstructedSafepointRecord will hold a raw pointer to this
  1710. // llvm::Instruction. Instead, we defer the replacement and deletion to
  1711. // after the live sets have been made explicit in the IR, and we no longer
  1712. // have raw pointers to worry about.
  1713. Replacements.emplace_back(
  1714. DeferredReplacement::createRAUW(Call, GCResult));
  1715. } else {
  1716. Replacements.emplace_back(DeferredReplacement::createDelete(Call));
  1717. }
  1718. }
  1719. Result.StatepointToken = Token;
  1720. // Second, create a gc.relocate for every live variable
  1721. CreateGCRelocates(LiveVariables, BasePtrs, Token, Builder);
  1722. }
  1723. // Replace an existing gc.statepoint with a new one and a set of gc.relocates
  1724. // which make the relocations happening at this safepoint explicit.
  1725. //
  1726. // WARNING: Does not do any fixup to adjust users of the original live
  1727. // values. That's the callers responsibility.
  1728. static void
  1729. makeStatepointExplicit(DominatorTree &DT, CallBase *Call,
  1730. PartiallyConstructedSafepointRecord &Result,
  1731. std::vector<DeferredReplacement> &Replacements,
  1732. const PointerToBaseTy &PointerToBase) {
  1733. const auto &LiveSet = Result.LiveSet;
  1734. // Convert to vector for efficient cross referencing.
  1735. SmallVector<Value *, 64> BaseVec, LiveVec;
  1736. LiveVec.reserve(LiveSet.size());
  1737. BaseVec.reserve(LiveSet.size());
  1738. for (Value *L : LiveSet) {
  1739. LiveVec.push_back(L);
  1740. assert(PointerToBase.count(L));
  1741. Value *Base = PointerToBase.find(L)->second;
  1742. BaseVec.push_back(Base);
  1743. }
  1744. assert(LiveVec.size() == BaseVec.size());
  1745. // Do the actual rewriting and delete the old statepoint
  1746. makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements,
  1747. PointerToBase);
  1748. }
  1749. // Helper function for the relocationViaAlloca.
  1750. //
  1751. // It receives iterator to the statepoint gc relocates and emits a store to the
  1752. // assigned location (via allocaMap) for the each one of them. It adds the
  1753. // visited values into the visitedLiveValues set, which we will later use them
  1754. // for validation checking.
  1755. static void
  1756. insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
  1757. DenseMap<Value *, AllocaInst *> &AllocaMap,
  1758. DenseSet<Value *> &VisitedLiveValues) {
  1759. for (User *U : GCRelocs) {
  1760. GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
  1761. if (!Relocate)
  1762. continue;
  1763. Value *OriginalValue = Relocate->getDerivedPtr();
  1764. assert(AllocaMap.count(OriginalValue));
  1765. Value *Alloca = AllocaMap[OriginalValue];
  1766. // Emit store into the related alloca
  1767. // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
  1768. // the correct type according to alloca.
  1769. assert(Relocate->getNextNode() &&
  1770. "Should always have one since it's not a terminator");
  1771. IRBuilder<> Builder(Relocate->getNextNode());
  1772. Value *CastedRelocatedValue =
  1773. Builder.CreateBitCast(Relocate,
  1774. cast<AllocaInst>(Alloca)->getAllocatedType(),
  1775. suffixed_name_or(Relocate, ".casted", ""));
  1776. new StoreInst(CastedRelocatedValue, Alloca,
  1777. cast<Instruction>(CastedRelocatedValue)->getNextNode());
  1778. #ifndef NDEBUG
  1779. VisitedLiveValues.insert(OriginalValue);
  1780. #endif
  1781. }
  1782. }
  1783. // Helper function for the "relocationViaAlloca". Similar to the
  1784. // "insertRelocationStores" but works for rematerialized values.
  1785. static void insertRematerializationStores(
  1786. const RematerializedValueMapTy &RematerializedValues,
  1787. DenseMap<Value *, AllocaInst *> &AllocaMap,
  1788. DenseSet<Value *> &VisitedLiveValues) {
  1789. for (auto RematerializedValuePair: RematerializedValues) {
  1790. Instruction *RematerializedValue = RematerializedValuePair.first;
  1791. Value *OriginalValue = RematerializedValuePair.second;
  1792. assert(AllocaMap.count(OriginalValue) &&
  1793. "Can not find alloca for rematerialized value");
  1794. Value *Alloca = AllocaMap[OriginalValue];
  1795. new StoreInst(RematerializedValue, Alloca,
  1796. RematerializedValue->getNextNode());
  1797. #ifndef NDEBUG
  1798. VisitedLiveValues.insert(OriginalValue);
  1799. #endif
  1800. }
  1801. }
  1802. /// Do all the relocation update via allocas and mem2reg
  1803. static void relocationViaAlloca(
  1804. Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
  1805. ArrayRef<PartiallyConstructedSafepointRecord> Records) {
  1806. #ifndef NDEBUG
  1807. // record initial number of (static) allocas; we'll check we have the same
  1808. // number when we get done.
  1809. int InitialAllocaNum = 0;
  1810. for (Instruction &I : F.getEntryBlock())
  1811. if (isa<AllocaInst>(I))
  1812. InitialAllocaNum++;
  1813. #endif
  1814. // TODO-PERF: change data structures, reserve
  1815. DenseMap<Value *, AllocaInst *> AllocaMap;
  1816. SmallVector<AllocaInst *, 200> PromotableAllocas;
  1817. // Used later to chack that we have enough allocas to store all values
  1818. std::size_t NumRematerializedValues = 0;
  1819. PromotableAllocas.reserve(Live.size());
  1820. // Emit alloca for "LiveValue" and record it in "allocaMap" and
  1821. // "PromotableAllocas"
  1822. const DataLayout &DL = F.getParent()->getDataLayout();
  1823. auto emitAllocaFor = [&](Value *LiveValue) {
  1824. AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
  1825. DL.getAllocaAddrSpace(), "",
  1826. F.getEntryBlock().getFirstNonPHI());
  1827. AllocaMap[LiveValue] = Alloca;
  1828. PromotableAllocas.push_back(Alloca);
  1829. };
  1830. // Emit alloca for each live gc pointer
  1831. for (Value *V : Live)
  1832. emitAllocaFor(V);
  1833. // Emit allocas for rematerialized values
  1834. for (const auto &Info : Records)
  1835. for (auto RematerializedValuePair : Info.RematerializedValues) {
  1836. Value *OriginalValue = RematerializedValuePair.second;
  1837. if (AllocaMap.count(OriginalValue) != 0)
  1838. continue;
  1839. emitAllocaFor(OriginalValue);
  1840. ++NumRematerializedValues;
  1841. }
  1842. // The next two loops are part of the same conceptual operation. We need to
  1843. // insert a store to the alloca after the original def and at each
  1844. // redefinition. We need to insert a load before each use. These are split
  1845. // into distinct loops for performance reasons.
  1846. // Update gc pointer after each statepoint: either store a relocated value or
  1847. // null (if no relocated value was found for this gc pointer and it is not a
  1848. // gc_result). This must happen before we update the statepoint with load of
  1849. // alloca otherwise we lose the link between statepoint and old def.
  1850. for (const auto &Info : Records) {
  1851. Value *Statepoint = Info.StatepointToken;
  1852. // This will be used for consistency check
  1853. DenseSet<Value *> VisitedLiveValues;
  1854. // Insert stores for normal statepoint gc relocates
  1855. insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
  1856. // In case if it was invoke statepoint
  1857. // we will insert stores for exceptional path gc relocates.
  1858. if (isa<InvokeInst>(Statepoint)) {
  1859. insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
  1860. VisitedLiveValues);
  1861. }
  1862. // Do similar thing with rematerialized values
  1863. insertRematerializationStores(Info.RematerializedValues, AllocaMap,
  1864. VisitedLiveValues);
  1865. if (ClobberNonLive) {
  1866. // As a debugging aid, pretend that an unrelocated pointer becomes null at
  1867. // the gc.statepoint. This will turn some subtle GC problems into
  1868. // slightly easier to debug SEGVs. Note that on large IR files with
  1869. // lots of gc.statepoints this is extremely costly both memory and time
  1870. // wise.
  1871. SmallVector<AllocaInst *, 64> ToClobber;
  1872. for (auto Pair : AllocaMap) {
  1873. Value *Def = Pair.first;
  1874. AllocaInst *Alloca = Pair.second;
  1875. // This value was relocated
  1876. if (VisitedLiveValues.count(Def)) {
  1877. continue;
  1878. }
  1879. ToClobber.push_back(Alloca);
  1880. }
  1881. auto InsertClobbersAt = [&](Instruction *IP) {
  1882. for (auto *AI : ToClobber) {
  1883. auto AT = AI->getAllocatedType();
  1884. Constant *CPN;
  1885. if (AT->isVectorTy())
  1886. CPN = ConstantAggregateZero::get(AT);
  1887. else
  1888. CPN = ConstantPointerNull::get(cast<PointerType>(AT));
  1889. new StoreInst(CPN, AI, IP);
  1890. }
  1891. };
  1892. // Insert the clobbering stores. These may get intermixed with the
  1893. // gc.results and gc.relocates, but that's fine.
  1894. if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
  1895. InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
  1896. InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
  1897. } else {
  1898. InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
  1899. }
  1900. }
  1901. }
  1902. // Update use with load allocas and add store for gc_relocated.
  1903. for (auto Pair : AllocaMap) {
  1904. Value *Def = Pair.first;
  1905. AllocaInst *Alloca = Pair.second;
  1906. // We pre-record the uses of allocas so that we dont have to worry about
  1907. // later update that changes the user information..
  1908. SmallVector<Instruction *, 20> Uses;
  1909. // PERF: trade a linear scan for repeated reallocation
  1910. Uses.reserve(Def->getNumUses());
  1911. for (User *U : Def->users()) {
  1912. if (!isa<ConstantExpr>(U)) {
  1913. // If the def has a ConstantExpr use, then the def is either a
  1914. // ConstantExpr use itself or null. In either case
  1915. // (recursively in the first, directly in the second), the oop
  1916. // it is ultimately dependent on is null and this particular
  1917. // use does not need to be fixed up.
  1918. Uses.push_back(cast<Instruction>(U));
  1919. }
  1920. }
  1921. llvm::sort(Uses);
  1922. auto Last = std::unique(Uses.begin(), Uses.end());
  1923. Uses.erase(Last, Uses.end());
  1924. for (Instruction *Use : Uses) {
  1925. if (isa<PHINode>(Use)) {
  1926. PHINode *Phi = cast<PHINode>(Use);
  1927. for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
  1928. if (Def == Phi->getIncomingValue(i)) {
  1929. LoadInst *Load =
  1930. new LoadInst(Alloca->getAllocatedType(), Alloca, "",
  1931. Phi->getIncomingBlock(i)->getTerminator());
  1932. Phi->setIncomingValue(i, Load);
  1933. }
  1934. }
  1935. } else {
  1936. LoadInst *Load =
  1937. new LoadInst(Alloca->getAllocatedType(), Alloca, "", Use);
  1938. Use->replaceUsesOfWith(Def, Load);
  1939. }
  1940. }
  1941. // Emit store for the initial gc value. Store must be inserted after load,
  1942. // otherwise store will be in alloca's use list and an extra load will be
  1943. // inserted before it.
  1944. StoreInst *Store = new StoreInst(Def, Alloca, /*volatile*/ false,
  1945. DL.getABITypeAlign(Def->getType()));
  1946. if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
  1947. if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
  1948. // InvokeInst is a terminator so the store need to be inserted into its
  1949. // normal destination block.
  1950. BasicBlock *NormalDest = Invoke->getNormalDest();
  1951. Store->insertBefore(NormalDest->getFirstNonPHI());
  1952. } else {
  1953. assert(!Inst->isTerminator() &&
  1954. "The only terminator that can produce a value is "
  1955. "InvokeInst which is handled above.");
  1956. Store->insertAfter(Inst);
  1957. }
  1958. } else {
  1959. assert(isa<Argument>(Def));
  1960. Store->insertAfter(cast<Instruction>(Alloca));
  1961. }
  1962. }
  1963. assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
  1964. "we must have the same allocas with lives");
  1965. (void) NumRematerializedValues;
  1966. if (!PromotableAllocas.empty()) {
  1967. // Apply mem2reg to promote alloca to SSA
  1968. PromoteMemToReg(PromotableAllocas, DT);
  1969. }
  1970. #ifndef NDEBUG
  1971. for (auto &I : F.getEntryBlock())
  1972. if (isa<AllocaInst>(I))
  1973. InitialAllocaNum--;
  1974. assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
  1975. #endif
  1976. }
  1977. /// Implement a unique function which doesn't require we sort the input
  1978. /// vector. Doing so has the effect of changing the output of a couple of
  1979. /// tests in ways which make them less useful in testing fused safepoints.
  1980. template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
  1981. SmallSet<T, 8> Seen;
  1982. erase_if(Vec, [&](const T &V) { return !Seen.insert(V).second; });
  1983. }
  1984. /// Insert holders so that each Value is obviously live through the entire
  1985. /// lifetime of the call.
  1986. static void insertUseHolderAfter(CallBase *Call, const ArrayRef<Value *> Values,
  1987. SmallVectorImpl<CallInst *> &Holders) {
  1988. if (Values.empty())
  1989. // No values to hold live, might as well not insert the empty holder
  1990. return;
  1991. Module *M = Call->getModule();
  1992. // Use a dummy vararg function to actually hold the values live
  1993. FunctionCallee Func = M->getOrInsertFunction(
  1994. "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
  1995. if (isa<CallInst>(Call)) {
  1996. // For call safepoints insert dummy calls right after safepoint
  1997. Holders.push_back(
  1998. CallInst::Create(Func, Values, "", &*++Call->getIterator()));
  1999. return;
  2000. }
  2001. // For invoke safepooints insert dummy calls both in normal and
  2002. // exceptional destination blocks
  2003. auto *II = cast<InvokeInst>(Call);
  2004. Holders.push_back(CallInst::Create(
  2005. Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
  2006. Holders.push_back(CallInst::Create(
  2007. Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
  2008. }
  2009. static void findLiveReferences(
  2010. Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
  2011. MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
  2012. GCPtrLivenessData OriginalLivenessData;
  2013. computeLiveInValues(DT, F, OriginalLivenessData);
  2014. for (size_t i = 0; i < records.size(); i++) {
  2015. struct PartiallyConstructedSafepointRecord &info = records[i];
  2016. analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
  2017. }
  2018. }
  2019. // Helper function for the "rematerializeLiveValues". It walks use chain
  2020. // starting from the "CurrentValue" until it reaches the root of the chain, i.e.
  2021. // the base or a value it cannot process. Only "simple" values are processed
  2022. // (currently it is GEP's and casts). The returned root is examined by the
  2023. // callers of findRematerializableChainToBasePointer. Fills "ChainToBase" array
  2024. // with all visited values.
  2025. static Value* findRematerializableChainToBasePointer(
  2026. SmallVectorImpl<Instruction*> &ChainToBase,
  2027. Value *CurrentValue) {
  2028. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
  2029. ChainToBase.push_back(GEP);
  2030. return findRematerializableChainToBasePointer(ChainToBase,
  2031. GEP->getPointerOperand());
  2032. }
  2033. if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
  2034. if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
  2035. return CI;
  2036. ChainToBase.push_back(CI);
  2037. return findRematerializableChainToBasePointer(ChainToBase,
  2038. CI->getOperand(0));
  2039. }
  2040. // We have reached the root of the chain, which is either equal to the base or
  2041. // is the first unsupported value along the use chain.
  2042. return CurrentValue;
  2043. }
  2044. // Helper function for the "rematerializeLiveValues". Compute cost of the use
  2045. // chain we are going to rematerialize.
  2046. static InstructionCost
  2047. chainToBasePointerCost(SmallVectorImpl<Instruction *> &Chain,
  2048. TargetTransformInfo &TTI) {
  2049. InstructionCost Cost = 0;
  2050. for (Instruction *Instr : Chain) {
  2051. if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
  2052. assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
  2053. "non noop cast is found during rematerialization");
  2054. Type *SrcTy = CI->getOperand(0)->getType();
  2055. Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy,
  2056. TTI::getCastContextHint(CI),
  2057. TargetTransformInfo::TCK_SizeAndLatency, CI);
  2058. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
  2059. // Cost of the address calculation
  2060. Type *ValTy = GEP->getSourceElementType();
  2061. Cost += TTI.getAddressComputationCost(ValTy);
  2062. // And cost of the GEP itself
  2063. // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
  2064. // allowed for the external usage)
  2065. if (!GEP->hasAllConstantIndices())
  2066. Cost += 2;
  2067. } else {
  2068. llvm_unreachable("unsupported instruction type during rematerialization");
  2069. }
  2070. }
  2071. return Cost;
  2072. }
  2073. static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
  2074. unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
  2075. if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
  2076. OrigRootPhi.getParent() != AlternateRootPhi.getParent())
  2077. return false;
  2078. // Map of incoming values and their corresponding basic blocks of
  2079. // OrigRootPhi.
  2080. SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
  2081. for (unsigned i = 0; i < PhiNum; i++)
  2082. CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
  2083. OrigRootPhi.getIncomingBlock(i);
  2084. // Both current and base PHIs should have same incoming values and
  2085. // the same basic blocks corresponding to the incoming values.
  2086. for (unsigned i = 0; i < PhiNum; i++) {
  2087. auto CIVI =
  2088. CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
  2089. if (CIVI == CurrentIncomingValues.end())
  2090. return false;
  2091. BasicBlock *CurrentIncomingBB = CIVI->second;
  2092. if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
  2093. return false;
  2094. }
  2095. return true;
  2096. }
  2097. // Find derived pointers that can be recomputed cheap enough and fill
  2098. // RematerizationCandidates with such candidates.
  2099. static void
  2100. findRematerializationCandidates(PointerToBaseTy PointerToBase,
  2101. RematCandTy &RematerizationCandidates,
  2102. TargetTransformInfo &TTI) {
  2103. const unsigned int ChainLengthThreshold = 10;
  2104. for (auto P2B : PointerToBase) {
  2105. auto *Derived = P2B.first;
  2106. auto *Base = P2B.second;
  2107. // Consider only derived pointers.
  2108. if (Derived == Base)
  2109. continue;
  2110. // For each live pointer find its defining chain.
  2111. SmallVector<Instruction *, 3> ChainToBase;
  2112. Value *RootOfChain =
  2113. findRematerializableChainToBasePointer(ChainToBase, Derived);
  2114. // Nothing to do, or chain is too long
  2115. if ( ChainToBase.size() == 0 ||
  2116. ChainToBase.size() > ChainLengthThreshold)
  2117. continue;
  2118. // Handle the scenario where the RootOfChain is not equal to the
  2119. // Base Value, but they are essentially the same phi values.
  2120. if (RootOfChain != PointerToBase[Derived]) {
  2121. PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
  2122. PHINode *AlternateRootPhi = dyn_cast<PHINode>(PointerToBase[Derived]);
  2123. if (!OrigRootPhi || !AlternateRootPhi)
  2124. continue;
  2125. // PHI nodes that have the same incoming values, and belonging to the same
  2126. // basic blocks are essentially the same SSA value. When the original phi
  2127. // has incoming values with different base pointers, the original phi is
  2128. // marked as conflict, and an additional `AlternateRootPhi` with the same
  2129. // incoming values get generated by the findBasePointer function. We need
  2130. // to identify the newly generated AlternateRootPhi (.base version of phi)
  2131. // and RootOfChain (the original phi node itself) are the same, so that we
  2132. // can rematerialize the gep and casts. This is a workaround for the
  2133. // deficiency in the findBasePointer algorithm.
  2134. if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
  2135. continue;
  2136. }
  2137. // Compute cost of this chain.
  2138. InstructionCost Cost = chainToBasePointerCost(ChainToBase, TTI);
  2139. // TODO: We can also account for cases when we will be able to remove some
  2140. // of the rematerialized values by later optimization passes. I.e if
  2141. // we rematerialized several intersecting chains. Or if original values
  2142. // don't have any uses besides this statepoint.
  2143. // Ok, there is a candidate.
  2144. RematerizlizationCandidateRecord Record;
  2145. Record.ChainToBase = ChainToBase;
  2146. Record.RootOfChain = RootOfChain;
  2147. Record.Cost = Cost;
  2148. RematerizationCandidates.insert({ Derived, Record });
  2149. }
  2150. }
  2151. // Try to rematerialize derived pointers immediately before their uses
  2152. // (instead of rematerializing after every statepoint it is live through).
  2153. // This can be beneficial when derived pointer is live across many
  2154. // statepoints, but uses are rare.
  2155. static void rematerializeLiveValuesAtUses(
  2156. RematCandTy &RematerizationCandidates,
  2157. MutableArrayRef<PartiallyConstructedSafepointRecord> Records,
  2158. PointerToBaseTy &PointerToBase) {
  2159. if (!RematDerivedAtUses)
  2160. return;
  2161. SmallVector<Instruction *, 32> LiveValuesToBeDeleted;
  2162. LLVM_DEBUG(dbgs() << "Rematerialize derived pointers at uses, "
  2163. << "Num statepoints: " << Records.size() << '\n');
  2164. for (auto &It : RematerizationCandidates) {
  2165. Instruction *Cand = cast<Instruction>(It.first);
  2166. auto &Record = It.second;
  2167. if (Record.Cost >= RematerializationThreshold)
  2168. continue;
  2169. if (Cand->user_empty())
  2170. continue;
  2171. if (Cand->hasOneUse())
  2172. if (auto *U = dyn_cast<Instruction>(Cand->getUniqueUndroppableUser()))
  2173. if (U->getParent() == Cand->getParent())
  2174. continue;
  2175. // Rematerialization before PHI nodes is not implemented.
  2176. if (llvm::any_of(Cand->users(),
  2177. [](const auto *U) { return isa<PHINode>(U); }))
  2178. continue;
  2179. LLVM_DEBUG(dbgs() << "Trying cand " << *Cand << " ... ");
  2180. // Count of rematerialization instructions we introduce is equal to number
  2181. // of candidate uses.
  2182. // Count of rematerialization instructions we eliminate is equal to number
  2183. // of statepoints it is live through.
  2184. // Consider transformation profitable if latter is greater than former
  2185. // (in other words, we create less than eliminate).
  2186. unsigned NumLiveStatepoints = llvm::count_if(
  2187. Records, [Cand](const auto &R) { return R.LiveSet.contains(Cand); });
  2188. unsigned NumUses = Cand->getNumUses();
  2189. LLVM_DEBUG(dbgs() << "Num uses: " << NumUses << " Num live statepoints: "
  2190. << NumLiveStatepoints << " ");
  2191. if (NumLiveStatepoints < NumUses) {
  2192. LLVM_DEBUG(dbgs() << "not profitable\n");
  2193. continue;
  2194. }
  2195. // If rematerialization is 'free', then favor rematerialization at
  2196. // uses as it generally shortens live ranges.
  2197. // TODO: Short (size ==1) chains only?
  2198. if (NumLiveStatepoints == NumUses && Record.Cost > 0) {
  2199. LLVM_DEBUG(dbgs() << "not profitable\n");
  2200. continue;
  2201. }
  2202. LLVM_DEBUG(dbgs() << "looks profitable\n");
  2203. // ChainToBase may contain another remat candidate (as a sub chain) which
  2204. // has been rewritten by now. Need to recollect chain to have up to date
  2205. // value.
  2206. // TODO: sort records in findRematerializationCandidates() in
  2207. // decreasing chain size order?
  2208. if (Record.ChainToBase.size() > 1) {
  2209. Record.ChainToBase.clear();
  2210. findRematerializableChainToBasePointer(Record.ChainToBase, Cand);
  2211. }
  2212. // Current rematerialization algorithm is very simple: we rematerialize
  2213. // immediately before EVERY use, even if there are several uses in same
  2214. // block or if use is local to Cand Def. The reason is that this allows
  2215. // us to avoid recomputing liveness without complicated analysis:
  2216. // - If we did not eliminate all uses of original Candidate, we do not
  2217. // know exaclty in what BBs it is still live.
  2218. // - If we rematerialize once per BB, we need to find proper insertion
  2219. // place (first use in block, but after Def) and analyze if there is
  2220. // statepoint between uses in the block.
  2221. while (!Cand->user_empty()) {
  2222. Instruction *UserI = cast<Instruction>(*Cand->user_begin());
  2223. Instruction *RematChain = rematerializeChain(
  2224. Record.ChainToBase, UserI, Record.RootOfChain, PointerToBase[Cand]);
  2225. UserI->replaceUsesOfWith(Cand, RematChain);
  2226. PointerToBase[RematChain] = PointerToBase[Cand];
  2227. }
  2228. LiveValuesToBeDeleted.push_back(Cand);
  2229. }
  2230. LLVM_DEBUG(dbgs() << "Rematerialized " << LiveValuesToBeDeleted.size()
  2231. << " derived pointers\n");
  2232. for (auto *Cand : LiveValuesToBeDeleted) {
  2233. assert(Cand->use_empty() && "Unexpected user remain");
  2234. RematerizationCandidates.erase(Cand);
  2235. for (auto &R : Records) {
  2236. assert(!R.LiveSet.contains(Cand) ||
  2237. R.LiveSet.contains(PointerToBase[Cand]));
  2238. R.LiveSet.remove(Cand);
  2239. }
  2240. }
  2241. // Recollect not rematerialized chains - we might have rewritten
  2242. // their sub-chains.
  2243. if (!LiveValuesToBeDeleted.empty()) {
  2244. for (auto &P : RematerizationCandidates) {
  2245. auto &R = P.second;
  2246. if (R.ChainToBase.size() > 1) {
  2247. R.ChainToBase.clear();
  2248. findRematerializableChainToBasePointer(R.ChainToBase, P.first);
  2249. }
  2250. }
  2251. }
  2252. }
  2253. // From the statepoint live set pick values that are cheaper to recompute then
  2254. // to relocate. Remove this values from the live set, rematerialize them after
  2255. // statepoint and record them in "Info" structure. Note that similar to
  2256. // relocated values we don't do any user adjustments here.
  2257. static void rematerializeLiveValues(CallBase *Call,
  2258. PartiallyConstructedSafepointRecord &Info,
  2259. PointerToBaseTy &PointerToBase,
  2260. RematCandTy &RematerizationCandidates,
  2261. TargetTransformInfo &TTI) {
  2262. // Record values we are going to delete from this statepoint live set.
  2263. // We can not di this in following loop due to iterator invalidation.
  2264. SmallVector<Value *, 32> LiveValuesToBeDeleted;
  2265. for (Value *LiveValue : Info.LiveSet) {
  2266. auto It = RematerizationCandidates.find(LiveValue);
  2267. if (It == RematerizationCandidates.end())
  2268. continue;
  2269. RematerizlizationCandidateRecord &Record = It->second;
  2270. InstructionCost Cost = Record.Cost;
  2271. // For invokes we need to rematerialize each chain twice - for normal and
  2272. // for unwind basic blocks. Model this by multiplying cost by two.
  2273. if (isa<InvokeInst>(Call))
  2274. Cost *= 2;
  2275. // If it's too expensive - skip it.
  2276. if (Cost >= RematerializationThreshold)
  2277. continue;
  2278. // Remove value from the live set
  2279. LiveValuesToBeDeleted.push_back(LiveValue);
  2280. // Clone instructions and record them inside "Info" structure.
  2281. // Different cases for calls and invokes. For invokes we need to clone
  2282. // instructions both on normal and unwind path.
  2283. if (isa<CallInst>(Call)) {
  2284. Instruction *InsertBefore = Call->getNextNode();
  2285. assert(InsertBefore);
  2286. Instruction *RematerializedValue =
  2287. rematerializeChain(Record.ChainToBase, InsertBefore,
  2288. Record.RootOfChain, PointerToBase[LiveValue]);
  2289. Info.RematerializedValues[RematerializedValue] = LiveValue;
  2290. } else {
  2291. auto *Invoke = cast<InvokeInst>(Call);
  2292. Instruction *NormalInsertBefore =
  2293. &*Invoke->getNormalDest()->getFirstInsertionPt();
  2294. Instruction *UnwindInsertBefore =
  2295. &*Invoke->getUnwindDest()->getFirstInsertionPt();
  2296. Instruction *NormalRematerializedValue =
  2297. rematerializeChain(Record.ChainToBase, NormalInsertBefore,
  2298. Record.RootOfChain, PointerToBase[LiveValue]);
  2299. Instruction *UnwindRematerializedValue =
  2300. rematerializeChain(Record.ChainToBase, UnwindInsertBefore,
  2301. Record.RootOfChain, PointerToBase[LiveValue]);
  2302. Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
  2303. Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
  2304. }
  2305. }
  2306. // Remove rematerialized values from the live set.
  2307. for (auto *LiveValue: LiveValuesToBeDeleted) {
  2308. Info.LiveSet.remove(LiveValue);
  2309. }
  2310. }
  2311. static bool inlineGetBaseAndOffset(Function &F,
  2312. SmallVectorImpl<CallInst *> &Intrinsics,
  2313. DefiningValueMapTy &DVCache,
  2314. IsKnownBaseMapTy &KnownBases) {
  2315. auto &Context = F.getContext();
  2316. auto &DL = F.getParent()->getDataLayout();
  2317. bool Changed = false;
  2318. for (auto *Callsite : Intrinsics)
  2319. switch (Callsite->getIntrinsicID()) {
  2320. case Intrinsic::experimental_gc_get_pointer_base: {
  2321. Changed = true;
  2322. Value *Base =
  2323. findBasePointer(Callsite->getOperand(0), DVCache, KnownBases);
  2324. assert(!DVCache.count(Callsite));
  2325. auto *BaseBC = IRBuilder<>(Callsite).CreateBitCast(
  2326. Base, Callsite->getType(), suffixed_name_or(Base, ".cast", ""));
  2327. if (BaseBC != Base)
  2328. DVCache[BaseBC] = Base;
  2329. Callsite->replaceAllUsesWith(BaseBC);
  2330. if (!BaseBC->hasName())
  2331. BaseBC->takeName(Callsite);
  2332. Callsite->eraseFromParent();
  2333. break;
  2334. }
  2335. case Intrinsic::experimental_gc_get_pointer_offset: {
  2336. Changed = true;
  2337. Value *Derived = Callsite->getOperand(0);
  2338. Value *Base = findBasePointer(Derived, DVCache, KnownBases);
  2339. assert(!DVCache.count(Callsite));
  2340. unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
  2341. unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
  2342. IRBuilder<> Builder(Callsite);
  2343. Value *BaseInt =
  2344. Builder.CreatePtrToInt(Base, Type::getIntNTy(Context, IntPtrSize),
  2345. suffixed_name_or(Base, ".int", ""));
  2346. Value *DerivedInt =
  2347. Builder.CreatePtrToInt(Derived, Type::getIntNTy(Context, IntPtrSize),
  2348. suffixed_name_or(Derived, ".int", ""));
  2349. Value *Offset = Builder.CreateSub(DerivedInt, BaseInt);
  2350. Callsite->replaceAllUsesWith(Offset);
  2351. Offset->takeName(Callsite);
  2352. Callsite->eraseFromParent();
  2353. break;
  2354. }
  2355. default:
  2356. llvm_unreachable("Unknown intrinsic");
  2357. }
  2358. return Changed;
  2359. }
  2360. static bool insertParsePoints(Function &F, DominatorTree &DT,
  2361. TargetTransformInfo &TTI,
  2362. SmallVectorImpl<CallBase *> &ToUpdate,
  2363. DefiningValueMapTy &DVCache,
  2364. IsKnownBaseMapTy &KnownBases) {
  2365. #ifndef NDEBUG
  2366. // Validate the input
  2367. std::set<CallBase *> Uniqued;
  2368. Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
  2369. assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
  2370. for (CallBase *Call : ToUpdate)
  2371. assert(Call->getFunction() == &F);
  2372. #endif
  2373. // When inserting gc.relocates for invokes, we need to be able to insert at
  2374. // the top of the successor blocks. See the comment on
  2375. // normalForInvokeSafepoint on exactly what is needed. Note that this step
  2376. // may restructure the CFG.
  2377. for (CallBase *Call : ToUpdate) {
  2378. auto *II = dyn_cast<InvokeInst>(Call);
  2379. if (!II)
  2380. continue;
  2381. normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
  2382. normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
  2383. }
  2384. // A list of dummy calls added to the IR to keep various values obviously
  2385. // live in the IR. We'll remove all of these when done.
  2386. SmallVector<CallInst *, 64> Holders;
  2387. // Insert a dummy call with all of the deopt operands we'll need for the
  2388. // actual safepoint insertion as arguments. This ensures reference operands
  2389. // in the deopt argument list are considered live through the safepoint (and
  2390. // thus makes sure they get relocated.)
  2391. for (CallBase *Call : ToUpdate) {
  2392. SmallVector<Value *, 64> DeoptValues;
  2393. for (Value *Arg : GetDeoptBundleOperands(Call)) {
  2394. assert(!isUnhandledGCPointerType(Arg->getType()) &&
  2395. "support for FCA unimplemented");
  2396. if (isHandledGCPointerType(Arg->getType()))
  2397. DeoptValues.push_back(Arg);
  2398. }
  2399. insertUseHolderAfter(Call, DeoptValues, Holders);
  2400. }
  2401. SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
  2402. // A) Identify all gc pointers which are statically live at the given call
  2403. // site.
  2404. findLiveReferences(F, DT, ToUpdate, Records);
  2405. /// Global mapping from live pointers to a base-defining-value.
  2406. PointerToBaseTy PointerToBase;
  2407. // B) Find the base pointers for each live pointer
  2408. for (size_t i = 0; i < Records.size(); i++) {
  2409. PartiallyConstructedSafepointRecord &info = Records[i];
  2410. findBasePointers(DT, DVCache, ToUpdate[i], info, PointerToBase, KnownBases);
  2411. }
  2412. if (PrintBasePointers) {
  2413. errs() << "Base Pairs (w/o Relocation):\n";
  2414. for (auto &Pair : PointerToBase) {
  2415. errs() << " derived ";
  2416. Pair.first->printAsOperand(errs(), false);
  2417. errs() << " base ";
  2418. Pair.second->printAsOperand(errs(), false);
  2419. errs() << "\n";
  2420. ;
  2421. }
  2422. }
  2423. // The base phi insertion logic (for any safepoint) may have inserted new
  2424. // instructions which are now live at some safepoint. The simplest such
  2425. // example is:
  2426. // loop:
  2427. // phi a <-- will be a new base_phi here
  2428. // safepoint 1 <-- that needs to be live here
  2429. // gep a + 1
  2430. // safepoint 2
  2431. // br loop
  2432. // We insert some dummy calls after each safepoint to definitely hold live
  2433. // the base pointers which were identified for that safepoint. We'll then
  2434. // ask liveness for _every_ base inserted to see what is now live. Then we
  2435. // remove the dummy calls.
  2436. Holders.reserve(Holders.size() + Records.size());
  2437. for (size_t i = 0; i < Records.size(); i++) {
  2438. PartiallyConstructedSafepointRecord &Info = Records[i];
  2439. SmallVector<Value *, 128> Bases;
  2440. for (auto *Derived : Info.LiveSet) {
  2441. assert(PointerToBase.count(Derived) && "Missed base for derived pointer");
  2442. Bases.push_back(PointerToBase[Derived]);
  2443. }
  2444. insertUseHolderAfter(ToUpdate[i], Bases, Holders);
  2445. }
  2446. // By selecting base pointers, we've effectively inserted new uses. Thus, we
  2447. // need to rerun liveness. We may *also* have inserted new defs, but that's
  2448. // not the key issue.
  2449. recomputeLiveInValues(F, DT, ToUpdate, Records, PointerToBase);
  2450. if (PrintBasePointers) {
  2451. errs() << "Base Pairs: (w/Relocation)\n";
  2452. for (auto Pair : PointerToBase) {
  2453. errs() << " derived ";
  2454. Pair.first->printAsOperand(errs(), false);
  2455. errs() << " base ";
  2456. Pair.second->printAsOperand(errs(), false);
  2457. errs() << "\n";
  2458. }
  2459. }
  2460. // It is possible that non-constant live variables have a constant base. For
  2461. // example, a GEP with a variable offset from a global. In this case we can
  2462. // remove it from the liveset. We already don't add constants to the liveset
  2463. // because we assume they won't move at runtime and the GC doesn't need to be
  2464. // informed about them. The same reasoning applies if the base is constant.
  2465. // Note that the relocation placement code relies on this filtering for
  2466. // correctness as it expects the base to be in the liveset, which isn't true
  2467. // if the base is constant.
  2468. for (auto &Info : Records) {
  2469. Info.LiveSet.remove_if([&](Value *LiveV) {
  2470. assert(PointerToBase.count(LiveV) && "Missed base for derived pointer");
  2471. return isa<Constant>(PointerToBase[LiveV]);
  2472. });
  2473. }
  2474. for (CallInst *CI : Holders)
  2475. CI->eraseFromParent();
  2476. Holders.clear();
  2477. // Compute the cost of possible re-materialization of derived pointers.
  2478. RematCandTy RematerizationCandidates;
  2479. findRematerializationCandidates(PointerToBase, RematerizationCandidates, TTI);
  2480. // In order to reduce live set of statepoint we might choose to rematerialize
  2481. // some values instead of relocating them. This is purely an optimization and
  2482. // does not influence correctness.
  2483. // First try rematerialization at uses, then after statepoints.
  2484. rematerializeLiveValuesAtUses(RematerizationCandidates, Records,
  2485. PointerToBase);
  2486. for (size_t i = 0; i < Records.size(); i++)
  2487. rematerializeLiveValues(ToUpdate[i], Records[i], PointerToBase,
  2488. RematerizationCandidates, TTI);
  2489. // We need this to safely RAUW and delete call or invoke return values that
  2490. // may themselves be live over a statepoint. For details, please see usage in
  2491. // makeStatepointExplicitImpl.
  2492. std::vector<DeferredReplacement> Replacements;
  2493. // Now run through and replace the existing statepoints with new ones with
  2494. // the live variables listed. We do not yet update uses of the values being
  2495. // relocated. We have references to live variables that need to
  2496. // survive to the last iteration of this loop. (By construction, the
  2497. // previous statepoint can not be a live variable, thus we can and remove
  2498. // the old statepoint calls as we go.)
  2499. for (size_t i = 0; i < Records.size(); i++)
  2500. makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements,
  2501. PointerToBase);
  2502. ToUpdate.clear(); // prevent accident use of invalid calls.
  2503. for (auto &PR : Replacements)
  2504. PR.doReplacement();
  2505. Replacements.clear();
  2506. for (auto &Info : Records) {
  2507. // These live sets may contain state Value pointers, since we replaced calls
  2508. // with operand bundles with calls wrapped in gc.statepoint, and some of
  2509. // those calls may have been def'ing live gc pointers. Clear these out to
  2510. // avoid accidentally using them.
  2511. //
  2512. // TODO: We should create a separate data structure that does not contain
  2513. // these live sets, and migrate to using that data structure from this point
  2514. // onward.
  2515. Info.LiveSet.clear();
  2516. }
  2517. PointerToBase.clear();
  2518. // Do all the fixups of the original live variables to their relocated selves
  2519. SmallVector<Value *, 128> Live;
  2520. for (size_t i = 0; i < Records.size(); i++) {
  2521. PartiallyConstructedSafepointRecord &Info = Records[i];
  2522. // We can't simply save the live set from the original insertion. One of
  2523. // the live values might be the result of a call which needs a safepoint.
  2524. // That Value* no longer exists and we need to use the new gc_result.
  2525. // Thankfully, the live set is embedded in the statepoint (and updated), so
  2526. // we just grab that.
  2527. llvm::append_range(Live, Info.StatepointToken->gc_args());
  2528. #ifndef NDEBUG
  2529. // Do some basic validation checking on our liveness results before
  2530. // performing relocation. Relocation can and will turn mistakes in liveness
  2531. // results into non-sensical code which is must harder to debug.
  2532. // TODO: It would be nice to test consistency as well
  2533. assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
  2534. "statepoint must be reachable or liveness is meaningless");
  2535. for (Value *V : Info.StatepointToken->gc_args()) {
  2536. if (!isa<Instruction>(V))
  2537. // Non-instruction values trivial dominate all possible uses
  2538. continue;
  2539. auto *LiveInst = cast<Instruction>(V);
  2540. assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
  2541. "unreachable values should never be live");
  2542. assert(DT.dominates(LiveInst, Info.StatepointToken) &&
  2543. "basic SSA liveness expectation violated by liveness analysis");
  2544. }
  2545. #endif
  2546. }
  2547. unique_unsorted(Live);
  2548. #ifndef NDEBUG
  2549. // Validation check
  2550. for (auto *Ptr : Live)
  2551. assert(isHandledGCPointerType(Ptr->getType()) &&
  2552. "must be a gc pointer type");
  2553. #endif
  2554. relocationViaAlloca(F, DT, Live, Records);
  2555. return !Records.empty();
  2556. }
  2557. // List of all parameter and return attributes which must be stripped when
  2558. // lowering from the abstract machine model. Note that we list attributes
  2559. // here which aren't valid as return attributes, that is okay.
  2560. static AttributeMask getParamAndReturnAttributesToRemove() {
  2561. AttributeMask R;
  2562. R.addAttribute(Attribute::Dereferenceable);
  2563. R.addAttribute(Attribute::DereferenceableOrNull);
  2564. R.addAttribute(Attribute::ReadNone);
  2565. R.addAttribute(Attribute::ReadOnly);
  2566. R.addAttribute(Attribute::WriteOnly);
  2567. R.addAttribute(Attribute::NoAlias);
  2568. R.addAttribute(Attribute::NoFree);
  2569. return R;
  2570. }
  2571. static void stripNonValidAttributesFromPrototype(Function &F) {
  2572. LLVMContext &Ctx = F.getContext();
  2573. // Intrinsics are very delicate. Lowering sometimes depends the presence
  2574. // of certain attributes for correctness, but we may have also inferred
  2575. // additional ones in the abstract machine model which need stripped. This
  2576. // assumes that the attributes defined in Intrinsic.td are conservatively
  2577. // correct for both physical and abstract model.
  2578. if (Intrinsic::ID id = F.getIntrinsicID()) {
  2579. F.setAttributes(Intrinsic::getAttributes(Ctx, id));
  2580. return;
  2581. }
  2582. AttributeMask R = getParamAndReturnAttributesToRemove();
  2583. for (Argument &A : F.args())
  2584. if (isa<PointerType>(A.getType()))
  2585. F.removeParamAttrs(A.getArgNo(), R);
  2586. if (isa<PointerType>(F.getReturnType()))
  2587. F.removeRetAttrs(R);
  2588. for (auto Attr : FnAttrsToStrip)
  2589. F.removeFnAttr(Attr);
  2590. }
  2591. /// Certain metadata on instructions are invalid after running RS4GC.
  2592. /// Optimizations that run after RS4GC can incorrectly use this metadata to
  2593. /// optimize functions. We drop such metadata on the instruction.
  2594. static void stripInvalidMetadataFromInstruction(Instruction &I) {
  2595. if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
  2596. return;
  2597. // These are the attributes that are still valid on loads and stores after
  2598. // RS4GC.
  2599. // The metadata implying dereferenceability and noalias are (conservatively)
  2600. // dropped. This is because semantically, after RewriteStatepointsForGC runs,
  2601. // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
  2602. // touch the entire heap including noalias objects. Note: The reasoning is
  2603. // same as stripping the dereferenceability and noalias attributes that are
  2604. // analogous to the metadata counterparts.
  2605. // We also drop the invariant.load metadata on the load because that metadata
  2606. // implies the address operand to the load points to memory that is never
  2607. // changed once it became dereferenceable. This is no longer true after RS4GC.
  2608. // Similar reasoning applies to invariant.group metadata, which applies to
  2609. // loads within a group.
  2610. unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
  2611. LLVMContext::MD_range,
  2612. LLVMContext::MD_alias_scope,
  2613. LLVMContext::MD_nontemporal,
  2614. LLVMContext::MD_nonnull,
  2615. LLVMContext::MD_align,
  2616. LLVMContext::MD_type};
  2617. // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
  2618. I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
  2619. }
  2620. static void stripNonValidDataFromBody(Function &F) {
  2621. if (F.empty())
  2622. return;
  2623. LLVMContext &Ctx = F.getContext();
  2624. MDBuilder Builder(Ctx);
  2625. // Set of invariantstart instructions that we need to remove.
  2626. // Use this to avoid invalidating the instruction iterator.
  2627. SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
  2628. for (Instruction &I : instructions(F)) {
  2629. // invariant.start on memory location implies that the referenced memory
  2630. // location is constant and unchanging. This is no longer true after
  2631. // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
  2632. // which frees the entire heap and the presence of invariant.start allows
  2633. // the optimizer to sink the load of a memory location past a statepoint,
  2634. // which is incorrect.
  2635. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  2636. if (II->getIntrinsicID() == Intrinsic::invariant_start) {
  2637. InvariantStartInstructions.push_back(II);
  2638. continue;
  2639. }
  2640. if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
  2641. MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
  2642. I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
  2643. }
  2644. stripInvalidMetadataFromInstruction(I);
  2645. AttributeMask R = getParamAndReturnAttributesToRemove();
  2646. if (auto *Call = dyn_cast<CallBase>(&I)) {
  2647. for (int i = 0, e = Call->arg_size(); i != e; i++)
  2648. if (isa<PointerType>(Call->getArgOperand(i)->getType()))
  2649. Call->removeParamAttrs(i, R);
  2650. if (isa<PointerType>(Call->getType()))
  2651. Call->removeRetAttrs(R);
  2652. }
  2653. }
  2654. // Delete the invariant.start instructions and RAUW undef.
  2655. for (auto *II : InvariantStartInstructions) {
  2656. II->replaceAllUsesWith(UndefValue::get(II->getType()));
  2657. II->eraseFromParent();
  2658. }
  2659. }
  2660. /// Returns true if this function should be rewritten by this pass. The main
  2661. /// point of this function is as an extension point for custom logic.
  2662. static bool shouldRewriteStatepointsIn(Function &F) {
  2663. // TODO: This should check the GCStrategy
  2664. if (F.hasGC()) {
  2665. const auto &FunctionGCName = F.getGC();
  2666. const StringRef StatepointExampleName("statepoint-example");
  2667. const StringRef CoreCLRName("coreclr");
  2668. return (StatepointExampleName == FunctionGCName) ||
  2669. (CoreCLRName == FunctionGCName);
  2670. } else
  2671. return false;
  2672. }
  2673. static void stripNonValidData(Module &M) {
  2674. #ifndef NDEBUG
  2675. assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
  2676. #endif
  2677. for (Function &F : M)
  2678. stripNonValidAttributesFromPrototype(F);
  2679. for (Function &F : M)
  2680. stripNonValidDataFromBody(F);
  2681. }
  2682. bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
  2683. TargetTransformInfo &TTI,
  2684. const TargetLibraryInfo &TLI) {
  2685. assert(!F.isDeclaration() && !F.empty() &&
  2686. "need function body to rewrite statepoints in");
  2687. assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
  2688. auto NeedsRewrite = [&TLI](Instruction &I) {
  2689. if (const auto *Call = dyn_cast<CallBase>(&I)) {
  2690. if (isa<GCStatepointInst>(Call))
  2691. return false;
  2692. if (callsGCLeafFunction(Call, TLI))
  2693. return false;
  2694. // Normally it's up to the frontend to make sure that non-leaf calls also
  2695. // have proper deopt state if it is required. We make an exception for
  2696. // element atomic memcpy/memmove intrinsics here. Unlike other intrinsics
  2697. // these are non-leaf by default. They might be generated by the optimizer
  2698. // which doesn't know how to produce a proper deopt state. So if we see a
  2699. // non-leaf memcpy/memmove without deopt state just treat it as a leaf
  2700. // copy and don't produce a statepoint.
  2701. if (!AllowStatepointWithNoDeoptInfo &&
  2702. !Call->getOperandBundle(LLVMContext::OB_deopt)) {
  2703. assert((isa<AtomicMemCpyInst>(Call) || isa<AtomicMemMoveInst>(Call)) &&
  2704. "Don't expect any other calls here!");
  2705. return false;
  2706. }
  2707. return true;
  2708. }
  2709. return false;
  2710. };
  2711. // Delete any unreachable statepoints so that we don't have unrewritten
  2712. // statepoints surviving this pass. This makes testing easier and the
  2713. // resulting IR less confusing to human readers.
  2714. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  2715. bool MadeChange = removeUnreachableBlocks(F, &DTU);
  2716. // Flush the Dominator Tree.
  2717. DTU.getDomTree();
  2718. // Gather all the statepoints which need rewritten. Be careful to only
  2719. // consider those in reachable code since we need to ask dominance queries
  2720. // when rewriting. We'll delete the unreachable ones in a moment.
  2721. SmallVector<CallBase *, 64> ParsePointNeeded;
  2722. SmallVector<CallInst *, 64> Intrinsics;
  2723. for (Instruction &I : instructions(F)) {
  2724. // TODO: only the ones with the flag set!
  2725. if (NeedsRewrite(I)) {
  2726. // NOTE removeUnreachableBlocks() is stronger than
  2727. // DominatorTree::isReachableFromEntry(). In other words
  2728. // removeUnreachableBlocks can remove some blocks for which
  2729. // isReachableFromEntry() returns true.
  2730. assert(DT.isReachableFromEntry(I.getParent()) &&
  2731. "no unreachable blocks expected");
  2732. ParsePointNeeded.push_back(cast<CallBase>(&I));
  2733. }
  2734. if (auto *CI = dyn_cast<CallInst>(&I))
  2735. if (CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_base ||
  2736. CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_offset)
  2737. Intrinsics.emplace_back(CI);
  2738. }
  2739. // Return early if no work to do.
  2740. if (ParsePointNeeded.empty() && Intrinsics.empty())
  2741. return MadeChange;
  2742. // As a prepass, go ahead and aggressively destroy single entry phi nodes.
  2743. // These are created by LCSSA. They have the effect of increasing the size
  2744. // of liveness sets for no good reason. It may be harder to do this post
  2745. // insertion since relocations and base phis can confuse things.
  2746. for (BasicBlock &BB : F)
  2747. if (BB.getUniquePredecessor())
  2748. MadeChange |= FoldSingleEntryPHINodes(&BB);
  2749. // Before we start introducing relocations, we want to tweak the IR a bit to
  2750. // avoid unfortunate code generation effects. The main example is that we
  2751. // want to try to make sure the comparison feeding a branch is after any
  2752. // safepoints. Otherwise, we end up with a comparison of pre-relocation
  2753. // values feeding a branch after relocation. This is semantically correct,
  2754. // but results in extra register pressure since both the pre-relocation and
  2755. // post-relocation copies must be available in registers. For code without
  2756. // relocations this is handled elsewhere, but teaching the scheduler to
  2757. // reverse the transform we're about to do would be slightly complex.
  2758. // Note: This may extend the live range of the inputs to the icmp and thus
  2759. // increase the liveset of any statepoint we move over. This is profitable
  2760. // as long as all statepoints are in rare blocks. If we had in-register
  2761. // lowering for live values this would be a much safer transform.
  2762. auto getConditionInst = [](Instruction *TI) -> Instruction * {
  2763. if (auto *BI = dyn_cast<BranchInst>(TI))
  2764. if (BI->isConditional())
  2765. return dyn_cast<Instruction>(BI->getCondition());
  2766. // TODO: Extend this to handle switches
  2767. return nullptr;
  2768. };
  2769. for (BasicBlock &BB : F) {
  2770. Instruction *TI = BB.getTerminator();
  2771. if (auto *Cond = getConditionInst(TI))
  2772. // TODO: Handle more than just ICmps here. We should be able to move
  2773. // most instructions without side effects or memory access.
  2774. if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
  2775. MadeChange = true;
  2776. Cond->moveBefore(TI);
  2777. }
  2778. }
  2779. // Nasty workaround - The base computation code in the main algorithm doesn't
  2780. // consider the fact that a GEP can be used to convert a scalar to a vector.
  2781. // The right fix for this is to integrate GEPs into the base rewriting
  2782. // algorithm properly, this is just a short term workaround to prevent
  2783. // crashes by canonicalizing such GEPs into fully vector GEPs.
  2784. for (Instruction &I : instructions(F)) {
  2785. if (!isa<GetElementPtrInst>(I))
  2786. continue;
  2787. unsigned VF = 0;
  2788. for (unsigned i = 0; i < I.getNumOperands(); i++)
  2789. if (auto *OpndVTy = dyn_cast<VectorType>(I.getOperand(i)->getType())) {
  2790. assert(VF == 0 ||
  2791. VF == cast<FixedVectorType>(OpndVTy)->getNumElements());
  2792. VF = cast<FixedVectorType>(OpndVTy)->getNumElements();
  2793. }
  2794. // It's the vector to scalar traversal through the pointer operand which
  2795. // confuses base pointer rewriting, so limit ourselves to that case.
  2796. if (!I.getOperand(0)->getType()->isVectorTy() && VF != 0) {
  2797. IRBuilder<> B(&I);
  2798. auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
  2799. I.setOperand(0, Splat);
  2800. MadeChange = true;
  2801. }
  2802. }
  2803. // Cache the 'defining value' relation used in the computation and
  2804. // insertion of base phis and selects. This ensures that we don't insert
  2805. // large numbers of duplicate base_phis. Use one cache for both
  2806. // inlineGetBaseAndOffset() and insertParsePoints().
  2807. DefiningValueMapTy DVCache;
  2808. // Mapping between a base values and a flag indicating whether it's a known
  2809. // base or not.
  2810. IsKnownBaseMapTy KnownBases;
  2811. if (!Intrinsics.empty())
  2812. // Inline @gc.get.pointer.base() and @gc.get.pointer.offset() before finding
  2813. // live references.
  2814. MadeChange |= inlineGetBaseAndOffset(F, Intrinsics, DVCache, KnownBases);
  2815. if (!ParsePointNeeded.empty())
  2816. MadeChange |=
  2817. insertParsePoints(F, DT, TTI, ParsePointNeeded, DVCache, KnownBases);
  2818. return MadeChange;
  2819. }
  2820. // liveness computation via standard dataflow
  2821. // -------------------------------------------------------------------
  2822. // TODO: Consider using bitvectors for liveness, the set of potentially
  2823. // interesting values should be small and easy to pre-compute.
  2824. /// Compute the live-in set for the location rbegin starting from
  2825. /// the live-out set of the basic block
  2826. static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
  2827. BasicBlock::reverse_iterator End,
  2828. SetVector<Value *> &LiveTmp) {
  2829. for (auto &I : make_range(Begin, End)) {
  2830. // KILL/Def - Remove this definition from LiveIn
  2831. LiveTmp.remove(&I);
  2832. // Don't consider *uses* in PHI nodes, we handle their contribution to
  2833. // predecessor blocks when we seed the LiveOut sets
  2834. if (isa<PHINode>(I))
  2835. continue;
  2836. // USE - Add to the LiveIn set for this instruction
  2837. for (Value *V : I.operands()) {
  2838. assert(!isUnhandledGCPointerType(V->getType()) &&
  2839. "support for FCA unimplemented");
  2840. if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
  2841. // The choice to exclude all things constant here is slightly subtle.
  2842. // There are two independent reasons:
  2843. // - We assume that things which are constant (from LLVM's definition)
  2844. // do not move at runtime. For example, the address of a global
  2845. // variable is fixed, even though it's contents may not be.
  2846. // - Second, we can't disallow arbitrary inttoptr constants even
  2847. // if the language frontend does. Optimization passes are free to
  2848. // locally exploit facts without respect to global reachability. This
  2849. // can create sections of code which are dynamically unreachable and
  2850. // contain just about anything. (see constants.ll in tests)
  2851. LiveTmp.insert(V);
  2852. }
  2853. }
  2854. }
  2855. }
  2856. static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
  2857. for (BasicBlock *Succ : successors(BB)) {
  2858. for (auto &I : *Succ) {
  2859. PHINode *PN = dyn_cast<PHINode>(&I);
  2860. if (!PN)
  2861. break;
  2862. Value *V = PN->getIncomingValueForBlock(BB);
  2863. assert(!isUnhandledGCPointerType(V->getType()) &&
  2864. "support for FCA unimplemented");
  2865. if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
  2866. LiveTmp.insert(V);
  2867. }
  2868. }
  2869. }
  2870. static SetVector<Value *> computeKillSet(BasicBlock *BB) {
  2871. SetVector<Value *> KillSet;
  2872. for (Instruction &I : *BB)
  2873. if (isHandledGCPointerType(I.getType()))
  2874. KillSet.insert(&I);
  2875. return KillSet;
  2876. }
  2877. #ifndef NDEBUG
  2878. /// Check that the items in 'Live' dominate 'TI'. This is used as a basic
  2879. /// validation check for the liveness computation.
  2880. static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
  2881. Instruction *TI, bool TermOkay = false) {
  2882. for (Value *V : Live) {
  2883. if (auto *I = dyn_cast<Instruction>(V)) {
  2884. // The terminator can be a member of the LiveOut set. LLVM's definition
  2885. // of instruction dominance states that V does not dominate itself. As
  2886. // such, we need to special case this to allow it.
  2887. if (TermOkay && TI == I)
  2888. continue;
  2889. assert(DT.dominates(I, TI) &&
  2890. "basic SSA liveness expectation violated by liveness analysis");
  2891. }
  2892. }
  2893. }
  2894. /// Check that all the liveness sets used during the computation of liveness
  2895. /// obey basic SSA properties. This is useful for finding cases where we miss
  2896. /// a def.
  2897. static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
  2898. BasicBlock &BB) {
  2899. checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
  2900. checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
  2901. checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
  2902. }
  2903. #endif
  2904. static void computeLiveInValues(DominatorTree &DT, Function &F,
  2905. GCPtrLivenessData &Data) {
  2906. SmallSetVector<BasicBlock *, 32> Worklist;
  2907. // Seed the liveness for each individual block
  2908. for (BasicBlock &BB : F) {
  2909. Data.KillSet[&BB] = computeKillSet(&BB);
  2910. Data.LiveSet[&BB].clear();
  2911. computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
  2912. #ifndef NDEBUG
  2913. for (Value *Kill : Data.KillSet[&BB])
  2914. assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
  2915. #endif
  2916. Data.LiveOut[&BB] = SetVector<Value *>();
  2917. computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
  2918. Data.LiveIn[&BB] = Data.LiveSet[&BB];
  2919. Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
  2920. Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
  2921. if (!Data.LiveIn[&BB].empty())
  2922. Worklist.insert(pred_begin(&BB), pred_end(&BB));
  2923. }
  2924. // Propagate that liveness until stable
  2925. while (!Worklist.empty()) {
  2926. BasicBlock *BB = Worklist.pop_back_val();
  2927. // Compute our new liveout set, then exit early if it hasn't changed despite
  2928. // the contribution of our successor.
  2929. SetVector<Value *> LiveOut = Data.LiveOut[BB];
  2930. const auto OldLiveOutSize = LiveOut.size();
  2931. for (BasicBlock *Succ : successors(BB)) {
  2932. assert(Data.LiveIn.count(Succ));
  2933. LiveOut.set_union(Data.LiveIn[Succ]);
  2934. }
  2935. // assert OutLiveOut is a subset of LiveOut
  2936. if (OldLiveOutSize == LiveOut.size()) {
  2937. // If the sets are the same size, then we didn't actually add anything
  2938. // when unioning our successors LiveIn. Thus, the LiveIn of this block
  2939. // hasn't changed.
  2940. continue;
  2941. }
  2942. Data.LiveOut[BB] = LiveOut;
  2943. // Apply the effects of this basic block
  2944. SetVector<Value *> LiveTmp = LiveOut;
  2945. LiveTmp.set_union(Data.LiveSet[BB]);
  2946. LiveTmp.set_subtract(Data.KillSet[BB]);
  2947. assert(Data.LiveIn.count(BB));
  2948. const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
  2949. // assert: OldLiveIn is a subset of LiveTmp
  2950. if (OldLiveIn.size() != LiveTmp.size()) {
  2951. Data.LiveIn[BB] = LiveTmp;
  2952. Worklist.insert(pred_begin(BB), pred_end(BB));
  2953. }
  2954. } // while (!Worklist.empty())
  2955. #ifndef NDEBUG
  2956. // Verify our output against SSA properties. This helps catch any
  2957. // missing kills during the above iteration.
  2958. for (BasicBlock &BB : F)
  2959. checkBasicSSA(DT, Data, BB);
  2960. #endif
  2961. }
  2962. static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
  2963. StatepointLiveSetTy &Out) {
  2964. BasicBlock *BB = Inst->getParent();
  2965. // Note: The copy is intentional and required
  2966. assert(Data.LiveOut.count(BB));
  2967. SetVector<Value *> LiveOut = Data.LiveOut[BB];
  2968. // We want to handle the statepoint itself oddly. It's
  2969. // call result is not live (normal), nor are it's arguments
  2970. // (unless they're used again later). This adjustment is
  2971. // specifically what we need to relocate
  2972. computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
  2973. LiveOut);
  2974. LiveOut.remove(Inst);
  2975. Out.insert(LiveOut.begin(), LiveOut.end());
  2976. }
  2977. static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
  2978. CallBase *Call,
  2979. PartiallyConstructedSafepointRecord &Info,
  2980. PointerToBaseTy &PointerToBase) {
  2981. StatepointLiveSetTy Updated;
  2982. findLiveSetAtInst(Call, RevisedLivenessData, Updated);
  2983. // We may have base pointers which are now live that weren't before. We need
  2984. // to update the PointerToBase structure to reflect this.
  2985. for (auto *V : Updated)
  2986. PointerToBase.insert({ V, V });
  2987. Info.LiveSet = Updated;
  2988. }