RewriteStatepointsForGC.cpp 111 KB

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