1d16a9b1fSPhilip Reames //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2d16a9b1fSPhilip Reames //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d16a9b1fSPhilip Reames //
7d16a9b1fSPhilip Reames //===----------------------------------------------------------------------===//
8d16a9b1fSPhilip Reames //
9ae80045dSPhilip Reames // Rewrite call/invoke instructions so as to make potential relocations
10ae80045dSPhilip Reames // performed by the garbage collector explicit in the IR.
11d16a9b1fSPhilip Reames //
12d16a9b1fSPhilip Reames //===----------------------------------------------------------------------===//
13d16a9b1fSPhilip Reames
144b86d790SFedor Sergeev #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
154b86d790SFedor Sergeev
1675075efeSEugene Zelenko #include "llvm/ADT/ArrayRef.h"
1775075efeSEugene Zelenko #include "llvm/ADT/DenseMap.h"
186bda14b3SChandler Carruth #include "llvm/ADT/DenseSet.h"
196bda14b3SChandler Carruth #include "llvm/ADT/MapVector.h"
2075075efeSEugene Zelenko #include "llvm/ADT/None.h"
2175075efeSEugene Zelenko #include "llvm/ADT/Optional.h"
2275075efeSEugene Zelenko #include "llvm/ADT/STLExtras.h"
236bda14b3SChandler Carruth #include "llvm/ADT/SetVector.h"
2475075efeSEugene Zelenko #include "llvm/ADT/SmallSet.h"
2575075efeSEugene Zelenko #include "llvm/ADT/SmallVector.h"
266bda14b3SChandler Carruth #include "llvm/ADT/StringRef.h"
2775075efeSEugene Zelenko #include "llvm/ADT/iterator_range.h"
285f436fc5SRichard Trieu #include "llvm/Analysis/DomTreeUpdater.h"
292574d7cbSDaniel Neilson #include "llvm/Analysis/TargetLibraryInfo.h"
30e0317186SIgor Laevsky #include "llvm/Analysis/TargetTransformInfo.h"
3175075efeSEugene Zelenko #include "llvm/IR/Argument.h"
3275075efeSEugene Zelenko #include "llvm/IR/Attributes.h"
33d16a9b1fSPhilip Reames #include "llvm/IR/BasicBlock.h"
3475075efeSEugene Zelenko #include "llvm/IR/CallingConv.h"
3575075efeSEugene Zelenko #include "llvm/IR/Constant.h"
3675075efeSEugene Zelenko #include "llvm/IR/Constants.h"
3775075efeSEugene Zelenko #include "llvm/IR/DataLayout.h"
3875075efeSEugene Zelenko #include "llvm/IR/DerivedTypes.h"
39d16a9b1fSPhilip Reames #include "llvm/IR/Dominators.h"
40d16a9b1fSPhilip Reames #include "llvm/IR/Function.h"
41d16a9b1fSPhilip Reames #include "llvm/IR/IRBuilder.h"
42d16a9b1fSPhilip Reames #include "llvm/IR/InstIterator.h"
4375075efeSEugene Zelenko #include "llvm/IR/InstrTypes.h"
4475075efeSEugene Zelenko #include "llvm/IR/Instruction.h"
45d16a9b1fSPhilip Reames #include "llvm/IR/Instructions.h"
46d16a9b1fSPhilip Reames #include "llvm/IR/IntrinsicInst.h"
476bda14b3SChandler Carruth #include "llvm/IR/Intrinsics.h"
4875075efeSEugene Zelenko #include "llvm/IR/LLVMContext.h"
49353a19e1SSanjoy Das #include "llvm/IR/MDBuilder.h"
5075075efeSEugene Zelenko #include "llvm/IR/Metadata.h"
516bda14b3SChandler Carruth #include "llvm/IR/Module.h"
52d16a9b1fSPhilip Reames #include "llvm/IR/Statepoint.h"
5375075efeSEugene Zelenko #include "llvm/IR/Type.h"
5475075efeSEugene Zelenko #include "llvm/IR/User.h"
55d16a9b1fSPhilip Reames #include "llvm/IR/Value.h"
5675075efeSEugene Zelenko #include "llvm/IR/ValueHandle.h"
5705da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
586bda14b3SChandler Carruth #include "llvm/Pass.h"
5975075efeSEugene Zelenko #include "llvm/Support/Casting.h"
60d16a9b1fSPhilip Reames #include "llvm/Support/CommandLine.h"
6175075efeSEugene Zelenko #include "llvm/Support/Compiler.h"
626bda14b3SChandler Carruth #include "llvm/Support/Debug.h"
6375075efeSEugene Zelenko #include "llvm/Support/ErrorHandling.h"
6475075efeSEugene Zelenko #include "llvm/Support/raw_ostream.h"
65d16a9b1fSPhilip Reames #include "llvm/Transforms/Scalar.h"
66d16a9b1fSPhilip Reames #include "llvm/Transforms/Utils/BasicBlockUtils.h"
6721a8b605SChijun Sima #include "llvm/Transforms/Utils/Local.h"
68d16a9b1fSPhilip Reames #include "llvm/Transforms/Utils/PromoteMemToReg.h"
6975075efeSEugene Zelenko #include <algorithm>
7075075efeSEugene Zelenko #include <cassert>
7175075efeSEugene Zelenko #include <cstddef>
7275075efeSEugene Zelenko #include <cstdint>
7375075efeSEugene Zelenko #include <iterator>
7475075efeSEugene Zelenko #include <set>
7575075efeSEugene Zelenko #include <string>
7675075efeSEugene Zelenko #include <utility>
7775075efeSEugene Zelenko #include <vector>
78d16a9b1fSPhilip Reames
79d16a9b1fSPhilip Reames #define DEBUG_TYPE "rewrite-statepoints-for-gc"
80d16a9b1fSPhilip Reames
81d16a9b1fSPhilip Reames using namespace llvm;
82d16a9b1fSPhilip Reames
83d16a9b1fSPhilip Reames // Print the liveset found at the insert location
84d16a9b1fSPhilip Reames static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
85d16a9b1fSPhilip Reames cl::init(false));
86704e78b1SPhilip Reames static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
87704e78b1SPhilip Reames cl::init(false));
8875075efeSEugene Zelenko
89d16a9b1fSPhilip Reames // Print out the base pointers for debugging
90704e78b1SPhilip Reames static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
91704e78b1SPhilip Reames cl::init(false));
92d16a9b1fSPhilip Reames
93e0317186SIgor Laevsky // Cost threshold measuring when it is profitable to rematerialize value instead
94e0317186SIgor Laevsky // of relocating it
95e0317186SIgor Laevsky static cl::opt<unsigned>
96e0317186SIgor Laevsky RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
97e0317186SIgor Laevsky cl::init(6));
98e0317186SIgor Laevsky
990da99375SFilipe Cabecinhas #ifdef EXPENSIVE_CHECKS
100e73300b9SPhilip Reames static bool ClobberNonLive = true;
101e73300b9SPhilip Reames #else
102e73300b9SPhilip Reames static bool ClobberNonLive = false;
103e73300b9SPhilip Reames #endif
10475075efeSEugene Zelenko
105e73300b9SPhilip Reames static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
106e73300b9SPhilip Reames cl::location(ClobberNonLive),
107e73300b9SPhilip Reames cl::Hidden);
108e73300b9SPhilip Reames
10925ec1a3eSSanjoy Das static cl::opt<bool>
11025ec1a3eSSanjoy Das AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
11125ec1a3eSSanjoy Das cl::Hidden, cl::init(true));
11225ec1a3eSSanjoy Das
1134b027e8fSAnna Thomas /// The IR fed into RewriteStatepointsForGC may have had attributes and
1144b027e8fSAnna Thomas /// metadata implying dereferenceability that are no longer valid/correct after
115353a19e1SSanjoy Das /// RewriteStatepointsForGC has run. This is because semantically, after
116353a19e1SSanjoy Das /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
117729dafc1SAnna Thomas /// heap. stripNonValidData (conservatively) restores
1184b027e8fSAnna Thomas /// correctness by erasing all attributes in the module that externally imply
1194b027e8fSAnna Thomas /// dereferenceability. Similar reasoning also applies to the noalias
1204b027e8fSAnna Thomas /// attributes and metadata. gc.statepoint can touch the entire heap including
1214b027e8fSAnna Thomas /// noalias objects.
122729dafc1SAnna Thomas /// Apart from attributes and metadata, we also remove instructions that imply
123729dafc1SAnna Thomas /// constant physical memory: llvm.invariant.start.
1244b86d790SFedor Sergeev static void stripNonValidData(Module &M);
125353a19e1SSanjoy Das
1264b86d790SFedor Sergeev static bool shouldRewriteStatepointsIn(Function &F);
12775075efeSEugene Zelenko
run(Module & M,ModuleAnalysisManager & AM)1284b86d790SFedor Sergeev PreservedAnalyses RewriteStatepointsForGC::run(Module &M,
1294b86d790SFedor Sergeev ModuleAnalysisManager &AM) {
1304b86d790SFedor Sergeev bool Changed = false;
1314b86d790SFedor Sergeev auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1324b86d790SFedor Sergeev for (Function &F : M) {
1334b86d790SFedor Sergeev // Nothing to do for declarations.
1344b86d790SFedor Sergeev if (F.isDeclaration() || F.empty())
1354b86d790SFedor Sergeev continue;
1364b86d790SFedor Sergeev
1374b86d790SFedor Sergeev // Policy choice says not to rewrite - the most common reason is that we're
1384b86d790SFedor Sergeev // compiling code without a GCStrategy.
1394b86d790SFedor Sergeev if (!shouldRewriteStatepointsIn(F))
1404b86d790SFedor Sergeev continue;
1414b86d790SFedor Sergeev
1424b86d790SFedor Sergeev auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1434b86d790SFedor Sergeev auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
1444b86d790SFedor Sergeev auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1454b86d790SFedor Sergeev Changed |= runOnFunction(F, DT, TTI, TLI);
1464b86d790SFedor Sergeev }
1474b86d790SFedor Sergeev if (!Changed)
1484b86d790SFedor Sergeev return PreservedAnalyses::all();
1494b86d790SFedor Sergeev
1504b86d790SFedor Sergeev // stripNonValidData asserts that shouldRewriteStatepointsIn
1514b86d790SFedor Sergeev // returns true for at least one function in the module. Since at least
1524b86d790SFedor Sergeev // one function changed, we know that the precondition is satisfied.
1534b86d790SFedor Sergeev stripNonValidData(M);
1544b86d790SFedor Sergeev
1554b86d790SFedor Sergeev PreservedAnalyses PA;
1564b86d790SFedor Sergeev PA.preserve<TargetIRAnalysis>();
1574b86d790SFedor Sergeev PA.preserve<TargetLibraryAnalysis>();
1584b86d790SFedor Sergeev return PA;
1594b86d790SFedor Sergeev }
1604b86d790SFedor Sergeev
1614b86d790SFedor Sergeev namespace {
1624b86d790SFedor Sergeev
1634b86d790SFedor Sergeev class RewriteStatepointsForGCLegacyPass : public ModulePass {
1644b86d790SFedor Sergeev RewriteStatepointsForGC Impl;
1654b86d790SFedor Sergeev
1664b86d790SFedor Sergeev public:
1674b86d790SFedor Sergeev static char ID; // Pass identification, replacement for typeid
1684b86d790SFedor Sergeev
RewriteStatepointsForGCLegacyPass()1694b86d790SFedor Sergeev RewriteStatepointsForGCLegacyPass() : ModulePass(ID), Impl() {
1704b86d790SFedor Sergeev initializeRewriteStatepointsForGCLegacyPassPass(
1714b86d790SFedor Sergeev *PassRegistry::getPassRegistry());
1724b86d790SFedor Sergeev }
1734b86d790SFedor Sergeev
runOnModule(Module & M)1744b86d790SFedor Sergeev bool runOnModule(Module &M) override {
1754b86d790SFedor Sergeev bool Changed = false;
1764b86d790SFedor Sergeev for (Function &F : M) {
1774b86d790SFedor Sergeev // Nothing to do for declarations.
1784b86d790SFedor Sergeev if (F.isDeclaration() || F.empty())
1794b86d790SFedor Sergeev continue;
1804b86d790SFedor Sergeev
1814b86d790SFedor Sergeev // Policy choice says not to rewrite - the most common reason is that
1824b86d790SFedor Sergeev // we're compiling code without a GCStrategy.
1834b86d790SFedor Sergeev if (!shouldRewriteStatepointsIn(F))
1844b86d790SFedor Sergeev continue;
1854b86d790SFedor Sergeev
1864b86d790SFedor Sergeev TargetTransformInfo &TTI =
1874b86d790SFedor Sergeev getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1889c27b59cSTeresa Johnson const TargetLibraryInfo &TLI =
1899c27b59cSTeresa Johnson getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1904b86d790SFedor Sergeev auto &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
1914b86d790SFedor Sergeev
1924b86d790SFedor Sergeev Changed |= Impl.runOnFunction(F, DT, TTI, TLI);
1934b86d790SFedor Sergeev }
1944b86d790SFedor Sergeev
1954b86d790SFedor Sergeev if (!Changed)
1964b86d790SFedor Sergeev return false;
1974b86d790SFedor Sergeev
1984b86d790SFedor Sergeev // stripNonValidData asserts that shouldRewriteStatepointsIn
1994b86d790SFedor Sergeev // returns true for at least one function in the module. Since at least
2004b86d790SFedor Sergeev // one function changed, we know that the precondition is satisfied.
2014b86d790SFedor Sergeev stripNonValidData(M);
2024b86d790SFedor Sergeev return true;
2034b86d790SFedor Sergeev }
2044b86d790SFedor Sergeev
getAnalysisUsage(AnalysisUsage & AU) const2054b86d790SFedor Sergeev void getAnalysisUsage(AnalysisUsage &AU) const override {
2064b86d790SFedor Sergeev // We add and rewrite a bunch of instructions, but don't really do much
2074b86d790SFedor Sergeev // else. We could in theory preserve a lot more analyses here.
2084b86d790SFedor Sergeev AU.addRequired<DominatorTreeWrapperPass>();
2094b86d790SFedor Sergeev AU.addRequired<TargetTransformInfoWrapperPass>();
2104b86d790SFedor Sergeev AU.addRequired<TargetLibraryInfoWrapperPass>();
2114b86d790SFedor Sergeev }
212d16a9b1fSPhilip Reames };
21375075efeSEugene Zelenko
21475075efeSEugene Zelenko } // end anonymous namespace
215d16a9b1fSPhilip Reames
2164b86d790SFedor Sergeev char RewriteStatepointsForGCLegacyPass::ID = 0;
217d16a9b1fSPhilip Reames
createRewriteStatepointsForGCLegacyPass()2184b86d790SFedor Sergeev ModulePass *llvm::createRewriteStatepointsForGCLegacyPass() {
2194b86d790SFedor Sergeev return new RewriteStatepointsForGCLegacyPass();
220d16a9b1fSPhilip Reames }
221d16a9b1fSPhilip Reames
2224b86d790SFedor Sergeev INITIALIZE_PASS_BEGIN(RewriteStatepointsForGCLegacyPass,
2234b86d790SFedor Sergeev "rewrite-statepoints-for-gc",
224d16a9b1fSPhilip Reames "Make relocations explicit at statepoints", false, false)
225d16a9b1fSPhilip Reames INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2266f852eedSDavide Italiano INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2274b86d790SFedor Sergeev INITIALIZE_PASS_END(RewriteStatepointsForGCLegacyPass,
2284b86d790SFedor Sergeev "rewrite-statepoints-for-gc",
229d16a9b1fSPhilip Reames "Make relocations explicit at statepoints", false, false)
230d16a9b1fSPhilip Reames
231d16a9b1fSPhilip Reames namespace {
23275075efeSEugene Zelenko
233df1ef08cSPhilip Reames struct GCPtrLivenessData {
234df1ef08cSPhilip Reames /// Values defined in this block.
235fb1811d3SIgor Laevsky MapVector<BasicBlock *, SetVector<Value *>> KillSet;
23675075efeSEugene Zelenko
237df1ef08cSPhilip Reames /// Values used in this block (and thus live); does not included values
238df1ef08cSPhilip Reames /// killed within this block.
239fb1811d3SIgor Laevsky MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
240df1ef08cSPhilip Reames
241df1ef08cSPhilip Reames /// Values live into this basic block (i.e. used by any
242df1ef08cSPhilip Reames /// instruction in this basic block or ones reachable from here)
243fb1811d3SIgor Laevsky MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
244df1ef08cSPhilip Reames
245df1ef08cSPhilip Reames /// Values live out of this basic block (i.e. live into
246df1ef08cSPhilip Reames /// any successor block)
247fb1811d3SIgor Laevsky MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
248df1ef08cSPhilip Reames };
249df1ef08cSPhilip Reames
250d16a9b1fSPhilip Reames // The type of the internal cache used inside the findBasePointers family
251d16a9b1fSPhilip Reames // of functions. From the callers perspective, this is an opaque type and
252d16a9b1fSPhilip Reames // should not be inspected.
253d16a9b1fSPhilip Reames //
254d16a9b1fSPhilip Reames // In the actual implementation this caches two relations:
255d16a9b1fSPhilip Reames // - The base relation itself (i.e. this pointer is based on that one)
256d16a9b1fSPhilip Reames // - The base defining value relation (i.e. before base_phi insertion)
257d16a9b1fSPhilip Reames // Generally, after the execution of a full findBasePointer call, only the
258d16a9b1fSPhilip Reames // base relation will remain. Internally, we add a mixture of the two
259d16a9b1fSPhilip Reames // types, then update all the second type to the first type
26075075efeSEugene Zelenko using DefiningValueMapTy = MapVector<Value *, Value *>;
2611da42c9fSDmitry Makogon using IsKnownBaseMapTy = MapVector<Value *, bool>;
26228c5e1b7SSerguei Katkov using PointerToBaseTy = MapVector<Value *, Value *>;
26375075efeSEugene Zelenko using StatepointLiveSetTy = SetVector<Value *>;
26475075efeSEugene Zelenko using RematerializedValueMapTy =
26575075efeSEugene Zelenko MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
266d16a9b1fSPhilip Reames
267d16a9b1fSPhilip Reames struct PartiallyConstructedSafepointRecord {
268df005cbeSBenjamin Kramer /// The set of values known to be live across this safepoint
269b40bd1a9SSanjoy Das StatepointLiveSetTy LiveSet;
270d16a9b1fSPhilip Reames
2710a3240f4SPhilip Reames /// The *new* gc.statepoint instruction itself. This produces the token
2720a3240f4SPhilip Reames /// that normal path gc.relocates and the gc.result are tied to.
273a0d2fd4aSPhilip Reames GCStatepointInst *StatepointToken;
274d16a9b1fSPhilip Reames
275f2041324SPhilip Reames /// Instruction to which exceptional gc relocates are attached
276f2041324SPhilip Reames /// Makes it easier to iterate through them during relocationViaAlloca.
277f2041324SPhilip Reames Instruction *UnwindToken;
278e0317186SIgor Laevsky
279e0317186SIgor Laevsky /// Record live values we are rematerialized instead of relocating.
280b40bd1a9SSanjoy Das /// They are not included into 'LiveSet' field.
281e0317186SIgor Laevsky /// Maps rematerialized copy to it's original value.
282e0317186SIgor Laevsky RematerializedValueMapTy RematerializedValues;
283d16a9b1fSPhilip Reames };
28475075efeSEugene Zelenko
28566f1c6fcSSerguei Katkov struct RematerizlizationCandidateRecord {
28666f1c6fcSSerguei Katkov // Chain from derived pointer to base.
28766f1c6fcSSerguei Katkov SmallVector<Instruction *, 3> ChainToBase;
28866f1c6fcSSerguei Katkov // Original base.
28966f1c6fcSSerguei Katkov Value *RootOfChain;
29066f1c6fcSSerguei Katkov // Cost of chain.
29166f1c6fcSSerguei Katkov InstructionCost Cost;
29266f1c6fcSSerguei Katkov };
29366f1c6fcSSerguei Katkov using RematCandTy = MapVector<Value *, RematerizlizationCandidateRecord>;
29466f1c6fcSSerguei Katkov
29575075efeSEugene Zelenko } // end anonymous namespace
296d16a9b1fSPhilip Reames
GetDeoptBundleOperands(const CallBase * Call)2973160734aSChandler Carruth static ArrayRef<Use> GetDeoptBundleOperands(const CallBase *Call) {
298acc43d19SSanjoy Das Optional<OperandBundleUse> DeoptBundle =
2993160734aSChandler Carruth Call->getOperandBundle(LLVMContext::OB_deopt);
30025ec1a3eSSanjoy Das
301e0e687a6SKazu Hirata if (!DeoptBundle) {
30225ec1a3eSSanjoy Das assert(AllowStatepointWithNoDeoptInfo &&
30325ec1a3eSSanjoy Das "Found non-leaf call without deopt info!");
30425ec1a3eSSanjoy Das return None;
30525ec1a3eSSanjoy Das }
30625ec1a3eSSanjoy Das
3077a47ee51SKazu Hirata return DeoptBundle->Inputs;
30825ec1a3eSSanjoy Das }
30925ec1a3eSSanjoy Das
310df1ef08cSPhilip Reames /// Compute the live-in set for every basic block in the function
311df1ef08cSPhilip Reames static void computeLiveInValues(DominatorTree &DT, Function &F,
312df1ef08cSPhilip Reames GCPtrLivenessData &Data);
313df1ef08cSPhilip Reames
314df1ef08cSPhilip Reames /// Given results from the dataflow liveness computation, find the set of live
315df1ef08cSPhilip Reames /// Values at a particular instruction.
316df1ef08cSPhilip Reames static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
317df1ef08cSPhilip Reames StatepointLiveSetTy &out);
318df1ef08cSPhilip Reames
319d16a9b1fSPhilip Reames // TODO: Once we can get to the GCStrategy, this becomes
320ee8f0553SPhilip Reames // Optional<bool> isGCManagedPointer(const Type *Ty) const override {
321d16a9b1fSPhilip Reames
isGCPointerType(Type * T)322e3dcce97SCraig Topper static bool isGCPointerType(Type *T) {
323e3dcce97SCraig Topper if (auto *PT = dyn_cast<PointerType>(T))
324d16a9b1fSPhilip Reames // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
325d16a9b1fSPhilip Reames // GC managed heap. We know that a pointer into this heap needs to be
326d16a9b1fSPhilip Reames // updated and that no other pointer does.
32773c7f260SSanjoy Das return PT->getAddressSpace() == 1;
328d16a9b1fSPhilip Reames return false;
329d16a9b1fSPhilip Reames }
330d16a9b1fSPhilip Reames
3318531d8c4SPhilip Reames // Return true if this type is one which a) is a gc pointer or contains a GC
3328531d8c4SPhilip Reames // pointer and b) is of a type this code expects to encounter as a live value.
3338531d8c4SPhilip Reames // (The insertion code will assert that a type which matches (a) and not (b)
3348531d8c4SPhilip Reames // is not encountered.)
isHandledGCPointerType(Type * T)3358531d8c4SPhilip Reames static bool isHandledGCPointerType(Type *T) {
3368531d8c4SPhilip Reames // We fully support gc pointers
3378531d8c4SPhilip Reames if (isGCPointerType(T))
3388531d8c4SPhilip Reames return true;
3398531d8c4SPhilip Reames // We partially support vectors of gc pointers. The code will assert if it
3408531d8c4SPhilip Reames // can't handle something.
3418531d8c4SPhilip Reames if (auto VT = dyn_cast<VectorType>(T))
3428531d8c4SPhilip Reames if (isGCPointerType(VT->getElementType()))
3438531d8c4SPhilip Reames return true;
3448531d8c4SPhilip Reames return false;
3458531d8c4SPhilip Reames }
3468531d8c4SPhilip Reames
3478531d8c4SPhilip Reames #ifndef NDEBUG
3488531d8c4SPhilip Reames /// Returns true if this type contains a gc pointer whether we know how to
3498531d8c4SPhilip Reames /// handle that type or not.
containsGCPtrType(Type * Ty)3508531d8c4SPhilip Reames static bool containsGCPtrType(Type *Ty) {
3518531d8c4SPhilip Reames if (isGCPointerType(Ty))
3528531d8c4SPhilip Reames return true;
3538531d8c4SPhilip Reames if (VectorType *VT = dyn_cast<VectorType>(Ty))
3548531d8c4SPhilip Reames return isGCPointerType(VT->getScalarType());
3558531d8c4SPhilip Reames if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
3568531d8c4SPhilip Reames return containsGCPtrType(AT->getElementType());
3578531d8c4SPhilip Reames if (StructType *ST = dyn_cast<StructType>(Ty))
35862df5eedSJames Y Knight return llvm::any_of(ST->elements(), containsGCPtrType);
3598531d8c4SPhilip Reames return false;
3608531d8c4SPhilip Reames }
3618531d8c4SPhilip Reames
3628531d8c4SPhilip Reames // Returns true if this is a type which a) is a gc pointer or contains a GC
3638531d8c4SPhilip Reames // pointer and b) is of a type which the code doesn't expect (i.e. first class
3648531d8c4SPhilip Reames // aggregates). Used to trip assertions.
isUnhandledGCPointerType(Type * Ty)3658531d8c4SPhilip Reames static bool isUnhandledGCPointerType(Type *Ty) {
3668531d8c4SPhilip Reames return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
3678531d8c4SPhilip Reames }
3688531d8c4SPhilip Reames #endif
3698531d8c4SPhilip Reames
370ece70b80SPhilip Reames // Return the name of the value suffixed with the provided value, or if the
371ece70b80SPhilip Reames // value didn't have a name, the default value specified.
suffixed_name_or(Value * V,StringRef Suffix,StringRef DefaultName)372ece70b80SPhilip Reames static std::string suffixed_name_or(Value *V, StringRef Suffix,
373ece70b80SPhilip Reames StringRef DefaultName) {
374ece70b80SPhilip Reames return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
375ece70b80SPhilip Reames }
376ece70b80SPhilip Reames
377df1ef08cSPhilip Reames // Conservatively identifies any definitions which might be live at the
378df1ef08cSPhilip Reames // given instruction. The analysis is performed immediately before the
379df1ef08cSPhilip Reames // given instruction. Values defined by that instruction are not considered
380df1ef08cSPhilip Reames // live. Values used by that instruction are considered live.
analyzeParsePointLiveness(DominatorTree & DT,GCPtrLivenessData & OriginalLivenessData,CallBase * Call,PartiallyConstructedSafepointRecord & Result)3813160734aSChandler Carruth static void analyzeParsePointLiveness(
3823160734aSChandler Carruth DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallBase *Call,
3831e7eeb4bSSanjoy Das PartiallyConstructedSafepointRecord &Result) {
384b40bd1a9SSanjoy Das StatepointLiveSetTy LiveSet;
3853160734aSChandler Carruth findLiveSetAtInst(Call, OriginalLivenessData, LiveSet);
386d16a9b1fSPhilip Reames
387d16a9b1fSPhilip Reames if (PrintLiveSet) {
3881e7eeb4bSSanjoy Das dbgs() << "Live Variables:\n";
389fb1811d3SIgor Laevsky for (Value *V : LiveSet)
390dab35f31SPhilip Reames dbgs() << " " << V->getName() << " " << *V << "\n";
391d16a9b1fSPhilip Reames }
392d16a9b1fSPhilip Reames if (PrintLiveSetSize) {
393a58b62b4SCraig Topper dbgs() << "Safepoint For: " << Call->getCalledOperand()->getName() << "\n";
3941e7eeb4bSSanjoy Das dbgs() << "Number live values: " << LiveSet.size() << "\n";
395d16a9b1fSPhilip Reames }
3961e7eeb4bSSanjoy Das Result.LiveSet = LiveSet;
397d16a9b1fSPhilip Reames }
398d16a9b1fSPhilip Reames
3991da42c9fSDmitry Makogon /// Returns true if V is a known base.
4001da42c9fSDmitry Makogon static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases);
40175075efeSEugene Zelenko
4021da42c9fSDmitry Makogon /// Caches the IsKnownBase flag for a value and asserts that it wasn't present
4031da42c9fSDmitry Makogon /// in the cache before.
4041da42c9fSDmitry Makogon static void setKnownBase(Value *V, bool IsKnownBase,
4051da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases);
40675075efeSEugene Zelenko
4071da42c9fSDmitry Makogon static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
4081da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases);
409311f7106SPhilip Reames
4108fe7f13aSPhilip Reames /// Return a base defining value for the 'Index' element of the given vector
4118fe7f13aSPhilip Reames /// instruction 'I'. If Index is null, returns a BDV for the entire vector
4128fe7f13aSPhilip Reames /// 'I'. As an optimization, this method will try to determine when the
4138fe7f13aSPhilip Reames /// element is known to already be a base pointer. If this can be established,
4148fe7f13aSPhilip Reames /// the second value in the returned pair will be true. Note that either a
4158fe7f13aSPhilip Reames /// vector or a pointer typed value can be returned. For the former, the
4168fe7f13aSPhilip Reames /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
4178fe7f13aSPhilip Reames /// If the later, the return pointer is a BDV (or possibly a base) for the
4188fe7f13aSPhilip Reames /// particular element in 'I'.
findBaseDefiningValueOfVector(Value * I,DefiningValueMapTy & Cache,IsKnownBaseMapTy & KnownBases)4191da42c9fSDmitry Makogon static Value *findBaseDefiningValueOfVector(Value *I, DefiningValueMapTy &Cache,
4201da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
4218531d8c4SPhilip Reames // Each case parallels findBaseDefiningValue below, see that code for
4228531d8c4SPhilip Reames // detailed motivation.
4238531d8c4SPhilip Reames
4241da42c9fSDmitry Makogon auto Cached = Cache.find(I);
4251da42c9fSDmitry Makogon if (Cached != Cache.end())
4261da42c9fSDmitry Makogon return Cached->second;
4278531d8c4SPhilip Reames
4281da42c9fSDmitry Makogon if (isa<Argument>(I)) {
4291da42c9fSDmitry Makogon // An incoming argument to the function is a base pointer
4301da42c9fSDmitry Makogon Cache[I] = I;
4311da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */true, KnownBases);
4321da42c9fSDmitry Makogon return I;
4331da42c9fSDmitry Makogon }
4341da42c9fSDmitry Makogon
4351da42c9fSDmitry Makogon if (isa<Constant>(I)) {
436df9db45cSIgor Laevsky // Base of constant vector consists only of constant null pointers.
437df9db45cSIgor Laevsky // For reasoning see similar case inside 'findBaseDefiningValue' function.
4381da42c9fSDmitry Makogon auto *CAZ = ConstantAggregateZero::get(I->getType());
4391da42c9fSDmitry Makogon Cache[I] = CAZ;
4401da42c9fSDmitry Makogon setKnownBase(CAZ, /* IsKnownBase */true, KnownBases);
4411da42c9fSDmitry Makogon return CAZ;
4421da42c9fSDmitry Makogon }
4438531d8c4SPhilip Reames
4441da42c9fSDmitry Makogon if (isa<LoadInst>(I)) {
4451da42c9fSDmitry Makogon Cache[I] = I;
4461da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */true, KnownBases);
4471da42c9fSDmitry Makogon return I;
4481da42c9fSDmitry Makogon }
4498531d8c4SPhilip Reames
4501da42c9fSDmitry Makogon if (isa<InsertElementInst>(I)) {
4518fe7f13aSPhilip Reames // We don't know whether this vector contains entirely base pointers or
4528fe7f13aSPhilip Reames // not. To be conservatively correct, we treat it as a BDV and will
4538fe7f13aSPhilip Reames // duplicate code as needed to construct a parallel vector of bases.
4541da42c9fSDmitry Makogon Cache[I] = I;
4551da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */false, KnownBases);
4561da42c9fSDmitry Makogon return I;
4571da42c9fSDmitry Makogon }
4588531d8c4SPhilip Reames
4591da42c9fSDmitry Makogon if (isa<ShuffleVectorInst>(I)) {
4608fe7f13aSPhilip Reames // We don't know whether this vector contains entirely base pointers or
4618fe7f13aSPhilip Reames // not. To be conservatively correct, we treat it as a BDV and will
4628fe7f13aSPhilip Reames // duplicate code as needed to construct a parallel vector of bases.
4638fe7f13aSPhilip Reames // TODO: There a number of local optimizations which could be applied here
4648fe7f13aSPhilip Reames // for particular sufflevector patterns.
4651da42c9fSDmitry Makogon Cache[I] = I;
4661da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */false, KnownBases);
4671da42c9fSDmitry Makogon return I;
4681da42c9fSDmitry Makogon }
4698fe7f13aSPhilip Reames
470c4e4dcdfSSanjoy Das // The behavior of getelementptr instructions is the same for vector and
471c4e4dcdfSSanjoy Das // non-vector data types.
4721da42c9fSDmitry Makogon if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
4731da42c9fSDmitry Makogon auto *BDV =
4741da42c9fSDmitry Makogon findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
4751da42c9fSDmitry Makogon Cache[GEP] = BDV;
4761da42c9fSDmitry Makogon return BDV;
4771da42c9fSDmitry Makogon }
478c4e4dcdfSSanjoy Das
4795e1ccdf9SSerguei Katkov // The behavior of freeze instructions is the same for vector and
4805e1ccdf9SSerguei Katkov // non-vector data types.
4815e1ccdf9SSerguei Katkov if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
4825e1ccdf9SSerguei Katkov auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
4835e1ccdf9SSerguei Katkov Cache[Freeze] = BDV;
4845e1ccdf9SSerguei Katkov return BDV;
4855e1ccdf9SSerguei Katkov }
4865e1ccdf9SSerguei Katkov
487fa14ebd1SDaniel Neilson // If the pointer comes through a bitcast of a vector of pointers to
488fa14ebd1SDaniel Neilson // a vector of another type of pointer, then look through the bitcast
4891da42c9fSDmitry Makogon if (auto *BC = dyn_cast<BitCastInst>(I)) {
4901da42c9fSDmitry Makogon auto *BDV = findBaseDefiningValue(BC->getOperand(0), Cache, KnownBases);
4911da42c9fSDmitry Makogon Cache[BC] = BDV;
4921da42c9fSDmitry Makogon return BDV;
4931da42c9fSDmitry Makogon }
494fa14ebd1SDaniel Neilson
495594f443bSDaniel Neilson // We assume that functions in the source language only return base
496594f443bSDaniel Neilson // pointers. This should probably be generalized via attributes to support
497594f443bSDaniel Neilson // both source language and internal functions.
4981da42c9fSDmitry Makogon if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
4991da42c9fSDmitry Makogon Cache[I] = I;
5001da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */true, KnownBases);
5011da42c9fSDmitry Makogon return I;
5021da42c9fSDmitry Makogon }
503594f443bSDaniel Neilson
5048fe7f13aSPhilip Reames // A PHI or Select is a base defining value. The outer findBasePointer
5058fe7f13aSPhilip Reames // algorithm is responsible for constructing a base value for this BDV.
5068fe7f13aSPhilip Reames assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
5078fe7f13aSPhilip Reames "unknown vector instruction - no base found for vector element");
5081da42c9fSDmitry Makogon Cache[I] = I;
5091da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */false, KnownBases);
5101da42c9fSDmitry Makogon return I;
5118fe7f13aSPhilip Reames }
5128fe7f13aSPhilip Reames
513d16a9b1fSPhilip Reames /// Helper function for findBasePointer - Will return a value which either a)
5149ac4e38aSPhilip Reames /// defines the base pointer for the input, b) blocks the simple search
5159ac4e38aSPhilip Reames /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
5169ac4e38aSPhilip Reames /// from pointer to vector type or back.
findBaseDefiningValue(Value * I,DefiningValueMapTy & Cache,IsKnownBaseMapTy & KnownBases)5171da42c9fSDmitry Makogon static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
5181da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
5190593cfd3SManuel Jacob assert(I->getType()->isPtrOrPtrVectorTy() &&
5200593cfd3SManuel Jacob "Illegal to ask for the base pointer of a non-pointer type");
5211da42c9fSDmitry Makogon auto Cached = Cache.find(I);
5221da42c9fSDmitry Makogon if (Cached != Cache.end())
5231da42c9fSDmitry Makogon return Cached->second;
5240593cfd3SManuel Jacob
5258fe7f13aSPhilip Reames if (I->getType()->isVectorTy())
5261da42c9fSDmitry Makogon return findBaseDefiningValueOfVector(I, Cache, KnownBases);
5278fe7f13aSPhilip Reames
5281da42c9fSDmitry Makogon if (isa<Argument>(I)) {
529d16a9b1fSPhilip Reames // An incoming argument to the function is a base pointer
530d16a9b1fSPhilip Reames // We should have never reached here if this argument isn't an gc value
5311da42c9fSDmitry Makogon Cache[I] = I;
5321da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */true, KnownBases);
5331da42c9fSDmitry Makogon return I;
5341da42c9fSDmitry Makogon }
535d16a9b1fSPhilip Reames
536df9db45cSIgor Laevsky if (isa<Constant>(I)) {
53775cbfdcfSManuel Jacob // We assume that objects with a constant base (e.g. a global) can't move
53875cbfdcfSManuel Jacob // and don't need to be reported to the collector because they are always
539df9db45cSIgor Laevsky // live. Besides global references, all kinds of constants (e.g. undef,
540df9db45cSIgor Laevsky // constant expressions, null pointers) can be introduced by the inliner or
541df9db45cSIgor Laevsky // the optimizer, especially on dynamically dead paths.
542df9db45cSIgor Laevsky // Here we treat all of them as having single null base. By doing this we
543df9db45cSIgor Laevsky // trying to avoid problems reporting various conflicts in a form of
544df9db45cSIgor Laevsky // "phi (const1, const2)" or "phi (const, regular gc ptr)".
545df9db45cSIgor Laevsky // See constant.ll file for relevant test cases.
546df9db45cSIgor Laevsky
5471da42c9fSDmitry Makogon auto *CPN = ConstantPointerNull::get(cast<PointerType>(I->getType()));
5481da42c9fSDmitry Makogon Cache[I] = CPN;
5491da42c9fSDmitry Makogon setKnownBase(CPN, /* IsKnownBase */true, KnownBases);
5501da42c9fSDmitry Makogon return CPN;
551df9db45cSIgor Laevsky }
552d16a9b1fSPhilip Reames
553c880d5e5SPhilip Reames // inttoptrs in an integral address space are currently ill-defined. We
554c880d5e5SPhilip Reames // treat them as defining base pointers here for consistency with the
555c880d5e5SPhilip Reames // constant rule above and because we don't really have a better semantic
556c880d5e5SPhilip Reames // to give them. Note that the optimizer is always free to insert undefined
557c880d5e5SPhilip Reames // behavior on dynamically dead paths as well.
5581da42c9fSDmitry Makogon if (isa<IntToPtrInst>(I)) {
5591da42c9fSDmitry Makogon Cache[I] = I;
5601da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */true, KnownBases);
5611da42c9fSDmitry Makogon return I;
5621da42c9fSDmitry Makogon }
563c880d5e5SPhilip Reames
564d16a9b1fSPhilip Reames if (CastInst *CI = dyn_cast<CastInst>(I)) {
565aa66dfa0SPhilip Reames Value *Def = CI->stripPointerCasts();
5668050a497SManuel Jacob // If stripping pointer casts changes the address space there is an
5678050a497SManuel Jacob // addrspacecast in between.
5688050a497SManuel Jacob assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
5698050a497SManuel Jacob cast<PointerType>(CI->getType())->getAddressSpace() &&
5708050a497SManuel Jacob "unsupported addrspacecast");
57182ad7877SDavid Blaikie // If we find a cast instruction here, it means we've found a cast which is
57282ad7877SDavid Blaikie // not simply a pointer cast (i.e. an inttoptr). We don't know how to
57382ad7877SDavid Blaikie // handle int->ptr conversion.
574aa66dfa0SPhilip Reames assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
5751da42c9fSDmitry Makogon auto *BDV = findBaseDefiningValue(Def, Cache, KnownBases);
5761da42c9fSDmitry Makogon Cache[CI] = BDV;
5771da42c9fSDmitry Makogon return BDV;
578d16a9b1fSPhilip Reames }
579d16a9b1fSPhilip Reames
5801da42c9fSDmitry Makogon if (isa<LoadInst>(I)) {
581f5b8e476SPhilip Reames // The value loaded is an gc base itself
5821da42c9fSDmitry Makogon Cache[I] = I;
5831da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */true, KnownBases);
5841da42c9fSDmitry Makogon return I;
5851da42c9fSDmitry Makogon }
586f5b8e476SPhilip Reames
5871da42c9fSDmitry Makogon if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
588aa66dfa0SPhilip Reames // The base of this GEP is the base
5891da42c9fSDmitry Makogon auto *BDV =
5901da42c9fSDmitry Makogon findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
5911da42c9fSDmitry Makogon Cache[GEP] = BDV;
5921da42c9fSDmitry Makogon return BDV;
5931da42c9fSDmitry Makogon }
594d16a9b1fSPhilip Reames
5951da42c9fSDmitry Makogon if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
5961da42c9fSDmitry Makogon auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
5971da42c9fSDmitry Makogon Cache[Freeze] = BDV;
5981da42c9fSDmitry Makogon return BDV;
5991da42c9fSDmitry Makogon }
6005a08e817SMax Kazantsev
601d16a9b1fSPhilip Reames if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
602d16a9b1fSPhilip Reames switch (II->getIntrinsicID()) {
603d16a9b1fSPhilip Reames default:
604d16a9b1fSPhilip Reames // fall through to general call handling
605d16a9b1fSPhilip Reames break;
606d16a9b1fSPhilip Reames case Intrinsic::experimental_gc_statepoint:
6074e4f60deSManuel Jacob llvm_unreachable("statepoints don't produce pointers");
60875075efeSEugene Zelenko case Intrinsic::experimental_gc_relocate:
609d16a9b1fSPhilip Reames // Rerunning safepoint insertion after safepoints are already
610d16a9b1fSPhilip Reames // inserted is not supported. It could probably be made to work,
611d16a9b1fSPhilip Reames // but why are you doing this? There's no good reason.
612d16a9b1fSPhilip Reames llvm_unreachable("repeat safepoint insertion is not supported");
613d16a9b1fSPhilip Reames case Intrinsic::gcroot:
614d16a9b1fSPhilip Reames // Currently, this mechanism hasn't been extended to work with gcroot.
615d16a9b1fSPhilip Reames // There's no reason it couldn't be, but I haven't thought about the
616d16a9b1fSPhilip Reames // implications much.
617d16a9b1fSPhilip Reames llvm_unreachable(
618d16a9b1fSPhilip Reames "interaction with the gcroot mechanism is not supported");
6194d26f41fSYevgeny Rouban case Intrinsic::experimental_gc_get_pointer_base:
6201da42c9fSDmitry Makogon auto *BDV = findBaseDefiningValue(II->getOperand(0), Cache, KnownBases);
6211da42c9fSDmitry Makogon Cache[II] = BDV;
6221da42c9fSDmitry Makogon return BDV;
623d16a9b1fSPhilip Reames }
624d16a9b1fSPhilip Reames }
625d16a9b1fSPhilip Reames // We assume that functions in the source language only return base
626d16a9b1fSPhilip Reames // pointers. This should probably be generalized via attributes to support
627d16a9b1fSPhilip Reames // both source language and internal functions.
6281da42c9fSDmitry Makogon if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
6291da42c9fSDmitry Makogon Cache[I] = I;
6301da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */true, KnownBases);
6311da42c9fSDmitry Makogon return I;
6321da42c9fSDmitry Makogon }
633d16a9b1fSPhilip Reames
634488c0576SAnna Thomas // TODO: I have absolutely no idea how to implement this part yet. It's not
635df005cbeSBenjamin Kramer // necessarily hard, I just haven't really looked at it yet.
636d16a9b1fSPhilip Reames assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
637d16a9b1fSPhilip Reames
6381da42c9fSDmitry Makogon if (isa<AtomicCmpXchgInst>(I)) {
639d16a9b1fSPhilip Reames // A CAS is effectively a atomic store and load combined under a
640d16a9b1fSPhilip Reames // predicate. From the perspective of base pointers, we just treat it
641aa66dfa0SPhilip Reames // like a load.
6421da42c9fSDmitry Makogon Cache[I] = I;
6431da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */true, KnownBases);
6441da42c9fSDmitry Makogon return I;
6451da42c9fSDmitry Makogon }
646aa66dfa0SPhilip Reames
647aa66dfa0SPhilip Reames assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
648aa66dfa0SPhilip Reames "binary ops which don't apply to pointers");
649d16a9b1fSPhilip Reames
650d16a9b1fSPhilip Reames // The aggregate ops. Aggregates can either be in the heap or on the
651d16a9b1fSPhilip Reames // stack, but in either case, this is simply a field load. As a result,
652d16a9b1fSPhilip Reames // this is a defining definition of the base just like a load is.
6531da42c9fSDmitry Makogon if (isa<ExtractValueInst>(I)) {
6541da42c9fSDmitry Makogon Cache[I] = I;
6551da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */true, KnownBases);
6561da42c9fSDmitry Makogon return I;
6571da42c9fSDmitry Makogon }
658d16a9b1fSPhilip Reames
659d16a9b1fSPhilip Reames // We should never see an insert vector since that would require we be
660d16a9b1fSPhilip Reames // tracing back a struct value not a pointer value.
661d16a9b1fSPhilip Reames assert(!isa<InsertValueInst>(I) &&
662d16a9b1fSPhilip Reames "Base pointer for a struct is meaningless");
663d16a9b1fSPhilip Reames
6644d26f41fSYevgeny Rouban // This value might have been generated by findBasePointer() called when
6654d26f41fSYevgeny Rouban // substituting gc.get.pointer.base() intrinsic.
6664d26f41fSYevgeny Rouban bool IsKnownBase =
6674d26f41fSYevgeny Rouban isa<Instruction>(I) && cast<Instruction>(I)->getMetadata("is_base_value");
6681da42c9fSDmitry Makogon setKnownBase(I, /* IsKnownBase */IsKnownBase, KnownBases);
6691da42c9fSDmitry Makogon Cache[I] = I;
6704d26f41fSYevgeny Rouban
6719ac4e38aSPhilip Reames // An extractelement produces a base result exactly when it's input does.
6729ac4e38aSPhilip Reames // We may need to insert a parallel instruction to extract the appropriate
6739ac4e38aSPhilip Reames // element out of the base vector corresponding to the input. Given this,
6749ac4e38aSPhilip Reames // it's analogous to the phi and select case even though it's not a merge.
6756628713fSPhilip Reames if (isa<ExtractElementInst>(I))
6766628713fSPhilip Reames // Note: There a lot of obvious peephole cases here. This are deliberately
6776628713fSPhilip Reames // handled after the main base pointer inference algorithm to make writing
6786628713fSPhilip Reames // test cases to exercise that code easier.
6791da42c9fSDmitry Makogon return I;
6809ac4e38aSPhilip Reames
681d16a9b1fSPhilip Reames // The last two cases here don't return a base pointer. Instead, they
682df005cbeSBenjamin Kramer // return a value which dynamically selects from among several base
683d16a9b1fSPhilip Reames // derived pointers (each with it's own base potentially). It's the job of
684d16a9b1fSPhilip Reames // the caller to resolve these.
685aa66dfa0SPhilip Reames assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
686e6a7afaeSMax Kazantsev "missing instruction case in findBaseDefiningValue");
6871da42c9fSDmitry Makogon return I;
688d16a9b1fSPhilip Reames }
689d16a9b1fSPhilip Reames
690d16a9b1fSPhilip Reames /// Returns the base defining value for this value.
findBaseDefiningValueCached(Value * I,DefiningValueMapTy & Cache,IsKnownBaseMapTy & KnownBases)6911da42c9fSDmitry Makogon static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache,
6921da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
6931da42c9fSDmitry Makogon if (Cache.find(I) == Cache.end()) {
6941da42c9fSDmitry Makogon auto *BDV = findBaseDefiningValue(I, Cache, KnownBases);
6951da42c9fSDmitry Makogon Cache[I] = BDV;
696d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
6971da42c9fSDmitry Makogon << Cache[I]->getName() << ", is known base = "
6981da42c9fSDmitry Makogon << KnownBases[I] << "\n");
699d16a9b1fSPhilip Reames }
70018d0feb7SPhilip Reames assert(Cache[I] != nullptr);
7011da42c9fSDmitry Makogon assert(KnownBases.find(Cache[I]) != KnownBases.end() &&
7021da42c9fSDmitry Makogon "Cached value must be present in known bases map");
7031da42c9fSDmitry Makogon return Cache[I];
704d16a9b1fSPhilip Reames }
705d16a9b1fSPhilip Reames
706d16a9b1fSPhilip Reames /// Return a base pointer for this value if known. Otherwise, return it's
707d16a9b1fSPhilip Reames /// base defining value.
findBaseOrBDV(Value * I,DefiningValueMapTy & Cache,IsKnownBaseMapTy & KnownBases)7081da42c9fSDmitry Makogon static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache,
7091da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
7101da42c9fSDmitry Makogon Value *Def = findBaseDefiningValueCached(I, Cache, KnownBases);
71118d0feb7SPhilip Reames auto Found = Cache.find(Def);
71218d0feb7SPhilip Reames if (Found != Cache.end()) {
713d16a9b1fSPhilip Reames // Either a base-of relation, or a self reference. Caller must check.
7146f66545aSBenjamin Kramer return Found->second;
715d16a9b1fSPhilip Reames }
716d16a9b1fSPhilip Reames // Only a BDV available
71718d0feb7SPhilip Reames return Def;
718d16a9b1fSPhilip Reames }
719d16a9b1fSPhilip Reames
72060e5fd00SFangrui Song #ifndef NDEBUG
721eb282be9SAnna Thomas /// This value is a base pointer that is not generated by RS4GC, i.e. it already
722eb282be9SAnna Thomas /// exists in the code.
isOriginalBaseResult(Value * V)723eb282be9SAnna Thomas static bool isOriginalBaseResult(Value *V) {
724eb282be9SAnna Thomas // no recursion possible
725eb282be9SAnna Thomas return !isa<PHINode>(V) && !isa<SelectInst>(V) &&
726eb282be9SAnna Thomas !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
727eb282be9SAnna Thomas !isa<ShuffleVectorInst>(V);
728eb282be9SAnna Thomas }
72960e5fd00SFangrui Song #endif
730eb282be9SAnna Thomas
isKnownBase(Value * V,const IsKnownBaseMapTy & KnownBases)7311da42c9fSDmitry Makogon static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases) {
7321da42c9fSDmitry Makogon auto It = KnownBases.find(V);
7331da42c9fSDmitry Makogon assert(It != KnownBases.end() && "Value not present in the map");
7341da42c9fSDmitry Makogon return It->second;
735d16a9b1fSPhilip Reames }
736d16a9b1fSPhilip Reames
setKnownBase(Value * V,bool IsKnownBase,IsKnownBaseMapTy & KnownBases)7371da42c9fSDmitry Makogon static void setKnownBase(Value *V, bool IsKnownBase,
7381da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
7391da42c9fSDmitry Makogon #ifndef NDEBUG
7401da42c9fSDmitry Makogon auto It = KnownBases.find(V);
7411da42c9fSDmitry Makogon if (It != KnownBases.end())
7421da42c9fSDmitry Makogon assert(It->second == IsKnownBase && "Changing already present value");
7431da42c9fSDmitry Makogon #endif
7441da42c9fSDmitry Makogon KnownBases[V] = IsKnownBase;
745d16a9b1fSPhilip Reames }
746d16a9b1fSPhilip Reames
747eb282be9SAnna Thomas // Returns true if First and Second values are both scalar or both vector.
areBothVectorOrScalar(Value * First,Value * Second)748eb282be9SAnna Thomas static bool areBothVectorOrScalar(Value *First, Value *Second) {
749eb282be9SAnna Thomas return isa<VectorType>(First->getType()) ==
750eb282be9SAnna Thomas isa<VectorType>(Second->getType());
751eb282be9SAnna Thomas }
752eb282be9SAnna Thomas
753d16a9b1fSPhilip Reames namespace {
75475075efeSEugene Zelenko
7559b141ed4SPhilip Reames /// Models the state of a single base defining value in the findBasePointer
7569b141ed4SPhilip Reames /// algorithm for determining where a new instruction is needed to propagate
7579b141ed4SPhilip Reames /// the base of this BDV.
7589b141ed4SPhilip Reames class BDVState {
759d16a9b1fSPhilip Reames public:
7608fe59ba5SPhilip Reames enum StatusTy {
7616334952fSPhilip Reames // Starting state of lattice
7626334952fSPhilip Reames Unknown,
7638fe59ba5SPhilip Reames // Some specific base value -- does *not* mean that instruction
7648fe59ba5SPhilip Reames // propagates the base of the object
7658fe59ba5SPhilip Reames // ex: gep %arg, 16 -> %arg is the base value
7666334952fSPhilip Reames Base,
7676334952fSPhilip Reames // Need to insert a node to represent a merge.
7686334952fSPhilip Reames Conflict
7696334952fSPhilip Reames };
770d16a9b1fSPhilip Reames
BDVState()7718fe59ba5SPhilip Reames BDVState() {
7728fe59ba5SPhilip Reames llvm_unreachable("missing state in map");
7738fe59ba5SPhilip Reames }
7748fe59ba5SPhilip Reames
BDVState(Value * OriginalValue)7758fe59ba5SPhilip Reames explicit BDVState(Value *OriginalValue)
7768fe59ba5SPhilip Reames : OriginalValue(OriginalValue) {}
BDVState(Value * OriginalValue,StatusTy Status,Value * BaseValue=nullptr)7778fe59ba5SPhilip Reames explicit BDVState(Value *OriginalValue, StatusTy Status, Value *BaseValue = nullptr)
7788fe59ba5SPhilip Reames : OriginalValue(OriginalValue), Status(Status), BaseValue(BaseValue) {
7797dda0edbSSanjoy Das assert(Status != Base || BaseValue);
7807dda0edbSSanjoy Das }
7817dda0edbSSanjoy Das
getStatus() const7828fe59ba5SPhilip Reames StatusTy getStatus() const { return Status; }
getOriginalValue() const7838fe59ba5SPhilip Reames Value *getOriginalValue() const { return OriginalValue; }
getBaseValue() const7847dda0edbSSanjoy Das Value *getBaseValue() const { return BaseValue; }
785d16a9b1fSPhilip Reames
isBase() const786d16a9b1fSPhilip Reames bool isBase() const { return getStatus() == Base; }
isUnknown() const787d16a9b1fSPhilip Reames bool isUnknown() const { return getStatus() == Unknown; }
isConflict() const788d16a9b1fSPhilip Reames bool isConflict() const { return getStatus() == Conflict; }
789d16a9b1fSPhilip Reames
790d2e15a83SSerguei Katkov // Values of type BDVState form a lattice, and this function implements the
791d2e15a83SSerguei Katkov // meet
792d2e15a83SSerguei Katkov // operation.
meet(const BDVState & Other)793d2e15a83SSerguei Katkov void meet(const BDVState &Other) {
794d2e15a83SSerguei Katkov auto markConflict = [&]() {
795d2e15a83SSerguei Katkov Status = BDVState::Conflict;
796d2e15a83SSerguei Katkov BaseValue = nullptr;
797d2e15a83SSerguei Katkov };
798d2e15a83SSerguei Katkov // Conflict is a final state.
799d2e15a83SSerguei Katkov if (isConflict())
800d2e15a83SSerguei Katkov return;
801d2e15a83SSerguei Katkov // if we are not known - just take other state.
802d2e15a83SSerguei Katkov if (isUnknown()) {
803d2e15a83SSerguei Katkov Status = Other.getStatus();
804d2e15a83SSerguei Katkov BaseValue = Other.getBaseValue();
805d2e15a83SSerguei Katkov return;
806d2e15a83SSerguei Katkov }
807d2e15a83SSerguei Katkov // We are base.
808d2e15a83SSerguei Katkov assert(isBase() && "Unknown state");
809d2e15a83SSerguei Katkov // If other is unknown - just keep our state.
810d2e15a83SSerguei Katkov if (Other.isUnknown())
811d2e15a83SSerguei Katkov return;
812d2e15a83SSerguei Katkov // If other is conflict - it is a final state.
813d2e15a83SSerguei Katkov if (Other.isConflict())
814d2e15a83SSerguei Katkov return markConflict();
815d2e15a83SSerguei Katkov // Other is base as well.
816d2e15a83SSerguei Katkov assert(Other.isBase() && "Unknown state");
817d2e15a83SSerguei Katkov // If bases are different - Conflict.
818d2e15a83SSerguei Katkov if (getBaseValue() != Other.getBaseValue())
819d2e15a83SSerguei Katkov return markConflict();
820d2e15a83SSerguei Katkov // We are identical, do nothing.
821d2e15a83SSerguei Katkov }
822d2e15a83SSerguei Katkov
operator ==(const BDVState & Other) const8237dda0edbSSanjoy Das bool operator==(const BDVState &Other) const {
824943b3048SDávid Bolvanský return OriginalValue == Other.OriginalValue && BaseValue == Other.BaseValue &&
8258fe59ba5SPhilip Reames Status == Other.Status;
826d16a9b1fSPhilip Reames }
827d16a9b1fSPhilip Reames
operator !=(const BDVState & other) const8289b141ed4SPhilip Reames bool operator!=(const BDVState &other) const { return !(*this == other); }
829d16a9b1fSPhilip Reames
8302a892a63SPhilip Reames LLVM_DUMP_METHOD
dump() const8317dda0edbSSanjoy Das void dump() const {
8327dda0edbSSanjoy Das print(dbgs());
8337dda0edbSSanjoy Das dbgs() << '\n';
8347dda0edbSSanjoy Das }
8352a892a63SPhilip Reames
print(raw_ostream & OS) const8362a892a63SPhilip Reames void print(raw_ostream &OS) const {
8377dda0edbSSanjoy Das switch (getStatus()) {
838dab35f31SPhilip Reames case Unknown:
839dab35f31SPhilip Reames OS << "U";
840dab35f31SPhilip Reames break;
841dab35f31SPhilip Reames case Base:
842dab35f31SPhilip Reames OS << "B";
843dab35f31SPhilip Reames break;
844dab35f31SPhilip Reames case Conflict:
845dab35f31SPhilip Reames OS << "C";
846dab35f31SPhilip Reames break;
84775075efeSEugene Zelenko }
8488fe59ba5SPhilip Reames OS << " (base " << getBaseValue() << " - "
8498fe59ba5SPhilip Reames << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << ")"
8508fe59ba5SPhilip Reames << " for " << OriginalValue->getName() << ":";
851d16a9b1fSPhilip Reames }
852d16a9b1fSPhilip Reames
853d16a9b1fSPhilip Reames private:
8548fe59ba5SPhilip Reames AssertingVH<Value> OriginalValue; // instruction this state corresponds to
8558fe59ba5SPhilip Reames StatusTy Status = Unknown;
8566334952fSPhilip Reames AssertingVH<Value> BaseValue = nullptr; // Non-null only if Status == Base.
857d16a9b1fSPhilip Reames };
85875075efeSEugene Zelenko
85975075efeSEugene Zelenko } // end anonymous namespace
860d16a9b1fSPhilip Reames
8616906e928SPhilip Reames #ifndef NDEBUG
operator <<(raw_ostream & OS,const BDVState & State)862b3967cd0SPhilip Reames static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
8632a892a63SPhilip Reames State.print(OS);
8642a892a63SPhilip Reames return OS;
8652a892a63SPhilip Reames }
8666906e928SPhilip Reames #endif
8672a892a63SPhilip Reames
86890547f1dSSanjoy Das /// For a given value or instruction, figure out what base ptr its derived from.
86990547f1dSSanjoy Das /// For gc objects, this is simply itself. On success, returns a value which is
87090547f1dSSanjoy Das /// the base pointer. (This is reliable and can be used for relocation.) On
87190547f1dSSanjoy Das /// failure, returns nullptr.
findBasePointer(Value * I,DefiningValueMapTy & Cache,IsKnownBaseMapTy & KnownBases)8721da42c9fSDmitry Makogon static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache,
8731da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
8741da42c9fSDmitry Makogon Value *Def = findBaseOrBDV(I, Cache, KnownBases);
875d16a9b1fSPhilip Reames
8761da42c9fSDmitry Makogon if (isKnownBase(Def, KnownBases) && areBothVectorOrScalar(Def, I))
87790547f1dSSanjoy Das return Def;
878d16a9b1fSPhilip Reames
879d16a9b1fSPhilip Reames // Here's the rough algorithm:
880d16a9b1fSPhilip Reames // - For every SSA value, construct a mapping to either an actual base
881d16a9b1fSPhilip Reames // pointer or a PHI which obscures the base pointer.
882d16a9b1fSPhilip Reames // - Construct a mapping from PHI to unknown TOP state. Use an
883d16a9b1fSPhilip Reames // optimistic algorithm to propagate base pointer information. Lattice
884d16a9b1fSPhilip Reames // looks like:
885d16a9b1fSPhilip Reames // UNKNOWN
886d16a9b1fSPhilip Reames // b1 b2 b3 b4
887d16a9b1fSPhilip Reames // CONFLICT
888d16a9b1fSPhilip Reames // When algorithm terminates, all PHIs will either have a single concrete
889d16a9b1fSPhilip Reames // base or be in a conflict state.
890d16a9b1fSPhilip Reames // - For every conflict, insert a dummy PHI node without arguments. Add
891d16a9b1fSPhilip Reames // these to the base[Instruction] = BasePtr mapping. For every
892d16a9b1fSPhilip Reames // non-conflict, add the actual base.
893d16a9b1fSPhilip Reames // - For every conflict, add arguments for the base[a] of each input
894d16a9b1fSPhilip Reames // arguments.
895d16a9b1fSPhilip Reames //
896d16a9b1fSPhilip Reames // Note: A simpler form of this would be to add the conflict form of all
897d16a9b1fSPhilip Reames // PHIs without running the optimistic algorithm. This would be
898df005cbeSBenjamin Kramer // analogous to pessimistic data flow and would likely lead to an
899d16a9b1fSPhilip Reames // overall worse solution.
900d16a9b1fSPhilip Reames
90129e9ae78SPhilip Reames #ifndef NDEBUG
90288958b2dSPhilip Reames auto isExpectedBDVType = [](Value *BDV) {
9036628713fSPhilip Reames return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
904479cbb94SAnna Thomas isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
905479cbb94SAnna Thomas isa<ShuffleVectorInst>(BDV);
90688958b2dSPhilip Reames };
90729e9ae78SPhilip Reames #endif
90888958b2dSPhilip Reames
90988958b2dSPhilip Reames // Once populated, will contain a mapping from each potentially non-base BDV
91088958b2dSPhilip Reames // to a lattice value (described above) which corresponds to that BDV.
91115d5563cSPhilip Reames // We use the order of insertion (DFS over the def/use graph) to provide a
91215d5563cSPhilip Reames // stable deterministic ordering for visiting DenseMaps (which are unordered)
91315d5563cSPhilip Reames // below. This is important for deterministic compilation.
91434d7a749SPhilip Reames MapVector<Value *, BDVState> States;
91515d5563cSPhilip Reames
9169fb6782cSFangrui Song #ifndef NDEBUG
9178fe59ba5SPhilip Reames auto VerifyStates = [&]() {
9188fe59ba5SPhilip Reames for (auto &Entry : States) {
9198fe59ba5SPhilip Reames assert(Entry.first == Entry.second.getOriginalValue());
9208fe59ba5SPhilip Reames }
9218fe59ba5SPhilip Reames };
9229fb6782cSFangrui Song #endif
9238fe59ba5SPhilip Reames
924cf1899e0SPhilip Reames auto visitBDVOperands = [](Value *BDV, std::function<void (Value*)> F) {
925cf1899e0SPhilip Reames if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
926cf1899e0SPhilip Reames for (Value *InVal : PN->incoming_values())
927cf1899e0SPhilip Reames F(InVal);
928cf1899e0SPhilip Reames } else if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
929cf1899e0SPhilip Reames F(SI->getTrueValue());
930cf1899e0SPhilip Reames F(SI->getFalseValue());
931cf1899e0SPhilip Reames } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
932cf1899e0SPhilip Reames F(EE->getVectorOperand());
933cf1899e0SPhilip Reames } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)) {
934cf1899e0SPhilip Reames F(IE->getOperand(0));
935cf1899e0SPhilip Reames F(IE->getOperand(1));
936cf1899e0SPhilip Reames } else if (auto *SV = dyn_cast<ShuffleVectorInst>(BDV)) {
937ef884e15SPhilip Reames // For a canonical broadcast, ignore the undef argument
938ef884e15SPhilip Reames // (without this, we insert a parallel base shuffle for every broadcast)
939cf1899e0SPhilip Reames F(SV->getOperand(0));
940ef884e15SPhilip Reames if (!SV->isZeroEltSplat())
941cf1899e0SPhilip Reames F(SV->getOperand(1));
942cf1899e0SPhilip Reames } else {
943cf1899e0SPhilip Reames llvm_unreachable("unexpected BDV type");
944cf1899e0SPhilip Reames }
945cf1899e0SPhilip Reames };
946cf1899e0SPhilip Reames
947cf1899e0SPhilip Reames
94815d5563cSPhilip Reames // Recursively fill in all base defining values reachable from the initial
94915d5563cSPhilip Reames // one for which we don't already know a definite base value for
95088958b2dSPhilip Reames /* scope */ {
95188958b2dSPhilip Reames SmallVector<Value*, 16> Worklist;
95290547f1dSSanjoy Das Worklist.push_back(Def);
9538fe59ba5SPhilip Reames States.insert({Def, BDVState(Def)});
95488958b2dSPhilip Reames while (!Worklist.empty()) {
95588958b2dSPhilip Reames Value *Current = Worklist.pop_back_val();
956eb282be9SAnna Thomas assert(!isOriginalBaseResult(Current) && "why did it get added?");
95788958b2dSPhilip Reames
95888958b2dSPhilip Reames auto visitIncomingValue = [&](Value *InVal) {
9591da42c9fSDmitry Makogon Value *Base = findBaseOrBDV(InVal, Cache, KnownBases);
9601da42c9fSDmitry Makogon if (isKnownBase(Base, KnownBases) && areBothVectorOrScalar(Base, InVal))
96188958b2dSPhilip Reames // Known bases won't need new instructions introduced and can be
962eb282be9SAnna Thomas // ignored safely. However, this can only be done when InVal and Base
963eb282be9SAnna Thomas // are both scalar or both vector. Otherwise, we need to find a
964eb282be9SAnna Thomas // correct BDV for InVal, by creating an entry in the lattice
965eb282be9SAnna Thomas // (States).
96688958b2dSPhilip Reames return;
96788958b2dSPhilip Reames assert(isExpectedBDVType(Base) && "the only non-base values "
96888958b2dSPhilip Reames "we see should be base defining values");
9698fe59ba5SPhilip Reames if (States.insert(std::make_pair(Base, BDVState(Base))).second)
97088958b2dSPhilip Reames Worklist.push_back(Base);
97188958b2dSPhilip Reames };
972cf1899e0SPhilip Reames
973cf1899e0SPhilip Reames visitBDVOperands(Current, visitIncomingValue);
974d16a9b1fSPhilip Reames }
975d16a9b1fSPhilip Reames }
976d16a9b1fSPhilip Reames
977dab35f31SPhilip Reames #ifndef NDEBUG
9788fe59ba5SPhilip Reames VerifyStates();
979d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "States after initialization:\n");
980f5d23d36SSimon Pilgrim for (const auto &Pair : States) {
981d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
9829d08642cSSanjoy Das }
983dab35f31SPhilip Reames #endif
984d16a9b1fSPhilip Reames
9855cabf472SPhilip Reames // Iterate forward through the value graph pruning any node from the state
9865cabf472SPhilip Reames // list where all of the inputs are base pointers. The purpose of this is to
9875cabf472SPhilip Reames // reuse existing values when the derived pointer we were asked to materialize
9885cabf472SPhilip Reames // a base pointer for happens to be a base pointer itself. (Or a sub-graph
9895cabf472SPhilip Reames // feeding it does.)
9905cabf472SPhilip Reames SmallVector<Value *> ToRemove;
9915cabf472SPhilip Reames do {
9925cabf472SPhilip Reames ToRemove.clear();
9935cabf472SPhilip Reames for (auto Pair : States) {
9945cabf472SPhilip Reames Value *BDV = Pair.first;
9955cabf472SPhilip Reames auto canPruneInput = [&](Value *V) {
996d03d2d8aSDmitry Makogon // If the input of the BDV is the BDV itself we can prune it. This is
997d03d2d8aSDmitry Makogon // only possible if the BDV is a PHI node.
998d03d2d8aSDmitry Makogon if (V->stripPointerCasts() == BDV)
999d03d2d8aSDmitry Makogon return true;
10001da42c9fSDmitry Makogon Value *VBDV = findBaseOrBDV(V, Cache, KnownBases);
1001d03d2d8aSDmitry Makogon if (V->stripPointerCasts() != VBDV)
10025cabf472SPhilip Reames return false;
10035cabf472SPhilip Reames // The assumption is that anything not in the state list is
10045cabf472SPhilip Reames // propagates a base pointer.
1005d03d2d8aSDmitry Makogon return States.count(VBDV) == 0;
10065cabf472SPhilip Reames };
10075cabf472SPhilip Reames
10085cabf472SPhilip Reames bool CanPrune = true;
10095cabf472SPhilip Reames visitBDVOperands(BDV, [&](Value *Op) {
10105cabf472SPhilip Reames CanPrune = CanPrune && canPruneInput(Op);
10115cabf472SPhilip Reames });
10125cabf472SPhilip Reames if (CanPrune)
10135cabf472SPhilip Reames ToRemove.push_back(BDV);
10145cabf472SPhilip Reames }
10155cabf472SPhilip Reames for (Value *V : ToRemove) {
10165cabf472SPhilip Reames States.erase(V);
10175cabf472SPhilip Reames // Cache the fact V is it's own base for later usage.
10185cabf472SPhilip Reames Cache[V] = V;
10195cabf472SPhilip Reames }
10205cabf472SPhilip Reames } while (!ToRemove.empty());
10215cabf472SPhilip Reames
10225cabf472SPhilip Reames // Did we manage to prove that Def itself must be a base pointer?
10235cabf472SPhilip Reames if (!States.count(Def))
10245cabf472SPhilip Reames return Def;
10255cabf472SPhilip Reames
1026273e6bbdSPhilip Reames // Return a phi state for a base defining value. We'll generate a new
1027273e6bbdSPhilip Reames // base state for known bases and expect to find a cached state otherwise.
1028eb282be9SAnna Thomas auto GetStateForBDV = [&](Value *BaseValue, Value *Input) {
1029eb282be9SAnna Thomas auto I = States.find(BaseValue);
10305cabf472SPhilip Reames if (I != States.end())
1031273e6bbdSPhilip Reames return I->second;
10325cabf472SPhilip Reames assert(areBothVectorOrScalar(BaseValue, Input));
10335cabf472SPhilip Reames return BDVState(BaseValue, BDVState::Base, BaseValue);
1034273e6bbdSPhilip Reames };
1035273e6bbdSPhilip Reames
103690547f1dSSanjoy Das bool Progress = true;
103790547f1dSSanjoy Das while (Progress) {
103842a7adf1SYaron Keren #ifndef NDEBUG
103990547f1dSSanjoy Das const size_t OldSize = States.size();
104042a7adf1SYaron Keren #endif
104190547f1dSSanjoy Das Progress = false;
104215d5563cSPhilip Reames // We're only changing values in this loop, thus safe to keep iterators.
104315d5563cSPhilip Reames // Since this is computing a fixed point, the order of visit does not
104415d5563cSPhilip Reames // effect the result. TODO: We could use a worklist here and make this run
104515d5563cSPhilip Reames // much faster.
104634d7a749SPhilip Reames for (auto Pair : States) {
1047ece70b80SPhilip Reames Value *BDV = Pair.first;
1048eb282be9SAnna Thomas // Only values that do not have known bases or those that have differing
1049eb282be9SAnna Thomas // type (scalar versus vector) from a possible known base should be in the
1050eb282be9SAnna Thomas // lattice.
10511da42c9fSDmitry Makogon assert((!isKnownBase(BDV, KnownBases) ||
1052eb282be9SAnna Thomas !areBothVectorOrScalar(BDV, Pair.second.getBaseValue())) &&
1053eb282be9SAnna Thomas "why did it get added?");
1054273e6bbdSPhilip Reames
10558fe59ba5SPhilip Reames BDVState NewState(BDV);
1056cf1899e0SPhilip Reames visitBDVOperands(BDV, [&](Value *Op) {
10571da42c9fSDmitry Makogon Value *BDV = findBaseOrBDV(Op, Cache, KnownBases);
1058cf1899e0SPhilip Reames auto OpState = GetStateForBDV(BDV, Op);
1059d2e15a83SSerguei Katkov NewState.meet(OpState);
1060cf1899e0SPhilip Reames });
10619ac4e38aSPhilip Reames
106290547f1dSSanjoy Das BDVState OldState = States[BDV];
106390547f1dSSanjoy Das if (OldState != NewState) {
106490547f1dSSanjoy Das Progress = true;
106590547f1dSSanjoy Das States[BDV] = NewState;
1066d16a9b1fSPhilip Reames }
1067d16a9b1fSPhilip Reames }
1068d16a9b1fSPhilip Reames
106990547f1dSSanjoy Das assert(OldSize == States.size() &&
1070b4e55f39SPhilip Reames "fixed point shouldn't be adding any new nodes to state");
1071d16a9b1fSPhilip Reames }
1072d16a9b1fSPhilip Reames
1073dab35f31SPhilip Reames #ifndef NDEBUG
10748fe59ba5SPhilip Reames VerifyStates();
1075d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "States after meet iteration:\n");
1076f5d23d36SSimon Pilgrim for (const auto &Pair : States) {
1077d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
10789d08642cSSanjoy Das }
1079dab35f31SPhilip Reames #endif
1080d16a9b1fSPhilip Reames
1081eb282be9SAnna Thomas // Handle all instructions that have a vector BDV, but the instruction itself
1082eb282be9SAnna Thomas // is of scalar type.
108334d7a749SPhilip Reames for (auto Pair : States) {
108415d5563cSPhilip Reames Instruction *I = cast<Instruction>(Pair.first);
108515d5563cSPhilip Reames BDVState State = Pair.second;
1086eb282be9SAnna Thomas auto *BaseValue = State.getBaseValue();
1087eb282be9SAnna Thomas // Only values that do not have known bases or those that have differing
1088eb282be9SAnna Thomas // type (scalar versus vector) from a possible known base should be in the
1089eb282be9SAnna Thomas // lattice.
10901da42c9fSDmitry Makogon assert(
10911da42c9fSDmitry Makogon (!isKnownBase(I, KnownBases) || !areBothVectorOrScalar(I, BaseValue)) &&
1092eb282be9SAnna Thomas "why did it get added?");
10936ff1a1e3SPhilip Reames assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
10949ac4e38aSPhilip Reames
1095eb282be9SAnna Thomas if (!State.isBase() || !isa<VectorType>(BaseValue->getType()))
1096eb282be9SAnna Thomas continue;
10979ac4e38aSPhilip Reames // extractelement instructions are a bit special in that we may need to
10989ac4e38aSPhilip Reames // insert an extract even when we know an exact base for the instruction.
10999ac4e38aSPhilip Reames // The problem is that we need to convert from a vector base to a scalar
11009ac4e38aSPhilip Reames // base for the particular indice we're interested in.
1101eb282be9SAnna Thomas if (isa<ExtractElementInst>(I)) {
11029ac4e38aSPhilip Reames auto *EE = cast<ExtractElementInst>(I);
11039ac4e38aSPhilip Reames // TODO: In many cases, the new instruction is just EE itself. We should
11049ac4e38aSPhilip Reames // exploit this, but can't do it here since it would break the invariant
11059ac4e38aSPhilip Reames // about the BDV not being known to be a base.
110690547f1dSSanjoy Das auto *BaseInst = ExtractElementInst::Create(
11077dda0edbSSanjoy Das State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
11089ac4e38aSPhilip Reames BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
11098fe59ba5SPhilip Reames States[I] = BDVState(I, BDVState::Base, BaseInst);
11101da42c9fSDmitry Makogon setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
1111eb282be9SAnna Thomas } else if (!isa<VectorType>(I->getType())) {
1112eb282be9SAnna Thomas // We need to handle cases that have a vector base but the instruction is
1113eb282be9SAnna Thomas // a scalar type (these could be phis or selects or any instruction that
1114eb282be9SAnna Thomas // are of scalar type, but the base can be a vector type). We
1115eb282be9SAnna Thomas // conservatively set this as conflict. Setting the base value for these
1116eb282be9SAnna Thomas // conflicts is handled in the next loop which traverses States.
11178fe59ba5SPhilip Reames States[I] = BDVState(I, BDVState::Conflict);
11189ac4e38aSPhilip Reames }
111959029b9eSAnna Thomas }
112059029b9eSAnna Thomas
11218fe59ba5SPhilip Reames #ifndef NDEBUG
11228fe59ba5SPhilip Reames VerifyStates();
11238fe59ba5SPhilip Reames #endif
11248fe59ba5SPhilip Reames
112559029b9eSAnna Thomas // Insert Phis for all conflicts
112659029b9eSAnna Thomas // TODO: adjust naming patterns to avoid this order of iteration dependency
112759029b9eSAnna Thomas for (auto Pair : States) {
112859029b9eSAnna Thomas Instruction *I = cast<Instruction>(Pair.first);
112959029b9eSAnna Thomas BDVState State = Pair.second;
1130eb282be9SAnna Thomas // Only values that do not have known bases or those that have differing
1131eb282be9SAnna Thomas // type (scalar versus vector) from a possible known base should be in the
1132eb282be9SAnna Thomas // lattice.
11331da42c9fSDmitry Makogon assert((!isKnownBase(I, KnownBases) ||
11341da42c9fSDmitry Makogon !areBothVectorOrScalar(I, State.getBaseValue())) &&
1135eb282be9SAnna Thomas "why did it get added?");
113659029b9eSAnna Thomas assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
11379ac4e38aSPhilip Reames
11386628713fSPhilip Reames // Since we're joining a vector and scalar base, they can never be the
11396628713fSPhilip Reames // same. As a result, we should always see insert element having reached
11406628713fSPhilip Reames // the conflict state.
114190547f1dSSanjoy Das assert(!isa<InsertElementInst>(I) || State.isConflict());
11426628713fSPhilip Reames
11436ff1a1e3SPhilip Reames if (!State.isConflict())
1144f986d68bSPhilip Reames continue;
1145f986d68bSPhilip Reames
1146cec9e735SPhilip Reames auto getMangledName = [](Instruction *I) -> std::string {
11476ff1a1e3SPhilip Reames if (isa<PHINode>(I)) {
1148cec9e735SPhilip Reames return suffixed_name_or(I, ".base", "base_phi");
1149cec9e735SPhilip Reames } else if (isa<SelectInst>(I)) {
1150cec9e735SPhilip Reames return suffixed_name_or(I, ".base", "base_select");
1151cec9e735SPhilip Reames } else if (isa<ExtractElementInst>(I)) {
1152cec9e735SPhilip Reames return suffixed_name_or(I, ".base", "base_ee");
1153cec9e735SPhilip Reames } else if (isa<InsertElementInst>(I)) {
1154cec9e735SPhilip Reames return suffixed_name_or(I, ".base", "base_ie");
1155479cbb94SAnna Thomas } else {
1156cec9e735SPhilip Reames return suffixed_name_or(I, ".base", "base_sv");
11579ac4e38aSPhilip Reames }
11586ff1a1e3SPhilip Reames };
1159cec9e735SPhilip Reames
1160cec9e735SPhilip Reames Instruction *BaseInst = I->clone();
1161cec9e735SPhilip Reames BaseInst->insertBefore(I);
1162cec9e735SPhilip Reames BaseInst->setName(getMangledName(I));
11636ff1a1e3SPhilip Reames // Add metadata marking this as a base value
11646ff1a1e3SPhilip Reames BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
11658fe59ba5SPhilip Reames States[I] = BDVState(I, BDVState::Conflict, BaseInst);
11661da42c9fSDmitry Makogon setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
1167d16a9b1fSPhilip Reames }
1168d16a9b1fSPhilip Reames
11698fe59ba5SPhilip Reames #ifndef NDEBUG
11708fe59ba5SPhilip Reames VerifyStates();
11718fe59ba5SPhilip Reames #endif
11728fe59ba5SPhilip Reames
11733ea15895SPhilip Reames // Returns a instruction which produces the base pointer for a given
11743ea15895SPhilip Reames // instruction. The instruction is assumed to be an input to one of the BDVs
11753ea15895SPhilip Reames // seen in the inference algorithm above. As such, we must either already
11763ea15895SPhilip Reames // know it's base defining value is a base, or have inserted a new
11773ea15895SPhilip Reames // instruction to propagate the base of it's BDV and have entered that newly
11783ea15895SPhilip Reames // introduced instruction into the state table. In either case, we are
11793ea15895SPhilip Reames // assured to be able to determine an instruction which produces it's base
11803ea15895SPhilip Reames // pointer.
11813ea15895SPhilip Reames auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
11821da42c9fSDmitry Makogon Value *BDV = findBaseOrBDV(Input, Cache, KnownBases);
11833ea15895SPhilip Reames Value *Base = nullptr;
11845cabf472SPhilip Reames if (!States.count(BDV)) {
11855cabf472SPhilip Reames assert(areBothVectorOrScalar(BDV, Input));
11863ea15895SPhilip Reames Base = BDV;
11873ea15895SPhilip Reames } else {
11883ea15895SPhilip Reames // Either conflict or base.
118934d7a749SPhilip Reames assert(States.count(BDV));
11907dda0edbSSanjoy Das Base = States[BDV].getBaseValue();
11913ea15895SPhilip Reames }
119290547f1dSSanjoy Das assert(Base && "Can't be null");
11933ea15895SPhilip Reames // The cast is needed since base traversal may strip away bitcasts
119490547f1dSSanjoy Das if (Base->getType() != Input->getType() && InsertPt)
119590547f1dSSanjoy Das Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
11963ea15895SPhilip Reames return Base;
11973ea15895SPhilip Reames };
11983ea15895SPhilip Reames
119915d5563cSPhilip Reames // Fixup all the inputs of the new PHIs. Visit order needs to be
120015d5563cSPhilip Reames // deterministic and predictable because we're naming newly created
120115d5563cSPhilip Reames // instructions.
120234d7a749SPhilip Reames for (auto Pair : States) {
12037540e3a4SPhilip Reames Instruction *BDV = cast<Instruction>(Pair.first);
1204c8ded462SPhilip Reames BDVState State = Pair.second;
1205d16a9b1fSPhilip Reames
1206eb282be9SAnna Thomas // Only values that do not have known bases or those that have differing
1207eb282be9SAnna Thomas // type (scalar versus vector) from a possible known base should be in the
1208eb282be9SAnna Thomas // lattice.
12091da42c9fSDmitry Makogon assert((!isKnownBase(BDV, KnownBases) ||
1210eb282be9SAnna Thomas !areBothVectorOrScalar(BDV, State.getBaseValue())) &&
1211eb282be9SAnna Thomas "why did it get added?");
1212c8ded462SPhilip Reames assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1213c8ded462SPhilip Reames if (!State.isConflict())
121428e61ce6SPhilip Reames continue;
121528e61ce6SPhilip Reames
12167dda0edbSSanjoy Das if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
121790547f1dSSanjoy Das PHINode *PN = cast<PHINode>(BDV);
1218cec9e735SPhilip Reames const unsigned NumPHIValues = PN->getNumIncomingValues();
1219cec9e735SPhilip Reames
1220cec9e735SPhilip Reames // The IR verifier requires phi nodes with multiple entries from the
1221cec9e735SPhilip Reames // same basic block to have the same incoming value for each of those
1222cec9e735SPhilip Reames // entries. Since we're inserting bitcasts in the loop, make sure we
1223cec9e735SPhilip Reames // do so at least once per incoming block.
1224cec9e735SPhilip Reames DenseMap<BasicBlock *, Value*> BlockToValue;
1225d16a9b1fSPhilip Reames for (unsigned i = 0; i < NumPHIValues; i++) {
122690547f1dSSanjoy Das Value *InVal = PN->getIncomingValue(i);
122790547f1dSSanjoy Das BasicBlock *InBB = PN->getIncomingBlock(i);
1228cec9e735SPhilip Reames if (!BlockToValue.count(InBB))
1229cec9e735SPhilip Reames BlockToValue[InBB] = getBaseForInput(InVal, InBB->getTerminator());
1230cec9e735SPhilip Reames else {
12313ea15895SPhilip Reames #ifndef NDEBUG
1232cec9e735SPhilip Reames Value *OldBase = BlockToValue[InBB];
12333ea15895SPhilip Reames Value *Base = getBaseForInput(InVal, nullptr);
12347c3e2b92SDaniil Suchkov
12357c3e2b92SDaniil Suchkov // We can't use `stripPointerCasts` instead of this function because
12367c3e2b92SDaniil Suchkov // `stripPointerCasts` doesn't handle vectors of pointers.
12377c3e2b92SDaniil Suchkov auto StripBitCasts = [](Value *V) -> Value * {
12387c3e2b92SDaniil Suchkov while (auto *BC = dyn_cast<BitCastInst>(V))
12397c3e2b92SDaniil Suchkov V = BC->getOperand(0);
12407c3e2b92SDaniil Suchkov return V;
12417c3e2b92SDaniil Suchkov };
124290547f1dSSanjoy Das // In essence this assert states: the only way two values
124390547f1dSSanjoy Das // incoming from the same basic block may be different is by
124490547f1dSSanjoy Das // being different bitcasts of the same value. A cleanup
124590547f1dSSanjoy Das // that remains TODO is changing findBaseOrBDV to return an
124690547f1dSSanjoy Das // llvm::Value of the correct type (and still remain pure).
124790547f1dSSanjoy Das // This will remove the need to add bitcasts.
12487c3e2b92SDaniil Suchkov assert(StripBitCasts(Base) == StripBitCasts(OldBase) &&
12499769e97cSZarko Todorovski "findBaseOrBDV should be pure!");
1250d16a9b1fSPhilip Reames #endif
1251d16a9b1fSPhilip Reames }
1252cec9e735SPhilip Reames Value *Base = BlockToValue[InBB];
1253cec9e735SPhilip Reames BasePHI->setIncomingValue(i, Base);
1254d16a9b1fSPhilip Reames }
12557dda0edbSSanjoy Das } else if (SelectInst *BaseSI =
12567dda0edbSSanjoy Das dyn_cast<SelectInst>(State.getBaseValue())) {
125790547f1dSSanjoy Das SelectInst *SI = cast<SelectInst>(BDV);
125890547f1dSSanjoy Das
125990547f1dSSanjoy Das // Find the instruction which produces the base for each input.
126090547f1dSSanjoy Das // We may need to insert a bitcast.
126190547f1dSSanjoy Das BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
126290547f1dSSanjoy Das BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
12637dda0edbSSanjoy Das } else if (auto *BaseEE =
12647dda0edbSSanjoy Das dyn_cast<ExtractElementInst>(State.getBaseValue())) {
12657540e3a4SPhilip Reames Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
12663ea15895SPhilip Reames // Find the instruction which produces the base for each input. We may
12673ea15895SPhilip Reames // need to insert a bitcast.
126890547f1dSSanjoy Das BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
1269479cbb94SAnna Thomas } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
12707540e3a4SPhilip Reames auto *BdvIE = cast<InsertElementInst>(BDV);
12716628713fSPhilip Reames auto UpdateOperand = [&](int OperandIdx) {
12726628713fSPhilip Reames Value *InVal = BdvIE->getOperand(OperandIdx);
1273953817b6SPhilip Reames Value *Base = getBaseForInput(InVal, BaseIE);
12746628713fSPhilip Reames BaseIE->setOperand(OperandIdx, Base);
12756628713fSPhilip Reames };
12766628713fSPhilip Reames UpdateOperand(0); // vector operand
12776628713fSPhilip Reames UpdateOperand(1); // scalar operand
1278479cbb94SAnna Thomas } else {
1279479cbb94SAnna Thomas auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1280479cbb94SAnna Thomas auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1281479cbb94SAnna Thomas auto UpdateOperand = [&](int OperandIdx) {
1282479cbb94SAnna Thomas Value *InVal = BdvSV->getOperand(OperandIdx);
1283479cbb94SAnna Thomas Value *Base = getBaseForInput(InVal, BaseSV);
1284479cbb94SAnna Thomas BaseSV->setOperand(OperandIdx, Base);
1285479cbb94SAnna Thomas };
1286479cbb94SAnna Thomas UpdateOperand(0); // vector operand
1287ef884e15SPhilip Reames if (!BdvSV->isZeroEltSplat())
1288479cbb94SAnna Thomas UpdateOperand(1); // vector operand
1289cec9e735SPhilip Reames else {
1290cec9e735SPhilip Reames // Never read, so just use undef
1291cec9e735SPhilip Reames Value *InVal = BdvSV->getOperand(1);
1292cec9e735SPhilip Reames BaseSV->setOperand(1, UndefValue::get(InVal->getType()));
1293cec9e735SPhilip Reames }
12946628713fSPhilip Reames }
1295d16a9b1fSPhilip Reames }
1296d16a9b1fSPhilip Reames
12978fe59ba5SPhilip Reames #ifndef NDEBUG
12988fe59ba5SPhilip Reames VerifyStates();
12998fe59ba5SPhilip Reames #endif
13008fe59ba5SPhilip Reames
1301d16a9b1fSPhilip Reames // Cache all of our results so we can cheaply reuse them
1302d16a9b1fSPhilip Reames // NOTE: This is actually two caches: one of the base defining value
1303d16a9b1fSPhilip Reames // relation and one of the base pointer relation! FIXME
130434d7a749SPhilip Reames for (auto Pair : States) {
130515d5563cSPhilip Reames auto *BDV = Pair.first;
13067dda0edbSSanjoy Das Value *Base = Pair.second.getBaseValue();
130790547f1dSSanjoy Das assert(BDV && Base);
1308eb282be9SAnna Thomas // Only values that do not have known bases or those that have differing
1309eb282be9SAnna Thomas // type (scalar versus vector) from a possible known base should be in the
1310eb282be9SAnna Thomas // lattice.
13111da42c9fSDmitry Makogon assert(
13121da42c9fSDmitry Makogon (!isKnownBase(BDV, KnownBases) || !areBothVectorOrScalar(BDV, Base)) &&
1313eb282be9SAnna Thomas "why did it get added?");
1314d16a9b1fSPhilip Reames
1315d34e60caSNicola Zaghen LLVM_DEBUG(
1316d34e60caSNicola Zaghen dbgs() << "Updating base value cache"
1317d3d9cbf1SEric Christopher << " for: " << BDV->getName() << " from: "
131890547f1dSSanjoy Das << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
131990547f1dSSanjoy Das << " to: " << Base->getName() << "\n");
1320d16a9b1fSPhilip Reames
132190547f1dSSanjoy Das Cache[BDV] = Base;
1322d16a9b1fSPhilip Reames }
132390547f1dSSanjoy Das assert(Cache.count(Def));
132490547f1dSSanjoy Das return Cache[Def];
1325d16a9b1fSPhilip Reames }
1326d16a9b1fSPhilip Reames
1327d16a9b1fSPhilip Reames // For a set of live pointers (base and/or derived), identify the base
1328d16a9b1fSPhilip Reames // pointer of the object which they are derived from. This routine will
1329d16a9b1fSPhilip Reames // mutate the IR graph as needed to make the 'base' pointer live at the
1330d16a9b1fSPhilip Reames // definition site of 'derived'. This ensures that any use of 'derived' can
1331d16a9b1fSPhilip Reames // also use 'base'. This may involve the insertion of a number of
1332d16a9b1fSPhilip Reames // additional PHI nodes.
1333d16a9b1fSPhilip Reames //
1334d16a9b1fSPhilip Reames // preconditions: live is a set of pointer type Values
1335d16a9b1fSPhilip Reames //
1336d16a9b1fSPhilip Reames // side effects: may insert PHI nodes into the existing CFG, will preserve
1337d16a9b1fSPhilip Reames // CFG, will not remove or mutate any existing nodes
1338d16a9b1fSPhilip Reames //
1339f2041324SPhilip Reames // post condition: PointerToBase contains one (derived, base) pair for every
1340d16a9b1fSPhilip Reames // pointer in live. Note that derived can be equal to base if the original
1341d16a9b1fSPhilip Reames // pointer was a base pointer.
findBasePointers(const StatepointLiveSetTy & live,PointerToBaseTy & PointerToBase,DominatorTree * DT,DefiningValueMapTy & DVCache,IsKnownBaseMapTy & KnownBases)134228c5e1b7SSerguei Katkov static void findBasePointers(const StatepointLiveSetTy &live,
134328c5e1b7SSerguei Katkov PointerToBaseTy &PointerToBase, DominatorTree *DT,
13441da42c9fSDmitry Makogon DefiningValueMapTy &DVCache,
13451da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
1346fb1811d3SIgor Laevsky for (Value *ptr : live) {
13471da42c9fSDmitry Makogon Value *base = findBasePointer(ptr, DVCache, KnownBases);
1348d16a9b1fSPhilip Reames assert(base && "failed to find base pointer");
1349f2041324SPhilip Reames PointerToBase[ptr] = base;
1350d16a9b1fSPhilip Reames assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1351d16a9b1fSPhilip Reames DT->dominates(cast<Instruction>(base)->getParent(),
1352d16a9b1fSPhilip Reames cast<Instruction>(ptr)->getParent())) &&
1353d16a9b1fSPhilip Reames "The base we found better dominate the derived pointer");
1354d16a9b1fSPhilip Reames }
1355d16a9b1fSPhilip Reames }
1356d16a9b1fSPhilip Reames
1357d16a9b1fSPhilip Reames /// Find the required based pointers (and adjust the live set) for the given
1358d16a9b1fSPhilip Reames /// parse point.
findBasePointers(DominatorTree & DT,DefiningValueMapTy & DVCache,CallBase * Call,PartiallyConstructedSafepointRecord & result,PointerToBaseTy & PointerToBase,IsKnownBaseMapTy & KnownBases)1359d16a9b1fSPhilip Reames static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
13603160734aSChandler Carruth CallBase *Call,
136128c5e1b7SSerguei Katkov PartiallyConstructedSafepointRecord &result,
13621da42c9fSDmitry Makogon PointerToBaseTy &PointerToBase,
13631da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
136499f93dd3SPhilip Reames StatepointLiveSetTy PotentiallyDerivedPointers = result.LiveSet;
136599f93dd3SPhilip Reames // We assume that all pointers passed to deopt are base pointers; as an
136699f93dd3SPhilip Reames // optimization, we can use this to avoid seperately materializing the base
136799f93dd3SPhilip Reames // pointer graph. This is only relevant since we're very conservative about
136899f93dd3SPhilip Reames // generating new conflict nodes during base pointer insertion. If we were
136999f93dd3SPhilip Reames // smarter there, this would be irrelevant.
137099f93dd3SPhilip Reames if (auto Opt = Call->getOperandBundle(LLVMContext::OB_deopt))
137199f93dd3SPhilip Reames for (Value *V : Opt->Inputs) {
137299f93dd3SPhilip Reames if (!PotentiallyDerivedPointers.count(V))
137399f93dd3SPhilip Reames continue;
137499f93dd3SPhilip Reames PotentiallyDerivedPointers.remove(V);
137599f93dd3SPhilip Reames PointerToBase[V] = V;
137699f93dd3SPhilip Reames }
13771da42c9fSDmitry Makogon findBasePointers(PotentiallyDerivedPointers, PointerToBase, &DT, DVCache,
13781da42c9fSDmitry Makogon KnownBases);
1379d16a9b1fSPhilip Reames }
1380d16a9b1fSPhilip Reames
1381df1ef08cSPhilip Reames /// Given an updated version of the dataflow liveness results, update the
1382df1ef08cSPhilip Reames /// liveset and base pointer maps for the call site CS.
1383df1ef08cSPhilip Reames static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
13843160734aSChandler Carruth CallBase *Call,
138528c5e1b7SSerguei Katkov PartiallyConstructedSafepointRecord &result,
138628c5e1b7SSerguei Katkov PointerToBaseTy &PointerToBase);
1387d16a9b1fSPhilip Reames
recomputeLiveInValues(Function & F,DominatorTree & DT,ArrayRef<CallBase * > toUpdate,MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,PointerToBaseTy & PointerToBase)1388df1ef08cSPhilip Reames static void recomputeLiveInValues(
13893160734aSChandler Carruth Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
139028c5e1b7SSerguei Katkov MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
139128c5e1b7SSerguei Katkov PointerToBaseTy &PointerToBase) {
1392df1ef08cSPhilip Reames // TODO-PERF: reuse the original liveness, then simply run the dataflow
1393df005cbeSBenjamin Kramer // again. The old values are still live and will help it stabilize quickly.
1394df1ef08cSPhilip Reames GCPtrLivenessData RevisedLivenessData;
1395df1ef08cSPhilip Reames computeLiveInValues(DT, F, RevisedLivenessData);
1396d16a9b1fSPhilip Reames for (size_t i = 0; i < records.size(); i++) {
1397d16a9b1fSPhilip Reames struct PartiallyConstructedSafepointRecord &info = records[i];
139828c5e1b7SSerguei Katkov recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info,
139928c5e1b7SSerguei Katkov PointerToBase);
1400d16a9b1fSPhilip Reames }
1401d16a9b1fSPhilip Reames }
1402d16a9b1fSPhilip Reames
14037ad67640SSanjoy Das // When inserting gc.relocate and gc.result calls, we need to ensure there are
14047ad67640SSanjoy Das // no uses of the original value / return value between the gc.statepoint and
14057ad67640SSanjoy Das // the gc.relocate / gc.result call. One case which can arise is a phi node
14067ad67640SSanjoy Das // starting one of the successor blocks. We also need to be able to insert the
14077ad67640SSanjoy Das // gc.relocates only on the path which goes through the statepoint. We might
14087ad67640SSanjoy Das // need to split an edge to make this possible.
1409f209a153SPhilip Reames static BasicBlock *
normalizeForInvokeSafepoint(BasicBlock * BB,BasicBlock * InvokeParent,DominatorTree & DT)1410ea45f0e0SSanjoy Das normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1411ea45f0e0SSanjoy Das DominatorTree &DT) {
141269e51caeSPhilip Reames BasicBlock *Ret = BB;
1413ff3dba73SSanjoy Das if (!BB->getUniquePredecessor())
141496ada25bSChandler Carruth Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1415d16a9b1fSPhilip Reames
14167ad67640SSanjoy Das // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
141769e51caeSPhilip Reames // from it
141869e51caeSPhilip Reames FoldSingleEntryPHINodes(Ret);
1419ff3dba73SSanjoy Das assert(!isa<PHINode>(Ret->begin()) &&
1420ff3dba73SSanjoy Das "All PHI nodes should have been removed!");
1421d16a9b1fSPhilip Reames
14227ad67640SSanjoy Das // At this point, we can safely insert a gc.relocate or gc.result as the first
14237ad67640SSanjoy Das // instruction in Ret if needed.
142469e51caeSPhilip Reames return Ret;
1425d16a9b1fSPhilip Reames }
1426d16a9b1fSPhilip Reames
14273f1c2183SPhilip Reames // List of all function attributes which must be stripped when lowering from
14283f1c2183SPhilip Reames // abstract machine model to physical machine model. Essentially, these are
14293f1c2183SPhilip Reames // all the effects a safepoint might have which we ignored in the abstract
14303f1c2183SPhilip Reames // machine model for purposes of optimization. We have to strip these on
14313f1c2183SPhilip Reames // both function declarations and call sites.
14323f1c2183SPhilip Reames static constexpr Attribute::AttrKind FnAttrsToStrip[] =
14333f1c2183SPhilip Reames {Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly,
14343f1c2183SPhilip Reames Attribute::ArgMemOnly, Attribute::InaccessibleMemOnly,
14353f1c2183SPhilip Reames Attribute::InaccessibleMemOrArgMemOnly,
14363f1c2183SPhilip Reames Attribute::NoSync, Attribute::NoFree};
14373f1c2183SPhilip Reames
1438df005cbeSBenjamin Kramer // Create new attribute set containing only attributes which can be transferred
1439d16a9b1fSPhilip Reames // from original call to the safepoint.
legalizeCallAttributes(LLVMContext & Ctx,AttributeList OrigAL,AttributeList StatepointAL)14407a5a1e94SBenjamin Kramer static AttributeList legalizeCallAttributes(LLVMContext &Ctx,
1441c680eeabSNikita Popov AttributeList OrigAL,
1442c680eeabSNikita Popov AttributeList StatepointAL) {
1443c680eeabSNikita Popov if (OrigAL.isEmpty())
1444c680eeabSNikita Popov return StatepointAL;
1445d16a9b1fSPhilip Reames
144699351967SReid Kleckner // Remove the readonly, readnone, and statepoint function attributes.
1447c680eeabSNikita Popov AttrBuilder FnAttrs(Ctx, OrigAL.getFnAttrs());
14483f1c2183SPhilip Reames for (auto Attr : FnAttrsToStrip)
14492c4548e1SPhilip Reames FnAttrs.removeAttribute(Attr);
14502c4548e1SPhilip Reames
1451c680eeabSNikita Popov for (Attribute A : OrigAL.getFnAttrs()) {
145299351967SReid Kleckner if (isStatepointDirectiveAttr(A))
14539290ccc3Sserge-sans-paille FnAttrs.removeAttribute(A);
1454d16a9b1fSPhilip Reames }
1455d16a9b1fSPhilip Reames
145699351967SReid Kleckner // Just skip parameter and return attributes for now
1457c680eeabSNikita Popov return StatepointAL.addFnAttributes(Ctx, FnAttrs);
1458d16a9b1fSPhilip Reames }
1459d16a9b1fSPhilip Reames
1460d16a9b1fSPhilip Reames /// Helper function to place all gc relocates necessary for the given
1461d16a9b1fSPhilip Reames /// statepoint.
1462d16a9b1fSPhilip Reames /// Inputs:
1463d16a9b1fSPhilip Reames /// liveVariables - list of variables to be relocated.
1464d16a9b1fSPhilip Reames /// basePtrs - base pointers.
1465d16a9b1fSPhilip Reames /// statepointToken - statepoint instruction to which relocates should be
1466d16a9b1fSPhilip Reames /// bound.
1467d16a9b1fSPhilip Reames /// Builder - Llvm IR builder to be used to construct new calls.
CreateGCRelocates(ArrayRef<Value * > LiveVariables,ArrayRef<Value * > BasePtrs,Instruction * StatepointToken,IRBuilder<> & Builder)1468b40bd1a9SSanjoy Das static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1469b40bd1a9SSanjoy Das ArrayRef<Value *> BasePtrs,
14705665c999SSanjoy Das Instruction *StatepointToken,
14717c362b25SNikita Popov IRBuilder<> &Builder) {
147294babb70SPhilip Reames if (LiveVariables.empty())
147394babb70SPhilip Reames return;
147494babb70SPhilip Reames
1475b1942f14SSanjoy Das auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
147675075efeSEugene Zelenko auto ValIt = llvm::find(LiveVec, Val);
1477b1942f14SSanjoy Das assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1478b1942f14SSanjoy Das size_t Index = std::distance(LiveVec.begin(), ValIt);
1479b1942f14SSanjoy Das assert(Index < LiveVec.size() && "Bug in std::find?");
1480b1942f14SSanjoy Das return Index;
1481b1942f14SSanjoy Das };
148274ce2e76SPhilip Reames Module *M = StatepointToken->getModule();
14835715f576SPhilip Reames
14845715f576SPhilip Reames // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
14855715f576SPhilip Reames // element type is i8 addrspace(1)*). We originally generated unique
14865715f576SPhilip Reames // declarations for each pointer type, but this proved problematic because
14875715f576SPhilip Reames // the intrinsic mangling code is incomplete and fragile. Since we're moving
14885715f576SPhilip Reames // towards a single unified pointer type anyways, we can just cast everything
14895715f576SPhilip Reames // to an i8* of the right address space. A bitcast is added later to convert
14905715f576SPhilip Reames // gc_relocate to the actual value's type.
14915715f576SPhilip Reames auto getGCRelocateDecl = [&] (Type *Ty) {
14925715f576SPhilip Reames assert(isHandledGCPointerType(Ty));
14935715f576SPhilip Reames auto AS = Ty->getScalarType()->getPointerAddressSpace();
14945715f576SPhilip Reames Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
14955715f576SPhilip Reames if (auto *VT = dyn_cast<VectorType>(Ty))
1496c444b1b9SChristopher Tetreault NewTy = FixedVectorType::get(NewTy,
1497c444b1b9SChristopher Tetreault cast<FixedVectorType>(VT)->getNumElements());
14985715f576SPhilip Reames return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
14995715f576SPhilip Reames {NewTy});
15005715f576SPhilip Reames };
15015715f576SPhilip Reames
15025715f576SPhilip Reames // Lazily populated map from input types to the canonicalized form mentioned
15035715f576SPhilip Reames // in the comment above. This should probably be cached somewhere more
15045715f576SPhilip Reames // broadly.
15057976eb58SJames Y Knight DenseMap<Type *, Function *> TypeToDeclMap;
1506d16a9b1fSPhilip Reames
15075665c999SSanjoy Das for (unsigned i = 0; i < LiveVariables.size(); i++) {
1508d16a9b1fSPhilip Reames // Generate the gc.relocate call and save the result
15093d40c751SPhilip Reames Value *BaseIdx = Builder.getInt32(FindIndex(LiveVariables, BasePtrs[i]));
15103d40c751SPhilip Reames Value *LiveIdx = Builder.getInt32(i);
1511d16a9b1fSPhilip Reames
15125715f576SPhilip Reames Type *Ty = LiveVariables[i]->getType();
15135715f576SPhilip Reames if (!TypeToDeclMap.count(Ty))
15145715f576SPhilip Reames TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
15157976eb58SJames Y Knight Function *GCRelocateDecl = TypeToDeclMap[Ty];
15165715f576SPhilip Reames
1517d16a9b1fSPhilip Reames // only specify a debug name if we can give a useful one
151874ce2e76SPhilip Reames CallInst *Reloc = Builder.CreateCall(
1519ff6409d0SDavid Blaikie GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1520ece70b80SPhilip Reames suffixed_name_or(LiveVariables[i], ".relocated", ""));
1521d16a9b1fSPhilip Reames // Trick CodeGen into thinking there are lots of free registers at this
1522d16a9b1fSPhilip Reames // fake call.
152374ce2e76SPhilip Reames Reloc->setCallingConv(CallingConv::Cold);
1524d16a9b1fSPhilip Reames }
1525d16a9b1fSPhilip Reames }
1526d16a9b1fSPhilip Reames
152725ec1a3eSSanjoy Das namespace {
152825ec1a3eSSanjoy Das
152925ec1a3eSSanjoy Das /// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
153025ec1a3eSSanjoy Das /// avoids having to worry about keeping around dangling pointers to Values.
153125ec1a3eSSanjoy Das class DeferredReplacement {
153225ec1a3eSSanjoy Das AssertingVH<Instruction> Old;
153325ec1a3eSSanjoy Das AssertingVH<Instruction> New;
153449e974b3SSanjoy Das bool IsDeoptimize = false;
153549e974b3SSanjoy Das
153675075efeSEugene Zelenko DeferredReplacement() = default;
153725ec1a3eSSanjoy Das
153825ec1a3eSSanjoy Das public:
createRAUW(Instruction * Old,Instruction * New)15398d89a2b2SSanjoy Das static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
15408d89a2b2SSanjoy Das assert(Old != New && Old && New &&
15418d89a2b2SSanjoy Das "Cannot RAUW equal values or to / from null!");
15428d89a2b2SSanjoy Das
15438d89a2b2SSanjoy Das DeferredReplacement D;
15448d89a2b2SSanjoy Das D.Old = Old;
15458d89a2b2SSanjoy Das D.New = New;
15468d89a2b2SSanjoy Das return D;
15478d89a2b2SSanjoy Das }
15488d89a2b2SSanjoy Das
createDelete(Instruction * ToErase)15498d89a2b2SSanjoy Das static DeferredReplacement createDelete(Instruction *ToErase) {
15508d89a2b2SSanjoy Das DeferredReplacement D;
15518d89a2b2SSanjoy Das D.Old = ToErase;
15528d89a2b2SSanjoy Das return D;
155325ec1a3eSSanjoy Das }
155425ec1a3eSSanjoy Das
createDeoptimizeReplacement(Instruction * Old)155549e974b3SSanjoy Das static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
155649e974b3SSanjoy Das #ifndef NDEBUG
155749e974b3SSanjoy Das auto *F = cast<CallInst>(Old)->getCalledFunction();
155849e974b3SSanjoy Das assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
155949e974b3SSanjoy Das "Only way to construct a deoptimize deferred replacement");
156049e974b3SSanjoy Das #endif
156149e974b3SSanjoy Das DeferredReplacement D;
156249e974b3SSanjoy Das D.Old = Old;
156349e974b3SSanjoy Das D.IsDeoptimize = true;
156449e974b3SSanjoy Das return D;
156549e974b3SSanjoy Das }
156649e974b3SSanjoy Das
156725ec1a3eSSanjoy Das /// Does the task represented by this instance.
doReplacement()156825ec1a3eSSanjoy Das void doReplacement() {
156925ec1a3eSSanjoy Das Instruction *OldI = Old;
157025ec1a3eSSanjoy Das Instruction *NewI = New;
157125ec1a3eSSanjoy Das
157225ec1a3eSSanjoy Das assert(OldI != NewI && "Disallowed at construction?!");
1573f35d4b09SRichard Trieu assert((!IsDeoptimize || !New) &&
1574f209649dSHiroshi Inoue "Deoptimize intrinsics are not replaced!");
157525ec1a3eSSanjoy Das
157625ec1a3eSSanjoy Das Old = nullptr;
157725ec1a3eSSanjoy Das New = nullptr;
157825ec1a3eSSanjoy Das
157925ec1a3eSSanjoy Das if (NewI)
158025ec1a3eSSanjoy Das OldI->replaceAllUsesWith(NewI);
158149e974b3SSanjoy Das
158249e974b3SSanjoy Das if (IsDeoptimize) {
158349e974b3SSanjoy Das // Note: we've inserted instructions, so the call to llvm.deoptimize may
1584f209649dSHiroshi Inoue // not necessarily be followed by the matching return.
158549e974b3SSanjoy Das auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
158649e974b3SSanjoy Das new UnreachableInst(RI->getContext(), RI);
158749e974b3SSanjoy Das RI->eraseFromParent();
158849e974b3SSanjoy Das }
158949e974b3SSanjoy Das
159025ec1a3eSSanjoy Das OldI->eraseFromParent();
159125ec1a3eSSanjoy Das }
159225ec1a3eSSanjoy Das };
159375075efeSEugene Zelenko
159475075efeSEugene Zelenko } // end anonymous namespace
159525ec1a3eSSanjoy Das
getDeoptLowering(CallBase * Call)15963160734aSChandler Carruth static StringRef getDeoptLowering(CallBase *Call) {
15972b1084acSPhilip Reames const char *DeoptLowering = "deopt-lowering";
15983160734aSChandler Carruth if (Call->hasFnAttr(DeoptLowering)) {
15993160734aSChandler Carruth // FIXME: Calls have a *really* confusing interface around attributes
16002b1084acSPhilip Reames // with values.
16013160734aSChandler Carruth const AttributeList &CSAS = Call->getAttributes();
1602d7593ebaSArthur Eubanks if (CSAS.hasFnAttr(DeoptLowering))
1603f80ae580SArthur Eubanks return CSAS.getFnAttr(DeoptLowering).getValueAsString();
16043160734aSChandler Carruth Function *F = Call->getCalledFunction();
16052b1084acSPhilip Reames assert(F && F->hasFnAttribute(DeoptLowering));
16062b1084acSPhilip Reames return F->getFnAttribute(DeoptLowering).getValueAsString();
16072b1084acSPhilip Reames }
16082b1084acSPhilip Reames return "live-through";
16092b1084acSPhilip Reames }
16102b1084acSPhilip Reames
1611d16a9b1fSPhilip Reames static void
makeStatepointExplicitImpl(CallBase * Call,const SmallVectorImpl<Value * > & BasePtrs,const SmallVectorImpl<Value * > & LiveVariables,PartiallyConstructedSafepointRecord & Result,std::vector<DeferredReplacement> & Replacements,const PointerToBaseTy & PointerToBase)16123160734aSChandler Carruth makeStatepointExplicitImpl(CallBase *Call, /* to replace */
1613b40bd1a9SSanjoy Das const SmallVectorImpl<Value *> &BasePtrs,
1614b40bd1a9SSanjoy Das const SmallVectorImpl<Value *> &LiveVariables,
161525ec1a3eSSanjoy Das PartiallyConstructedSafepointRecord &Result,
161628c5e1b7SSerguei Katkov std::vector<DeferredReplacement> &Replacements,
161728c5e1b7SSerguei Katkov const PointerToBaseTy &PointerToBase) {
1618b40bd1a9SSanjoy Das assert(BasePtrs.size() == LiveVariables.size());
1619d16a9b1fSPhilip Reames
1620d16a9b1fSPhilip Reames // Then go ahead and use the builder do actually do the inserts. We insert
1621d16a9b1fSPhilip Reames // immediately before the previous instruction under the assumption that all
1622d16a9b1fSPhilip Reames // arguments will be available here. We can't insert afterwards since we may
1623d16a9b1fSPhilip Reames // be replacing a terminator.
16243160734aSChandler Carruth IRBuilder<> Builder(Call);
1625b40bd1a9SSanjoy Das
16263c520a12SSanjoy Das ArrayRef<Value *> GCArgs(LiveVariables);
1627c9058ca9SSanjoy Das uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
162825ec1a3eSSanjoy Das uint32_t NumPatchBytes = 0;
162925ec1a3eSSanjoy Das uint32_t Flags = uint32_t(StatepointFlags::None);
16303c520a12SSanjoy Das
163119aacdb7SKazu Hirata SmallVector<Value *, 8> CallArgs(Call->args());
1632587fa99cSPhilip Reames Optional<ArrayRef<Use>> DeoptArgs;
1633587fa99cSPhilip Reames if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_deopt))
1634587fa99cSPhilip Reames DeoptArgs = Bundle->Inputs;
1635587fa99cSPhilip Reames Optional<ArrayRef<Use>> TransitionArgs;
1636587fa99cSPhilip Reames if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
1637587fa99cSPhilip Reames TransitionArgs = Bundle->Inputs;
1638587fa99cSPhilip Reames // TODO: This flag no longer serves a purpose and can be removed later
1639a34ce95bSSanjoy Das Flags |= uint32_t(StatepointFlags::GCTransition);
1640a34ce95bSSanjoy Das }
164199abb272SSanjoy Das
164299abb272SSanjoy Das // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
164399abb272SSanjoy Das // with a return value, we lower then as never returning calls to
164499abb272SSanjoy Das // __llvm_deoptimize that are followed by unreachable to get better codegen.
164549e974b3SSanjoy Das bool IsDeoptimize = false;
164625ec1a3eSSanjoy Das
164731203887SSanjoy Das StatepointDirectives SD =
16483160734aSChandler Carruth parseStatepointDirectivesFromAttrs(Call->getAttributes());
164931203887SSanjoy Das if (SD.NumPatchBytes)
165031203887SSanjoy Das NumPatchBytes = *SD.NumPatchBytes;
165131203887SSanjoy Das if (SD.StatepointID)
165231203887SSanjoy Das StatepointID = *SD.StatepointID;
165325ec1a3eSSanjoy Das
16542b1084acSPhilip Reames // Pass through the requested lowering if any. The default is live-through.
16553160734aSChandler Carruth StringRef DeoptLowering = getDeoptLowering(Call);
16562b1084acSPhilip Reames if (DeoptLowering.equals("live-in"))
16572b1084acSPhilip Reames Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
16582b1084acSPhilip Reames else {
16592b1084acSPhilip Reames assert(DeoptLowering.equals("live-through") && "Unsupported value!");
16602b1084acSPhilip Reames }
16612b1084acSPhilip Reames
1662c680eeabSNikita Popov FunctionCallee CallTarget(Call->getFunctionType(), Call->getCalledOperand());
1663c680eeabSNikita Popov if (Function *F = dyn_cast<Function>(CallTarget.getCallee())) {
1664e8cce5adSArtur Pilipenko auto IID = F->getIntrinsicID();
1665e8cce5adSArtur Pilipenko if (IID == Intrinsic::experimental_deoptimize) {
1666091fcfa3SSanjoy Das // Calls to llvm.experimental.deoptimize are lowered to calls to the
1667d4c78333SSanjoy Das // __llvm_deoptimize symbol. We want to resolve this now, since the
1668d4c78333SSanjoy Das // verifier does not allow taking the address of an intrinsic function.
1669d4c78333SSanjoy Das
1670d4c78333SSanjoy Das SmallVector<Type *, 8> DomainTy;
1671d4c78333SSanjoy Das for (Value *Arg : CallArgs)
1672d4c78333SSanjoy Das DomainTy.push_back(Arg->getType());
167349e974b3SSanjoy Das auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1674d4c78333SSanjoy Das /* isVarArg = */ false);
1675d4c78333SSanjoy Das
1676d4c78333SSanjoy Das // Note: CallTarget can be a bitcast instruction of a symbol if there are
1677d4c78333SSanjoy Das // calls to @llvm.experimental.deoptimize with different argument types in
1678d4c78333SSanjoy Das // the same module. This is fine -- we assume the frontend knew what it
1679d4c78333SSanjoy Das // was doing when generating this kind of IR.
168013680223SJames Y Knight CallTarget = F->getParent()
1681c680eeabSNikita Popov ->getOrInsertFunction("__llvm_deoptimize", FTy);
168249e974b3SSanjoy Das
168349e974b3SSanjoy Das IsDeoptimize = true;
16846ec2c5e4SArtur Pilipenko } else if (IID == Intrinsic::memcpy_element_unordered_atomic ||
16856ec2c5e4SArtur Pilipenko IID == Intrinsic::memmove_element_unordered_atomic) {
16866ec2c5e4SArtur Pilipenko // Unordered atomic memcpy and memmove intrinsics which are not explicitly
16876ec2c5e4SArtur Pilipenko // marked as "gc-leaf-function" should be lowered in a GC parseable way.
16886ec2c5e4SArtur Pilipenko // Specifically, these calls should be lowered to the
16896ec2c5e4SArtur Pilipenko // __llvm_{memcpy|memmove}_element_unordered_atomic_safepoint symbols.
16906ec2c5e4SArtur Pilipenko // Similarly to __llvm_deoptimize we want to resolve this now, since the
16916ec2c5e4SArtur Pilipenko // verifier does not allow taking the address of an intrinsic function.
16926ec2c5e4SArtur Pilipenko //
16936ec2c5e4SArtur Pilipenko // Moreover we need to shuffle the arguments for the call in order to
16946ec2c5e4SArtur Pilipenko // accommodate GC. The underlying source and destination objects might be
16956ec2c5e4SArtur Pilipenko // relocated during copy operation should the GC occur. To relocate the
16966ec2c5e4SArtur Pilipenko // derived source and destination pointers the implementation of the
16976ec2c5e4SArtur Pilipenko // intrinsic should know the corresponding base pointers.
16986ec2c5e4SArtur Pilipenko //
16996ec2c5e4SArtur Pilipenko // To make the base pointers available pass them explicitly as arguments:
17006ec2c5e4SArtur Pilipenko // memcpy(dest_derived, source_derived, ...) =>
17016ec2c5e4SArtur Pilipenko // memcpy(dest_base, dest_offset, source_base, source_offset, ...)
17026ec2c5e4SArtur Pilipenko auto &Context = Call->getContext();
17036ec2c5e4SArtur Pilipenko auto &DL = Call->getModule()->getDataLayout();
17046ec2c5e4SArtur Pilipenko auto GetBaseAndOffset = [&](Value *Derived) {
1705*a40af858SMax Kazantsev Value *Base = nullptr;
1706*a40af858SMax Kazantsev // Optimizations in unreachable code might substitute the real pointer
1707*a40af858SMax Kazantsev // with undef, poison or null-derived constant. Return null base for
1708*a40af858SMax Kazantsev // them to be consistent with the handling in the main algorithm in
1709*a40af858SMax Kazantsev // findBaseDefiningValue.
1710*a40af858SMax Kazantsev if (isa<Constant>(Derived))
1711*a40af858SMax Kazantsev Base =
1712*a40af858SMax Kazantsev ConstantPointerNull::get(cast<PointerType>(Derived->getType()));
1713*a40af858SMax Kazantsev else {
171428c5e1b7SSerguei Katkov assert(PointerToBase.count(Derived));
1715*a40af858SMax Kazantsev Base = PointerToBase.find(Derived)->second;
1716*a40af858SMax Kazantsev }
17176ec2c5e4SArtur Pilipenko unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
17186ec2c5e4SArtur Pilipenko unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
17196ec2c5e4SArtur Pilipenko Value *Base_int = Builder.CreatePtrToInt(
17206ec2c5e4SArtur Pilipenko Base, Type::getIntNTy(Context, IntPtrSize));
17216ec2c5e4SArtur Pilipenko Value *Derived_int = Builder.CreatePtrToInt(
17226ec2c5e4SArtur Pilipenko Derived, Type::getIntNTy(Context, IntPtrSize));
17236ec2c5e4SArtur Pilipenko return std::make_pair(Base, Builder.CreateSub(Derived_int, Base_int));
17246ec2c5e4SArtur Pilipenko };
17256ec2c5e4SArtur Pilipenko
17266ec2c5e4SArtur Pilipenko auto *Dest = CallArgs[0];
17276ec2c5e4SArtur Pilipenko Value *DestBase, *DestOffset;
17286ec2c5e4SArtur Pilipenko std::tie(DestBase, DestOffset) = GetBaseAndOffset(Dest);
17296ec2c5e4SArtur Pilipenko
17306ec2c5e4SArtur Pilipenko auto *Source = CallArgs[1];
17316ec2c5e4SArtur Pilipenko Value *SourceBase, *SourceOffset;
17326ec2c5e4SArtur Pilipenko std::tie(SourceBase, SourceOffset) = GetBaseAndOffset(Source);
17336ec2c5e4SArtur Pilipenko
17346ec2c5e4SArtur Pilipenko auto *LengthInBytes = CallArgs[2];
17356ec2c5e4SArtur Pilipenko auto *ElementSizeCI = cast<ConstantInt>(CallArgs[3]);
17366ec2c5e4SArtur Pilipenko
17376ec2c5e4SArtur Pilipenko CallArgs.clear();
17386ec2c5e4SArtur Pilipenko CallArgs.push_back(DestBase);
17396ec2c5e4SArtur Pilipenko CallArgs.push_back(DestOffset);
17406ec2c5e4SArtur Pilipenko CallArgs.push_back(SourceBase);
17416ec2c5e4SArtur Pilipenko CallArgs.push_back(SourceOffset);
17426ec2c5e4SArtur Pilipenko CallArgs.push_back(LengthInBytes);
17436ec2c5e4SArtur Pilipenko
17446ec2c5e4SArtur Pilipenko SmallVector<Type *, 8> DomainTy;
17456ec2c5e4SArtur Pilipenko for (Value *Arg : CallArgs)
17466ec2c5e4SArtur Pilipenko DomainTy.push_back(Arg->getType());
17476ec2c5e4SArtur Pilipenko auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
17486ec2c5e4SArtur Pilipenko /* isVarArg = */ false);
17496ec2c5e4SArtur Pilipenko
17506ec2c5e4SArtur Pilipenko auto GetFunctionName = [](Intrinsic::ID IID, ConstantInt *ElementSizeCI) {
17516ec2c5e4SArtur Pilipenko uint64_t ElementSize = ElementSizeCI->getZExtValue();
17526ec2c5e4SArtur Pilipenko if (IID == Intrinsic::memcpy_element_unordered_atomic) {
17536ec2c5e4SArtur Pilipenko switch (ElementSize) {
17546ec2c5e4SArtur Pilipenko case 1:
17556ec2c5e4SArtur Pilipenko return "__llvm_memcpy_element_unordered_atomic_safepoint_1";
17566ec2c5e4SArtur Pilipenko case 2:
17576ec2c5e4SArtur Pilipenko return "__llvm_memcpy_element_unordered_atomic_safepoint_2";
17586ec2c5e4SArtur Pilipenko case 4:
17596ec2c5e4SArtur Pilipenko return "__llvm_memcpy_element_unordered_atomic_safepoint_4";
17606ec2c5e4SArtur Pilipenko case 8:
17616ec2c5e4SArtur Pilipenko return "__llvm_memcpy_element_unordered_atomic_safepoint_8";
17626ec2c5e4SArtur Pilipenko case 16:
17636ec2c5e4SArtur Pilipenko return "__llvm_memcpy_element_unordered_atomic_safepoint_16";
17646ec2c5e4SArtur Pilipenko default:
17656ec2c5e4SArtur Pilipenko llvm_unreachable("unexpected element size!");
17666ec2c5e4SArtur Pilipenko }
17676ec2c5e4SArtur Pilipenko }
17686ec2c5e4SArtur Pilipenko assert(IID == Intrinsic::memmove_element_unordered_atomic);
17696ec2c5e4SArtur Pilipenko switch (ElementSize) {
17706ec2c5e4SArtur Pilipenko case 1:
17716ec2c5e4SArtur Pilipenko return "__llvm_memmove_element_unordered_atomic_safepoint_1";
17726ec2c5e4SArtur Pilipenko case 2:
17736ec2c5e4SArtur Pilipenko return "__llvm_memmove_element_unordered_atomic_safepoint_2";
17746ec2c5e4SArtur Pilipenko case 4:
17756ec2c5e4SArtur Pilipenko return "__llvm_memmove_element_unordered_atomic_safepoint_4";
17766ec2c5e4SArtur Pilipenko case 8:
17776ec2c5e4SArtur Pilipenko return "__llvm_memmove_element_unordered_atomic_safepoint_8";
17786ec2c5e4SArtur Pilipenko case 16:
17796ec2c5e4SArtur Pilipenko return "__llvm_memmove_element_unordered_atomic_safepoint_16";
17806ec2c5e4SArtur Pilipenko default:
17816ec2c5e4SArtur Pilipenko llvm_unreachable("unexpected element size!");
17826ec2c5e4SArtur Pilipenko }
17836ec2c5e4SArtur Pilipenko };
17846ec2c5e4SArtur Pilipenko
17856ec2c5e4SArtur Pilipenko CallTarget =
17866ec2c5e4SArtur Pilipenko F->getParent()
1787c680eeabSNikita Popov ->getOrInsertFunction(GetFunctionName(IID, ElementSizeCI), FTy);
1788d4c78333SSanjoy Das }
1789d4c78333SSanjoy Das }
179025ec1a3eSSanjoy Das
1791d16a9b1fSPhilip Reames // Create the statepoint given all the arguments
1792a0d2fd4aSPhilip Reames GCStatepointInst *Token = nullptr;
17933160734aSChandler Carruth if (auto *CI = dyn_cast<CallInst>(Call)) {
17943160734aSChandler Carruth CallInst *SPCall = Builder.CreateGCStatepointCall(
17953c520a12SSanjoy Das StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
17963c520a12SSanjoy Das TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
17973c520a12SSanjoy Das
17983160734aSChandler Carruth SPCall->setTailCallKind(CI->getTailCallKind());
17993160734aSChandler Carruth SPCall->setCallingConv(CI->getCallingConv());
1800d16a9b1fSPhilip Reames
1801d16a9b1fSPhilip Reames // Currently we will fail on parameter attributes and on certain
180299351967SReid Kleckner // function attributes. In case if we can handle this set of attributes -
180399351967SReid Kleckner // set up function attrs directly on statepoint and return attrs later for
180499351967SReid Kleckner // gc_result intrinsic.
1805c680eeabSNikita Popov SPCall->setAttributes(legalizeCallAttributes(
1806c680eeabSNikita Popov CI->getContext(), CI->getAttributes(), SPCall->getAttributes()));
1807d16a9b1fSPhilip Reames
1808a0d2fd4aSPhilip Reames Token = cast<GCStatepointInst>(SPCall);
1809d16a9b1fSPhilip Reames
1810d16a9b1fSPhilip Reames // Put the following gc_result and gc_relocate calls immediately after the
1811d16a9b1fSPhilip Reames // the old call (which we're about to delete)
18123160734aSChandler Carruth assert(CI->getNextNode() && "Not a terminator, must have next!");
18133160734aSChandler Carruth Builder.SetInsertPoint(CI->getNextNode());
18143160734aSChandler Carruth Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
181582ad7877SDavid Blaikie } else {
18163160734aSChandler Carruth auto *II = cast<InvokeInst>(Call);
1817d16a9b1fSPhilip Reames
1818d16a9b1fSPhilip Reames // Insert the new invoke into the old block. We'll remove the old one in a
1819d16a9b1fSPhilip Reames // moment at which point this will become the new terminator for the
1820d16a9b1fSPhilip Reames // original block.
18213160734aSChandler Carruth InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
18223160734aSChandler Carruth StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
18233160734aSChandler Carruth II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs, GCArgs,
18243160734aSChandler Carruth "statepoint_token");
18253c520a12SSanjoy Das
18263160734aSChandler Carruth SPInvoke->setCallingConv(II->getCallingConv());
1827d16a9b1fSPhilip Reames
1828d16a9b1fSPhilip Reames // Currently we will fail on parameter attributes and on certain
182999351967SReid Kleckner // function attributes. In case if we can handle this set of attributes -
183099351967SReid Kleckner // set up function attrs directly on statepoint and return attrs later for
183199351967SReid Kleckner // gc_result intrinsic.
1832c680eeabSNikita Popov SPInvoke->setAttributes(legalizeCallAttributes(
1833c680eeabSNikita Popov II->getContext(), II->getAttributes(), SPInvoke->getAttributes()));
1834d16a9b1fSPhilip Reames
1835a0d2fd4aSPhilip Reames Token = cast<GCStatepointInst>(SPInvoke);
1836d16a9b1fSPhilip Reames
1837d16a9b1fSPhilip Reames // Generate gc relocates in exceptional path
18383160734aSChandler Carruth BasicBlock *UnwindBlock = II->getUnwindDest();
1839b40bd1a9SSanjoy Das assert(!isa<PHINode>(UnwindBlock->begin()) &&
1840b40bd1a9SSanjoy Das UnwindBlock->getUniquePredecessor() &&
184169e51caeSPhilip Reames "can't safely insert in this block!");
1842d16a9b1fSPhilip Reames
1843be4d8cbaSDuncan P. N. Exon Smith Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
18443160734aSChandler Carruth Builder.SetCurrentDebugLocation(II->getDebugLoc());
1845d16a9b1fSPhilip Reames
1846d71999efSChen Li // Attach exceptional gc relocates to the landingpad.
1847d71999efSChen Li Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
1848b40bd1a9SSanjoy Das Result.UnwindToken = ExceptionalToken;
1849d16a9b1fSPhilip Reames
18503d40c751SPhilip Reames CreateGCRelocates(LiveVariables, BasePtrs, ExceptionalToken, Builder);
1851d16a9b1fSPhilip Reames
1852d16a9b1fSPhilip Reames // Generate gc relocates and returns for normal block
18533160734aSChandler Carruth BasicBlock *NormalDest = II->getNormalDest();
1854b40bd1a9SSanjoy Das assert(!isa<PHINode>(NormalDest->begin()) &&
1855b40bd1a9SSanjoy Das NormalDest->getUniquePredecessor() &&
185669e51caeSPhilip Reames "can't safely insert in this block!");
1857d16a9b1fSPhilip Reames
1858be4d8cbaSDuncan P. N. Exon Smith Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1859d16a9b1fSPhilip Reames
1860d16a9b1fSPhilip Reames // gc relocates will be generated later as if it were regular call
1861d16a9b1fSPhilip Reames // statepoint
1862d16a9b1fSPhilip Reames }
1863b40bd1a9SSanjoy Das assert(Token && "Should be set in one of the above branches!");
1864d16a9b1fSPhilip Reames
186549e974b3SSanjoy Das if (IsDeoptimize) {
186649e974b3SSanjoy Das // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
186749e974b3SSanjoy Das // transform the tail-call like structure to a call to a void function
186849e974b3SSanjoy Das // followed by unreachable to get better codegen.
186949e974b3SSanjoy Das Replacements.push_back(
18703160734aSChandler Carruth DeferredReplacement::createDeoptimizeReplacement(Call));
187149e974b3SSanjoy Das } else {
187225ec1a3eSSanjoy Das Token->setName("statepoint_token");
18733160734aSChandler Carruth if (!Call->getType()->isVoidTy() && !Call->use_empty()) {
18743160734aSChandler Carruth StringRef Name = Call->hasName() ? Call->getName() : "";
18753160734aSChandler Carruth CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
1876eb9dd5b8SReid Kleckner GCResult->setAttributes(
1877eb9dd5b8SReid Kleckner AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
187880ea2bb5SArthur Eubanks Call->getAttributes().getRetAttrs()));
1879d16a9b1fSPhilip Reames
188025ec1a3eSSanjoy Das // We cannot RAUW or delete CS.getInstruction() because it could be in the
188125ec1a3eSSanjoy Das // live set of some other safepoint, in which case that safepoint's
188225ec1a3eSSanjoy Das // PartiallyConstructedSafepointRecord will hold a raw pointer to this
188325ec1a3eSSanjoy Das // llvm::Instruction. Instead, we defer the replacement and deletion to
188425ec1a3eSSanjoy Das // after the live sets have been made explicit in the IR, and we no longer
188525ec1a3eSSanjoy Das // have raw pointers to worry about.
18868d89a2b2SSanjoy Das Replacements.emplace_back(
18873160734aSChandler Carruth DeferredReplacement::createRAUW(Call, GCResult));
188825ec1a3eSSanjoy Das } else {
18893160734aSChandler Carruth Replacements.emplace_back(DeferredReplacement::createDelete(Call));
189025ec1a3eSSanjoy Das }
189149e974b3SSanjoy Das }
1892d16a9b1fSPhilip Reames
1893b40bd1a9SSanjoy Das Result.StatepointToken = Token;
18940a3240f4SPhilip Reames
1895d16a9b1fSPhilip Reames // Second, create a gc.relocate for every live variable
18963d40c751SPhilip Reames CreateGCRelocates(LiveVariables, BasePtrs, Token, Builder);
1897d16a9b1fSPhilip Reames }
1898d16a9b1fSPhilip Reames
1899d16a9b1fSPhilip Reames // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1900d16a9b1fSPhilip Reames // which make the relocations happening at this safepoint explicit.
1901d16a9b1fSPhilip Reames //
1902d16a9b1fSPhilip Reames // WARNING: Does not do any fixup to adjust users of the original live
1903d16a9b1fSPhilip Reames // values. That's the callers responsibility.
1904d16a9b1fSPhilip Reames static void
makeStatepointExplicit(DominatorTree & DT,CallBase * Call,PartiallyConstructedSafepointRecord & Result,std::vector<DeferredReplacement> & Replacements,const PointerToBaseTy & PointerToBase)19053160734aSChandler Carruth makeStatepointExplicit(DominatorTree &DT, CallBase *Call,
190625ec1a3eSSanjoy Das PartiallyConstructedSafepointRecord &Result,
190728c5e1b7SSerguei Katkov std::vector<DeferredReplacement> &Replacements,
190828c5e1b7SSerguei Katkov const PointerToBaseTy &PointerToBase) {
19091ede5367SSanjoy Das const auto &LiveSet = Result.LiveSet;
1910d16a9b1fSPhilip Reames
1911d16a9b1fSPhilip Reames // Convert to vector for efficient cross referencing.
1912b40bd1a9SSanjoy Das SmallVector<Value *, 64> BaseVec, LiveVec;
1913b40bd1a9SSanjoy Das LiveVec.reserve(LiveSet.size());
1914b40bd1a9SSanjoy Das BaseVec.reserve(LiveSet.size());
1915b40bd1a9SSanjoy Das for (Value *L : LiveSet) {
1916b40bd1a9SSanjoy Das LiveVec.push_back(L);
191774ce2e76SPhilip Reames assert(PointerToBase.count(L));
19181ede5367SSanjoy Das Value *Base = PointerToBase.find(L)->second;
1919b40bd1a9SSanjoy Das BaseVec.push_back(Base);
1920d16a9b1fSPhilip Reames }
1921b40bd1a9SSanjoy Das assert(LiveVec.size() == BaseVec.size());
1922d16a9b1fSPhilip Reames
1923d16a9b1fSPhilip Reames // Do the actual rewriting and delete the old statepoint
192428c5e1b7SSerguei Katkov makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements,
192528c5e1b7SSerguei Katkov PointerToBase);
1926d16a9b1fSPhilip Reames }
1927d16a9b1fSPhilip Reames
1928d16a9b1fSPhilip Reames // Helper function for the relocationViaAlloca.
1929b40bd1a9SSanjoy Das //
1930b40bd1a9SSanjoy Das // It receives iterator to the statepoint gc relocates and emits a store to the
1931b40bd1a9SSanjoy Das // assigned location (via allocaMap) for the each one of them. It adds the
1932b40bd1a9SSanjoy Das // visited values into the visitedLiveValues set, which we will later use them
19339769e97cSZarko Todorovski // for validation checking.
1934d16a9b1fSPhilip Reames static void
insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,DenseMap<Value *,AllocaInst * > & AllocaMap,DenseSet<Value * > & VisitedLiveValues)19355665c999SSanjoy Das insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
193614359ef1SJames Y Knight DenseMap<Value *, AllocaInst *> &AllocaMap,
19375665c999SSanjoy Das DenseSet<Value *> &VisitedLiveValues) {
19385665c999SSanjoy Das for (User *U : GCRelocs) {
193983eefa6dSManuel Jacob GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
194083eefa6dSManuel Jacob if (!Relocate)
1941d16a9b1fSPhilip Reames continue;
1942d16a9b1fSPhilip Reames
1943565f7866SSanjoy Das Value *OriginalValue = Relocate->getDerivedPtr();
19445665c999SSanjoy Das assert(AllocaMap.count(OriginalValue));
19455665c999SSanjoy Das Value *Alloca = AllocaMap[OriginalValue];
1946d16a9b1fSPhilip Reames
1947d16a9b1fSPhilip Reames // Emit store into the related alloca
1948b40bd1a9SSanjoy Das // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
194989c5491aSSanjoy Das // the correct type according to alloca.
195083eefa6dSManuel Jacob assert(Relocate->getNextNode() &&
1951b40bd1a9SSanjoy Das "Should always have one since it's not a terminator");
195283eefa6dSManuel Jacob IRBuilder<> Builder(Relocate->getNextNode());
195389c5491aSSanjoy Das Value *CastedRelocatedValue =
195483eefa6dSManuel Jacob Builder.CreateBitCast(Relocate,
1955ece70b80SPhilip Reames cast<AllocaInst>(Alloca)->getAllocatedType(),
195683eefa6dSManuel Jacob suffixed_name_or(Relocate, ".casted", ""));
195789c5491aSSanjoy Das
195811aa3707SEli Friedman new StoreInst(CastedRelocatedValue, Alloca,
195911aa3707SEli Friedman cast<Instruction>(CastedRelocatedValue)->getNextNode());
1960d16a9b1fSPhilip Reames
1961d16a9b1fSPhilip Reames #ifndef NDEBUG
19625665c999SSanjoy Das VisitedLiveValues.insert(OriginalValue);
1963d16a9b1fSPhilip Reames #endif
1964d16a9b1fSPhilip Reames }
1965d16a9b1fSPhilip Reames }
1966d16a9b1fSPhilip Reames
1967e0317186SIgor Laevsky // Helper function for the "relocationViaAlloca". Similar to the
1968e0317186SIgor Laevsky // "insertRelocationStores" but works for rematerialized values.
insertRematerializationStores(const RematerializedValueMapTy & RematerializedValues,DenseMap<Value *,AllocaInst * > & AllocaMap,DenseSet<Value * > & VisitedLiveValues)1969adc23763SJoseph Tremoulet static void insertRematerializationStores(
1970adc23763SJoseph Tremoulet const RematerializedValueMapTy &RematerializedValues,
197114359ef1SJames Y Knight DenseMap<Value *, AllocaInst *> &AllocaMap,
1972e0317186SIgor Laevsky DenseSet<Value *> &VisitedLiveValues) {
1973e0317186SIgor Laevsky for (auto RematerializedValuePair: RematerializedValues) {
1974e0317186SIgor Laevsky Instruction *RematerializedValue = RematerializedValuePair.first;
1975e0317186SIgor Laevsky Value *OriginalValue = RematerializedValuePair.second;
1976e0317186SIgor Laevsky
1977e0317186SIgor Laevsky assert(AllocaMap.count(OriginalValue) &&
1978e0317186SIgor Laevsky "Can not find alloca for rematerialized value");
1979e0317186SIgor Laevsky Value *Alloca = AllocaMap[OriginalValue];
1980e0317186SIgor Laevsky
198111aa3707SEli Friedman new StoreInst(RematerializedValue, Alloca,
198211aa3707SEli Friedman RematerializedValue->getNextNode());
1983e0317186SIgor Laevsky
1984e0317186SIgor Laevsky #ifndef NDEBUG
1985e0317186SIgor Laevsky VisitedLiveValues.insert(OriginalValue);
1986e0317186SIgor Laevsky #endif
1987e0317186SIgor Laevsky }
1988e0317186SIgor Laevsky }
1989e0317186SIgor Laevsky
1990b40bd1a9SSanjoy Das /// Do all the relocation update via allocas and mem2reg
relocationViaAlloca(Function & F,DominatorTree & DT,ArrayRef<Value * > Live,ArrayRef<PartiallyConstructedSafepointRecord> Records)1991d16a9b1fSPhilip Reames static void relocationViaAlloca(
1992285fe84eSIgor Laevsky Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1993b40bd1a9SSanjoy Das ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1994d16a9b1fSPhilip Reames #ifndef NDEBUG
1995a6ebf075SPhilip Reames // record initial number of (static) allocas; we'll check we have the same
1996a6ebf075SPhilip Reames // number when we get done.
1997a6ebf075SPhilip Reames int InitialAllocaNum = 0;
1998135f735aSBenjamin Kramer for (Instruction &I : F.getEntryBlock())
1999135f735aSBenjamin Kramer if (isa<AllocaInst>(I))
2000a6ebf075SPhilip Reames InitialAllocaNum++;
2001d16a9b1fSPhilip Reames #endif
2002d16a9b1fSPhilip Reames
2003d16a9b1fSPhilip Reames // TODO-PERF: change data structures, reserve
200414359ef1SJames Y Knight DenseMap<Value *, AllocaInst *> AllocaMap;
2005d16a9b1fSPhilip Reames SmallVector<AllocaInst *, 200> PromotableAllocas;
2006e0317186SIgor Laevsky // Used later to chack that we have enough allocas to store all values
2007e0317186SIgor Laevsky std::size_t NumRematerializedValues = 0;
2008285fe84eSIgor Laevsky PromotableAllocas.reserve(Live.size());
2009d16a9b1fSPhilip Reames
2010e0317186SIgor Laevsky // Emit alloca for "LiveValue" and record it in "allocaMap" and
2011e0317186SIgor Laevsky // "PromotableAllocas"
20123c1fc768SMatt Arsenault const DataLayout &DL = F.getParent()->getDataLayout();
2013e0317186SIgor Laevsky auto emitAllocaFor = [&](Value *LiveValue) {
20143c1fc768SMatt Arsenault AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
20153c1fc768SMatt Arsenault DL.getAllocaAddrSpace(), "",
2016e0317186SIgor Laevsky F.getEntryBlock().getFirstNonPHI());
2017285fe84eSIgor Laevsky AllocaMap[LiveValue] = Alloca;
2018e0317186SIgor Laevsky PromotableAllocas.push_back(Alloca);
2019e0317186SIgor Laevsky };
2020e0317186SIgor Laevsky
2021b40bd1a9SSanjoy Das // Emit alloca for each live gc pointer
2022b40bd1a9SSanjoy Das for (Value *V : Live)
2023b40bd1a9SSanjoy Das emitAllocaFor(V);
2024e0317186SIgor Laevsky
2025b40bd1a9SSanjoy Das // Emit allocas for rematerialized values
2026b40bd1a9SSanjoy Das for (const auto &Info : Records)
2027e0317186SIgor Laevsky for (auto RematerializedValuePair : Info.RematerializedValues) {
2028e0317186SIgor Laevsky Value *OriginalValue = RematerializedValuePair.second;
2029285fe84eSIgor Laevsky if (AllocaMap.count(OriginalValue) != 0)
2030e0317186SIgor Laevsky continue;
2031e0317186SIgor Laevsky
2032e0317186SIgor Laevsky emitAllocaFor(OriginalValue);
2033e0317186SIgor Laevsky ++NumRematerializedValues;
2034e0317186SIgor Laevsky }
2035d16a9b1fSPhilip Reames
2036d16a9b1fSPhilip Reames // The next two loops are part of the same conceptual operation. We need to
2037d16a9b1fSPhilip Reames // insert a store to the alloca after the original def and at each
2038d16a9b1fSPhilip Reames // redefinition. We need to insert a load before each use. These are split
2039d16a9b1fSPhilip Reames // into distinct loops for performance reasons.
2040d16a9b1fSPhilip Reames
2041b40bd1a9SSanjoy Das // Update gc pointer after each statepoint: either store a relocated value or
2042b40bd1a9SSanjoy Das // null (if no relocated value was found for this gc pointer and it is not a
2043b40bd1a9SSanjoy Das // gc_result). This must happen before we update the statepoint with load of
2044b40bd1a9SSanjoy Das // alloca otherwise we lose the link between statepoint and old def.
2045b40bd1a9SSanjoy Das for (const auto &Info : Records) {
2046285fe84eSIgor Laevsky Value *Statepoint = Info.StatepointToken;
2047d16a9b1fSPhilip Reames
2048d16a9b1fSPhilip Reames // This will be used for consistency check
2049285fe84eSIgor Laevsky DenseSet<Value *> VisitedLiveValues;
2050d16a9b1fSPhilip Reames
2051d16a9b1fSPhilip Reames // Insert stores for normal statepoint gc relocates
2052285fe84eSIgor Laevsky insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
2053d16a9b1fSPhilip Reames
2054d16a9b1fSPhilip Reames // In case if it was invoke statepoint
2055d16a9b1fSPhilip Reames // we will insert stores for exceptional path gc relocates.
20560a3240f4SPhilip Reames if (isa<InvokeInst>(Statepoint)) {
2057285fe84eSIgor Laevsky insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
2058285fe84eSIgor Laevsky VisitedLiveValues);
2059d16a9b1fSPhilip Reames }
2060d16a9b1fSPhilip Reames
2061e0317186SIgor Laevsky // Do similar thing with rematerialized values
2062285fe84eSIgor Laevsky insertRematerializationStores(Info.RematerializedValues, AllocaMap,
2063285fe84eSIgor Laevsky VisitedLiveValues);
2064e0317186SIgor Laevsky
2065e73300b9SPhilip Reames if (ClobberNonLive) {
2066df005cbeSBenjamin Kramer // As a debugging aid, pretend that an unrelocated pointer becomes null at
2067e73300b9SPhilip Reames // the gc.statepoint. This will turn some subtle GC problems into
2068e73300b9SPhilip Reames // slightly easier to debug SEGVs. Note that on large IR files with
2069e73300b9SPhilip Reames // lots of gc.statepoints this is extremely costly both memory and time
2070e73300b9SPhilip Reames // wise.
2071fa2fcf17SPhilip Reames SmallVector<AllocaInst *, 64> ToClobber;
2072285fe84eSIgor Laevsky for (auto Pair : AllocaMap) {
2073fa2fcf17SPhilip Reames Value *Def = Pair.first;
207414359ef1SJames Y Knight AllocaInst *Alloca = Pair.second;
2075d16a9b1fSPhilip Reames
2076d16a9b1fSPhilip Reames // This value was relocated
2077285fe84eSIgor Laevsky if (VisitedLiveValues.count(Def)) {
2078d16a9b1fSPhilip Reames continue;
2079d16a9b1fSPhilip Reames }
2080fa2fcf17SPhilip Reames ToClobber.push_back(Alloca);
2081d16a9b1fSPhilip Reames }
2082fa2fcf17SPhilip Reames
2083fa2fcf17SPhilip Reames auto InsertClobbersAt = [&](Instruction *IP) {
2084fa2fcf17SPhilip Reames for (auto *AI : ToClobber) {
208590c44491SEduard Burtescu auto PT = cast<PointerType>(AI->getAllocatedType());
2086fa2fcf17SPhilip Reames Constant *CPN = ConstantPointerNull::get(PT);
208711aa3707SEli Friedman new StoreInst(CPN, AI, IP);
2088fa2fcf17SPhilip Reames }
2089fa2fcf17SPhilip Reames };
2090fa2fcf17SPhilip Reames
2091fa2fcf17SPhilip Reames // Insert the clobbering stores. These may get intermixed with the
2092fa2fcf17SPhilip Reames // gc.results and gc.relocates, but that's fine.
2093fa2fcf17SPhilip Reames if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
2094be4d8cbaSDuncan P. N. Exon Smith InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
2095be4d8cbaSDuncan P. N. Exon Smith InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
209682ad7877SDavid Blaikie } else {
2097b40bd1a9SSanjoy Das InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
209882ad7877SDavid Blaikie }
2099e73300b9SPhilip Reames }
2100d16a9b1fSPhilip Reames }
2101b40bd1a9SSanjoy Das
2102b40bd1a9SSanjoy Das // Update use with load allocas and add store for gc_relocated.
2103285fe84eSIgor Laevsky for (auto Pair : AllocaMap) {
2104285fe84eSIgor Laevsky Value *Def = Pair.first;
210514359ef1SJames Y Knight AllocaInst *Alloca = Pair.second;
2106d16a9b1fSPhilip Reames
2107b40bd1a9SSanjoy Das // We pre-record the uses of allocas so that we dont have to worry about
2108b40bd1a9SSanjoy Das // later update that changes the user information..
2109b40bd1a9SSanjoy Das
2110285fe84eSIgor Laevsky SmallVector<Instruction *, 20> Uses;
2111d16a9b1fSPhilip Reames // PERF: trade a linear scan for repeated reallocation
2112e0b5f86bSVedant Kumar Uses.reserve(Def->getNumUses());
2113285fe84eSIgor Laevsky for (User *U : Def->users()) {
2114d16a9b1fSPhilip Reames if (!isa<ConstantExpr>(U)) {
2115d16a9b1fSPhilip Reames // If the def has a ConstantExpr use, then the def is either a
2116d16a9b1fSPhilip Reames // ConstantExpr use itself or null. In either case
2117d16a9b1fSPhilip Reames // (recursively in the first, directly in the second), the oop
2118d16a9b1fSPhilip Reames // it is ultimately dependent on is null and this particular
2119d16a9b1fSPhilip Reames // use does not need to be fixed up.
2120285fe84eSIgor Laevsky Uses.push_back(cast<Instruction>(U));
2121d16a9b1fSPhilip Reames }
2122d16a9b1fSPhilip Reames }
2123d16a9b1fSPhilip Reames
21240cac726aSFangrui Song llvm::sort(Uses);
2125285fe84eSIgor Laevsky auto Last = std::unique(Uses.begin(), Uses.end());
2126285fe84eSIgor Laevsky Uses.erase(Last, Uses.end());
2127d16a9b1fSPhilip Reames
2128285fe84eSIgor Laevsky for (Instruction *Use : Uses) {
2129285fe84eSIgor Laevsky if (isa<PHINode>(Use)) {
2130285fe84eSIgor Laevsky PHINode *Phi = cast<PHINode>(Use);
2131285fe84eSIgor Laevsky for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
2132285fe84eSIgor Laevsky if (Def == Phi->getIncomingValue(i)) {
213314359ef1SJames Y Knight LoadInst *Load =
213414359ef1SJames Y Knight new LoadInst(Alloca->getAllocatedType(), Alloca, "",
213514359ef1SJames Y Knight Phi->getIncomingBlock(i)->getTerminator());
2136285fe84eSIgor Laevsky Phi->setIncomingValue(i, Load);
2137d16a9b1fSPhilip Reames }
2138d16a9b1fSPhilip Reames }
2139d16a9b1fSPhilip Reames } else {
214014359ef1SJames Y Knight LoadInst *Load =
214114359ef1SJames Y Knight new LoadInst(Alloca->getAllocatedType(), Alloca, "", Use);
2142285fe84eSIgor Laevsky Use->replaceUsesOfWith(Def, Load);
2143d16a9b1fSPhilip Reames }
2144d16a9b1fSPhilip Reames }
2145d16a9b1fSPhilip Reames
2146b40bd1a9SSanjoy Das // Emit store for the initial gc value. Store must be inserted after load,
2147b40bd1a9SSanjoy Das // otherwise store will be in alloca's use list and an extra load will be
2148b40bd1a9SSanjoy Das // inserted before it.
214911aa3707SEli Friedman StoreInst *Store = new StoreInst(Def, Alloca, /*volatile*/ false,
215011aa3707SEli Friedman DL.getABITypeAlign(Def->getType()));
2151285fe84eSIgor Laevsky if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
2152285fe84eSIgor Laevsky if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
2153edb12a83SChandler Carruth // InvokeInst is a terminator so the store need to be inserted into its
2154edb12a83SChandler Carruth // normal destination block.
2155285fe84eSIgor Laevsky BasicBlock *NormalDest = Invoke->getNormalDest();
2156285fe84eSIgor Laevsky Store->insertBefore(NormalDest->getFirstNonPHI());
21576da37857SPhilip Reames } else {
2158285fe84eSIgor Laevsky assert(!Inst->isTerminator() &&
2159edb12a83SChandler Carruth "The only terminator that can produce a value is "
21606da37857SPhilip Reames "InvokeInst which is handled above.");
2161285fe84eSIgor Laevsky Store->insertAfter(Inst);
21626da37857SPhilip Reames }
2163d16a9b1fSPhilip Reames } else {
2164285fe84eSIgor Laevsky assert(isa<Argument>(Def));
2165285fe84eSIgor Laevsky Store->insertAfter(cast<Instruction>(Alloca));
2166d16a9b1fSPhilip Reames }
2167d16a9b1fSPhilip Reames }
2168d16a9b1fSPhilip Reames
2169285fe84eSIgor Laevsky assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
2170d16a9b1fSPhilip Reames "we must have the same allocas with lives");
217146776f75SMartin Storsjö (void) NumRematerializedValues;
2172d16a9b1fSPhilip Reames if (!PromotableAllocas.empty()) {
2173b40bd1a9SSanjoy Das // Apply mem2reg to promote alloca to SSA
2174d16a9b1fSPhilip Reames PromoteMemToReg(PromotableAllocas, DT);
2175d16a9b1fSPhilip Reames }
2176d16a9b1fSPhilip Reames
2177d16a9b1fSPhilip Reames #ifndef NDEBUG
2178b40bd1a9SSanjoy Das for (auto &I : F.getEntryBlock())
2179b40bd1a9SSanjoy Das if (isa<AllocaInst>(I))
2180a6ebf075SPhilip Reames InitialAllocaNum--;
2181a6ebf075SPhilip Reames assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
2182d16a9b1fSPhilip Reames #endif
2183d16a9b1fSPhilip Reames }
2184d16a9b1fSPhilip Reames
2185d16a9b1fSPhilip Reames /// Implement a unique function which doesn't require we sort the input
2186d16a9b1fSPhilip Reames /// vector. Doing so has the effect of changing the output of a couple of
2187d16a9b1fSPhilip Reames /// tests in ways which make them less useful in testing fused safepoints.
unique_unsorted(SmallVectorImpl<T> & Vec)2188d2b66464SPhilip Reames template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
2189258ea0dbSBenjamin Kramer SmallSet<T, 8> Seen;
2190b6211167SKazu Hirata erase_if(Vec, [&](const T &V) { return !Seen.insert(V).second; });
2191d16a9b1fSPhilip Reames }
2192d16a9b1fSPhilip Reames
2193d16a9b1fSPhilip Reames /// Insert holders so that each Value is obviously live through the entire
2194f209a153SPhilip Reames /// lifetime of the call.
insertUseHolderAfter(CallBase * Call,const ArrayRef<Value * > Values,SmallVectorImpl<CallInst * > & Holders)21953160734aSChandler Carruth static void insertUseHolderAfter(CallBase *Call, const ArrayRef<Value *> Values,
2196f209a153SPhilip Reames SmallVectorImpl<CallInst *> &Holders) {
219721142752SPhilip Reames if (Values.empty())
219821142752SPhilip Reames // No values to hold live, might as well not insert the empty holder
219921142752SPhilip Reames return;
220021142752SPhilip Reames
22013160734aSChandler Carruth Module *M = Call->getModule();
2202f209a153SPhilip Reames // Use a dummy vararg function to actually hold the values live
220313680223SJames Y Knight FunctionCallee Func = M->getOrInsertFunction(
220413680223SJames Y Knight "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
22053160734aSChandler Carruth if (isa<CallInst>(Call)) {
2206d16a9b1fSPhilip Reames // For call safepoints insert dummy calls right after safepoint
22073160734aSChandler Carruth Holders.push_back(
22083160734aSChandler Carruth CallInst::Create(Func, Values, "", &*++Call->getIterator()));
2209f209a153SPhilip Reames return;
2210f209a153SPhilip Reames }
2211d16a9b1fSPhilip Reames // For invoke safepooints insert dummy calls both in normal and
2212d16a9b1fSPhilip Reames // exceptional destination blocks
22133160734aSChandler Carruth auto *II = cast<InvokeInst>(Call);
2214f209a153SPhilip Reames Holders.push_back(CallInst::Create(
2215be4d8cbaSDuncan P. N. Exon Smith Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
2216f209a153SPhilip Reames Holders.push_back(CallInst::Create(
2217be4d8cbaSDuncan P. N. Exon Smith Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
2218d16a9b1fSPhilip Reames }
2219d16a9b1fSPhilip Reames
findLiveReferences(Function & F,DominatorTree & DT,ArrayRef<CallBase * > toUpdate,MutableArrayRef<struct PartiallyConstructedSafepointRecord> records)2220d16a9b1fSPhilip Reames static void findLiveReferences(
22213160734aSChandler Carruth Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
2222d2b66464SPhilip Reames MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
2223df1ef08cSPhilip Reames GCPtrLivenessData OriginalLivenessData;
2224df1ef08cSPhilip Reames computeLiveInValues(DT, F, OriginalLivenessData);
2225d16a9b1fSPhilip Reames for (size_t i = 0; i < records.size(); i++) {
2226d16a9b1fSPhilip Reames struct PartiallyConstructedSafepointRecord &info = records[i];
2227a3244874SSanjoy Das analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
2228d16a9b1fSPhilip Reames }
2229d16a9b1fSPhilip Reames }
2230d16a9b1fSPhilip Reames
2231e0317186SIgor Laevsky // Helper function for the "rematerializeLiveValues". It walks use chain
22328cd7de1dSAnna Thomas // starting from the "CurrentValue" until it reaches the root of the chain, i.e.
22338cd7de1dSAnna Thomas // the base or a value it cannot process. Only "simple" values are processed
22348cd7de1dSAnna Thomas // (currently it is GEP's and casts). The returned root is examined by the
22358cd7de1dSAnna Thomas // callers of findRematerializableChainToBasePointer. Fills "ChainToBase" array
22368cd7de1dSAnna Thomas // with all visited values.
findRematerializableChainToBasePointer(SmallVectorImpl<Instruction * > & ChainToBase,Value * CurrentValue)22378cd7de1dSAnna Thomas static Value* findRematerializableChainToBasePointer(
2238e0317186SIgor Laevsky SmallVectorImpl<Instruction*> &ChainToBase,
22398cd7de1dSAnna Thomas Value *CurrentValue) {
2240e0317186SIgor Laevsky if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2241e0317186SIgor Laevsky ChainToBase.push_back(GEP);
2242e0317186SIgor Laevsky return findRematerializableChainToBasePointer(ChainToBase,
22438cd7de1dSAnna Thomas GEP->getPointerOperand());
2244e0317186SIgor Laevsky }
2245e0317186SIgor Laevsky
2246e0317186SIgor Laevsky if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2247e0317186SIgor Laevsky if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
22488cd7de1dSAnna Thomas return CI;
2249e0317186SIgor Laevsky
2250e0317186SIgor Laevsky ChainToBase.push_back(CI);
22519db5b93fSManuel Jacob return findRematerializableChainToBasePointer(ChainToBase,
22528cd7de1dSAnna Thomas CI->getOperand(0));
2253e0317186SIgor Laevsky }
2254e0317186SIgor Laevsky
22558cd7de1dSAnna Thomas // We have reached the root of the chain, which is either equal to the base or
22568cd7de1dSAnna Thomas // is the first unsupported value along the use chain.
22578cd7de1dSAnna Thomas return CurrentValue;
2258e0317186SIgor Laevsky }
2259e0317186SIgor Laevsky
2260e0317186SIgor Laevsky // Helper function for the "rematerializeLiveValues". Compute cost of the use
2261e0317186SIgor Laevsky // chain we are going to rematerialize.
22624cd48535SDavid Sherwood static InstructionCost
chainToBasePointerCost(SmallVectorImpl<Instruction * > & Chain,TargetTransformInfo & TTI)2263e0317186SIgor Laevsky chainToBasePointerCost(SmallVectorImpl<Instruction *> &Chain,
2264e0317186SIgor Laevsky TargetTransformInfo &TTI) {
22654cd48535SDavid Sherwood InstructionCost Cost = 0;
2266e0317186SIgor Laevsky
2267e0317186SIgor Laevsky for (Instruction *Instr : Chain) {
2268e0317186SIgor Laevsky if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2269e0317186SIgor Laevsky assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2270e0317186SIgor Laevsky "non noop cast is found during rematerialization");
2271e0317186SIgor Laevsky
2272e0317186SIgor Laevsky Type *SrcTy = CI->getOperand(0)->getType();
227340574fefSSam Parker Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy,
227460280e98SDavid Green TTI::getCastContextHint(CI),
227560280e98SDavid Green TargetTransformInfo::TCK_SizeAndLatency, CI);
2276e0317186SIgor Laevsky
2277e0317186SIgor Laevsky } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2278e0317186SIgor Laevsky // Cost of the address calculation
227919eb0310SEduard Burtescu Type *ValTy = GEP->getSourceElementType();
2280e0317186SIgor Laevsky Cost += TTI.getAddressComputationCost(ValTy);
2281e0317186SIgor Laevsky
2282e0317186SIgor Laevsky // And cost of the GEP itself
2283e0317186SIgor Laevsky // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2284e0317186SIgor Laevsky // allowed for the external usage)
2285e0317186SIgor Laevsky if (!GEP->hasAllConstantIndices())
2286e0317186SIgor Laevsky Cost += 2;
2287e0317186SIgor Laevsky
2288e0317186SIgor Laevsky } else {
2289f209649dSHiroshi Inoue llvm_unreachable("unsupported instruction type during rematerialization");
2290e0317186SIgor Laevsky }
2291e0317186SIgor Laevsky }
2292e0317186SIgor Laevsky
2293e0317186SIgor Laevsky return Cost;
2294e0317186SIgor Laevsky }
2295e0317186SIgor Laevsky
AreEquivalentPhiNodes(PHINode & OrigRootPhi,PHINode & AlternateRootPhi)22968cd7de1dSAnna Thomas static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
22978cd7de1dSAnna Thomas unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
22988cd7de1dSAnna Thomas if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
22998cd7de1dSAnna Thomas OrigRootPhi.getParent() != AlternateRootPhi.getParent())
23008cd7de1dSAnna Thomas return false;
23018cd7de1dSAnna Thomas // Map of incoming values and their corresponding basic blocks of
23028cd7de1dSAnna Thomas // OrigRootPhi.
23038cd7de1dSAnna Thomas SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
23048cd7de1dSAnna Thomas for (unsigned i = 0; i < PhiNum; i++)
23058cd7de1dSAnna Thomas CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
23068cd7de1dSAnna Thomas OrigRootPhi.getIncomingBlock(i);
23078cd7de1dSAnna Thomas
23088cd7de1dSAnna Thomas // Both current and base PHIs should have same incoming values and
23098cd7de1dSAnna Thomas // the same basic blocks corresponding to the incoming values.
23108cd7de1dSAnna Thomas for (unsigned i = 0; i < PhiNum; i++) {
23118cd7de1dSAnna Thomas auto CIVI =
23128cd7de1dSAnna Thomas CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
23138cd7de1dSAnna Thomas if (CIVI == CurrentIncomingValues.end())
23148cd7de1dSAnna Thomas return false;
23158cd7de1dSAnna Thomas BasicBlock *CurrentIncomingBB = CIVI->second;
23168cd7de1dSAnna Thomas if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
23178cd7de1dSAnna Thomas return false;
23188cd7de1dSAnna Thomas }
23198cd7de1dSAnna Thomas return true;
23208cd7de1dSAnna Thomas }
23218cd7de1dSAnna Thomas
232266f1c6fcSSerguei Katkov // Find derived pointers that can be recomputed cheap enough and fill
232366f1c6fcSSerguei Katkov // RematerizationCandidates with such candidates.
232466f1c6fcSSerguei Katkov static void
findRematerializationCandidates(PointerToBaseTy PointerToBase,RematCandTy & RematerizationCandidates,TargetTransformInfo & TTI)232566f1c6fcSSerguei Katkov findRematerializationCandidates(PointerToBaseTy PointerToBase,
232666f1c6fcSSerguei Katkov RematCandTy &RematerizationCandidates,
2327e0317186SIgor Laevsky TargetTransformInfo &TTI) {
2328ff7d4fadSAaron Ballman const unsigned int ChainLengthThreshold = 10;
2329e0317186SIgor Laevsky
233066f1c6fcSSerguei Katkov for (auto P2B : PointerToBase) {
233166f1c6fcSSerguei Katkov auto *Derived = P2B.first;
233266f1c6fcSSerguei Katkov auto *Base = P2B.second;
233366f1c6fcSSerguei Katkov // Consider only derived pointers.
233466f1c6fcSSerguei Katkov if (Derived == Base)
233566f1c6fcSSerguei Katkov continue;
2336e0317186SIgor Laevsky
233766f1c6fcSSerguei Katkov // For each live pointer find its defining chain.
2338e0317186SIgor Laevsky SmallVector<Instruction *, 3> ChainToBase;
23398cd7de1dSAnna Thomas Value *RootOfChain =
234066f1c6fcSSerguei Katkov findRematerializableChainToBasePointer(ChainToBase, Derived);
23418cd7de1dSAnna Thomas
2342e0317186SIgor Laevsky // Nothing to do, or chain is too long
23438cd7de1dSAnna Thomas if ( ChainToBase.size() == 0 ||
2344e0317186SIgor Laevsky ChainToBase.size() > ChainLengthThreshold)
2345e0317186SIgor Laevsky continue;
2346e0317186SIgor Laevsky
23478cd7de1dSAnna Thomas // Handle the scenario where the RootOfChain is not equal to the
23488cd7de1dSAnna Thomas // Base Value, but they are essentially the same phi values.
234966f1c6fcSSerguei Katkov if (RootOfChain != PointerToBase[Derived]) {
23508cd7de1dSAnna Thomas PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
235166f1c6fcSSerguei Katkov PHINode *AlternateRootPhi = dyn_cast<PHINode>(PointerToBase[Derived]);
23528cd7de1dSAnna Thomas if (!OrigRootPhi || !AlternateRootPhi)
23538cd7de1dSAnna Thomas continue;
23548cd7de1dSAnna Thomas // PHI nodes that have the same incoming values, and belonging to the same
23558cd7de1dSAnna Thomas // basic blocks are essentially the same SSA value. When the original phi
23568cd7de1dSAnna Thomas // has incoming values with different base pointers, the original phi is
23578cd7de1dSAnna Thomas // marked as conflict, and an additional `AlternateRootPhi` with the same
23588cd7de1dSAnna Thomas // incoming values get generated by the findBasePointer function. We need
23598cd7de1dSAnna Thomas // to identify the newly generated AlternateRootPhi (.base version of phi)
23608cd7de1dSAnna Thomas // and RootOfChain (the original phi node itself) are the same, so that we
23618cd7de1dSAnna Thomas // can rematerialize the gep and casts. This is a workaround for the
2362ef1c2ba2SHiroshi Inoue // deficiency in the findBasePointer algorithm.
23638cd7de1dSAnna Thomas if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
23648cd7de1dSAnna Thomas continue;
23658cd7de1dSAnna Thomas }
236666f1c6fcSSerguei Katkov // Compute cost of this chain.
23674cd48535SDavid Sherwood InstructionCost Cost = chainToBasePointerCost(ChainToBase, TTI);
2368e0317186SIgor Laevsky // TODO: We can also account for cases when we will be able to remove some
2369e0317186SIgor Laevsky // of the rematerialized values by later optimization passes. I.e if
2370e0317186SIgor Laevsky // we rematerialized several intersecting chains. Or if original values
2371e0317186SIgor Laevsky // don't have any uses besides this statepoint.
2372e0317186SIgor Laevsky
237366f1c6fcSSerguei Katkov // Ok, there is a candidate.
237466f1c6fcSSerguei Katkov RematerizlizationCandidateRecord Record;
237566f1c6fcSSerguei Katkov Record.ChainToBase = ChainToBase;
237666f1c6fcSSerguei Katkov Record.RootOfChain = RootOfChain;
237766f1c6fcSSerguei Katkov Record.Cost = Cost;
237866f1c6fcSSerguei Katkov RematerizationCandidates.insert({ Derived, Record });
237966f1c6fcSSerguei Katkov }
238066f1c6fcSSerguei Katkov }
238166f1c6fcSSerguei Katkov
238266f1c6fcSSerguei Katkov // From the statepoint live set pick values that are cheaper to recompute then
238366f1c6fcSSerguei Katkov // to relocate. Remove this values from the live set, rematerialize them after
238466f1c6fcSSerguei Katkov // statepoint and record them in "Info" structure. Note that similar to
238566f1c6fcSSerguei Katkov // relocated values we don't do any user adjustments here.
rematerializeLiveValues(CallBase * Call,PartiallyConstructedSafepointRecord & Info,PointerToBaseTy & PointerToBase,RematCandTy & RematerizationCandidates,TargetTransformInfo & TTI)238666f1c6fcSSerguei Katkov static void rematerializeLiveValues(CallBase *Call,
238766f1c6fcSSerguei Katkov PartiallyConstructedSafepointRecord &Info,
238866f1c6fcSSerguei Katkov PointerToBaseTy &PointerToBase,
238966f1c6fcSSerguei Katkov RematCandTy &RematerizationCandidates,
239066f1c6fcSSerguei Katkov TargetTransformInfo &TTI) {
239166f1c6fcSSerguei Katkov // Record values we are going to delete from this statepoint live set.
239266f1c6fcSSerguei Katkov // We can not di this in following loop due to iterator invalidation.
239366f1c6fcSSerguei Katkov SmallVector<Value *, 32> LiveValuesToBeDeleted;
239466f1c6fcSSerguei Katkov
239566f1c6fcSSerguei Katkov for (Value *LiveValue : Info.LiveSet) {
239666f1c6fcSSerguei Katkov auto It = RematerizationCandidates.find(LiveValue);
239766f1c6fcSSerguei Katkov if (It == RematerizationCandidates.end())
239866f1c6fcSSerguei Katkov continue;
239966f1c6fcSSerguei Katkov
240066f1c6fcSSerguei Katkov RematerizlizationCandidateRecord &Record = It->second;
240166f1c6fcSSerguei Katkov
240266f1c6fcSSerguei Katkov InstructionCost Cost = Record.Cost;
2403e0317186SIgor Laevsky // For invokes we need to rematerialize each chain twice - for normal and
2404e0317186SIgor Laevsky // for unwind basic blocks. Model this by multiplying cost by two.
240566f1c6fcSSerguei Katkov if (isa<InvokeInst>(Call))
2406e0317186SIgor Laevsky Cost *= 2;
240766f1c6fcSSerguei Katkov
240866f1c6fcSSerguei Katkov // If it's too expensive - skip it.
2409e0317186SIgor Laevsky if (Cost >= RematerializationThreshold)
2410e0317186SIgor Laevsky continue;
2411e0317186SIgor Laevsky
2412e0317186SIgor Laevsky // Remove value from the live set
2413e0317186SIgor Laevsky LiveValuesToBeDeleted.push_back(LiveValue);
2414e0317186SIgor Laevsky
241566f1c6fcSSerguei Katkov // Clone instructions and record them inside "Info" structure.
2416e0317186SIgor Laevsky
241766f1c6fcSSerguei Katkov // For each live pointer find get its defining chain.
241866f1c6fcSSerguei Katkov SmallVector<Instruction *, 3> ChainToBase = Record.ChainToBase;
241966f1c6fcSSerguei Katkov // Walk backwards to visit top-most instructions first.
2420e0317186SIgor Laevsky std::reverse(ChainToBase.begin(), ChainToBase.end());
2421e0317186SIgor Laevsky
2422e0317186SIgor Laevsky // Utility function which clones all instructions from "ChainToBase"
2423e0317186SIgor Laevsky // and inserts them before "InsertBefore". Returns rematerialized value
2424e0317186SIgor Laevsky // which should be used after statepoint.
242582c3717fSAnna Thomas auto rematerializeChain = [&ChainToBase](
242682c3717fSAnna Thomas Instruction *InsertBefore, Value *RootOfChain, Value *AlternateLiveBase) {
2427e0317186SIgor Laevsky Instruction *LastClonedValue = nullptr;
2428e0317186SIgor Laevsky Instruction *LastValue = nullptr;
2429e0317186SIgor Laevsky for (Instruction *Instr: ChainToBase) {
2430bb703e89SHiroshi Inoue // Only GEP's and casts are supported as we need to be careful to not
2431e0317186SIgor Laevsky // introduce any new uses of pointers not in the liveset.
2432e0317186SIgor Laevsky // Note that it's fine to introduce new uses of pointers which were
2433e0317186SIgor Laevsky // otherwise not used after this statepoint.
2434e0317186SIgor Laevsky assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2435e0317186SIgor Laevsky
2436e0317186SIgor Laevsky Instruction *ClonedValue = Instr->clone();
2437e0317186SIgor Laevsky ClonedValue->insertBefore(InsertBefore);
2438e0317186SIgor Laevsky ClonedValue->setName(Instr->getName() + ".remat");
2439e0317186SIgor Laevsky
2440e0317186SIgor Laevsky // If it is not first instruction in the chain then it uses previously
2441e0317186SIgor Laevsky // cloned value. We should update it to use cloned value.
2442e0317186SIgor Laevsky if (LastClonedValue) {
2443e0317186SIgor Laevsky assert(LastValue);
2444e0317186SIgor Laevsky ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2445e0317186SIgor Laevsky #ifndef NDEBUG
244682c3717fSAnna Thomas for (auto OpValue : ClonedValue->operand_values()) {
2447d83f6976SIgor Laevsky // Assert that cloned instruction does not use any instructions from
2448d83f6976SIgor Laevsky // this chain other than LastClonedValue
24490d955d0bSDavid Majnemer assert(!is_contained(ChainToBase, OpValue) &&
2450d83f6976SIgor Laevsky "incorrect use in rematerialization chain");
245182c3717fSAnna Thomas // Assert that the cloned instruction does not use the RootOfChain
245282c3717fSAnna Thomas // or the AlternateLiveBase.
245382c3717fSAnna Thomas assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
2454e0317186SIgor Laevsky }
2455e0317186SIgor Laevsky #endif
245682c3717fSAnna Thomas } else {
245782c3717fSAnna Thomas // For the first instruction, replace the use of unrelocated base i.e.
245882c3717fSAnna Thomas // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
245982c3717fSAnna Thomas // live set. They have been proved to be the same PHI nodes. Note
246082c3717fSAnna Thomas // that the *only* use of the RootOfChain in the ChainToBase list is
246182c3717fSAnna Thomas // the first Value in the list.
246282c3717fSAnna Thomas if (RootOfChain != AlternateLiveBase)
246382c3717fSAnna Thomas ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
2464e0317186SIgor Laevsky }
2465e0317186SIgor Laevsky
2466e0317186SIgor Laevsky LastClonedValue = ClonedValue;
2467e0317186SIgor Laevsky LastValue = Instr;
2468e0317186SIgor Laevsky }
2469e0317186SIgor Laevsky assert(LastClonedValue);
2470e0317186SIgor Laevsky return LastClonedValue;
2471e0317186SIgor Laevsky };
2472e0317186SIgor Laevsky
2473e0317186SIgor Laevsky // Different cases for calls and invokes. For invokes we need to clone
2474e0317186SIgor Laevsky // instructions both on normal and unwind path.
24753160734aSChandler Carruth if (isa<CallInst>(Call)) {
24763160734aSChandler Carruth Instruction *InsertBefore = Call->getNextNode();
2477e0317186SIgor Laevsky assert(InsertBefore);
247882c3717fSAnna Thomas Instruction *RematerializedValue = rematerializeChain(
247966f1c6fcSSerguei Katkov InsertBefore, Record.RootOfChain, PointerToBase[LiveValue]);
2480e0317186SIgor Laevsky Info.RematerializedValues[RematerializedValue] = LiveValue;
2481e0317186SIgor Laevsky } else {
24823160734aSChandler Carruth auto *Invoke = cast<InvokeInst>(Call);
2483e0317186SIgor Laevsky
2484e0317186SIgor Laevsky Instruction *NormalInsertBefore =
2485be4d8cbaSDuncan P. N. Exon Smith &*Invoke->getNormalDest()->getFirstInsertionPt();
2486e0317186SIgor Laevsky Instruction *UnwindInsertBefore =
2487be4d8cbaSDuncan P. N. Exon Smith &*Invoke->getUnwindDest()->getFirstInsertionPt();
2488e0317186SIgor Laevsky
248982c3717fSAnna Thomas Instruction *NormalRematerializedValue = rematerializeChain(
249066f1c6fcSSerguei Katkov NormalInsertBefore, Record.RootOfChain, PointerToBase[LiveValue]);
249182c3717fSAnna Thomas Instruction *UnwindRematerializedValue = rematerializeChain(
249266f1c6fcSSerguei Katkov UnwindInsertBefore, Record.RootOfChain, PointerToBase[LiveValue]);
2493e0317186SIgor Laevsky
2494e0317186SIgor Laevsky Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2495e0317186SIgor Laevsky Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2496e0317186SIgor Laevsky }
2497e0317186SIgor Laevsky }
2498e0317186SIgor Laevsky
2499e0317186SIgor Laevsky // Remove rematerializaed values from the live set
2500e0317186SIgor Laevsky for (auto LiveValue: LiveValuesToBeDeleted) {
2501fb1811d3SIgor Laevsky Info.LiveSet.remove(LiveValue);
2502e0317186SIgor Laevsky }
2503e0317186SIgor Laevsky }
2504e0317186SIgor Laevsky
inlineGetBaseAndOffset(Function & F,SmallVectorImpl<CallInst * > & Intrinsics,DefiningValueMapTy & DVCache,IsKnownBaseMapTy & KnownBases)25054d26f41fSYevgeny Rouban static bool inlineGetBaseAndOffset(Function &F,
250688024a72SYevgeny Rouban SmallVectorImpl<CallInst *> &Intrinsics,
25071da42c9fSDmitry Makogon DefiningValueMapTy &DVCache,
25081da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
25094d26f41fSYevgeny Rouban auto &Context = F.getContext();
25104d26f41fSYevgeny Rouban auto &DL = F.getParent()->getDataLayout();
25114d26f41fSYevgeny Rouban bool Changed = false;
25124d26f41fSYevgeny Rouban
25134d26f41fSYevgeny Rouban for (auto *Callsite : Intrinsics)
25144d26f41fSYevgeny Rouban switch (Callsite->getIntrinsicID()) {
25154d26f41fSYevgeny Rouban case Intrinsic::experimental_gc_get_pointer_base: {
25164d26f41fSYevgeny Rouban Changed = true;
25171da42c9fSDmitry Makogon Value *Base =
25181da42c9fSDmitry Makogon findBasePointer(Callsite->getOperand(0), DVCache, KnownBases);
25194d26f41fSYevgeny Rouban assert(!DVCache.count(Callsite));
25204d26f41fSYevgeny Rouban auto *BaseBC = IRBuilder<>(Callsite).CreateBitCast(
25214d26f41fSYevgeny Rouban Base, Callsite->getType(), suffixed_name_or(Base, ".cast", ""));
25224d26f41fSYevgeny Rouban if (BaseBC != Base)
25234d26f41fSYevgeny Rouban DVCache[BaseBC] = Base;
25244d26f41fSYevgeny Rouban Callsite->replaceAllUsesWith(BaseBC);
25254d26f41fSYevgeny Rouban if (!BaseBC->hasName())
25264d26f41fSYevgeny Rouban BaseBC->takeName(Callsite);
25274d26f41fSYevgeny Rouban Callsite->eraseFromParent();
25284d26f41fSYevgeny Rouban break;
25294d26f41fSYevgeny Rouban }
25304d26f41fSYevgeny Rouban case Intrinsic::experimental_gc_get_pointer_offset: {
25314d26f41fSYevgeny Rouban Changed = true;
25324d26f41fSYevgeny Rouban Value *Derived = Callsite->getOperand(0);
25331da42c9fSDmitry Makogon Value *Base = findBasePointer(Derived, DVCache, KnownBases);
25344d26f41fSYevgeny Rouban assert(!DVCache.count(Callsite));
25354d26f41fSYevgeny Rouban unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
25364d26f41fSYevgeny Rouban unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
25374d26f41fSYevgeny Rouban IRBuilder<> Builder(Callsite);
25384d26f41fSYevgeny Rouban Value *BaseInt =
25394d26f41fSYevgeny Rouban Builder.CreatePtrToInt(Base, Type::getIntNTy(Context, IntPtrSize),
25404d26f41fSYevgeny Rouban suffixed_name_or(Base, ".int", ""));
25414d26f41fSYevgeny Rouban Value *DerivedInt =
25424d26f41fSYevgeny Rouban Builder.CreatePtrToInt(Derived, Type::getIntNTy(Context, IntPtrSize),
25434d26f41fSYevgeny Rouban suffixed_name_or(Derived, ".int", ""));
25444d26f41fSYevgeny Rouban Value *Offset = Builder.CreateSub(DerivedInt, BaseInt);
25454d26f41fSYevgeny Rouban Callsite->replaceAllUsesWith(Offset);
25464d26f41fSYevgeny Rouban Offset->takeName(Callsite);
25474d26f41fSYevgeny Rouban Callsite->eraseFromParent();
25484d26f41fSYevgeny Rouban break;
25494d26f41fSYevgeny Rouban }
25504d26f41fSYevgeny Rouban default:
25514d26f41fSYevgeny Rouban llvm_unreachable("Unknown intrinsic");
25524d26f41fSYevgeny Rouban }
25534d26f41fSYevgeny Rouban
25544d26f41fSYevgeny Rouban return Changed;
25554d26f41fSYevgeny Rouban }
25564d26f41fSYevgeny Rouban
insertParsePoints(Function & F,DominatorTree & DT,TargetTransformInfo & TTI,SmallVectorImpl<CallBase * > & ToUpdate,DefiningValueMapTy & DVCache,IsKnownBaseMapTy & KnownBases)2557843fb204SJustin Bogner static bool insertParsePoints(Function &F, DominatorTree &DT,
2558843fb204SJustin Bogner TargetTransformInfo &TTI,
255988024a72SYevgeny Rouban SmallVectorImpl<CallBase *> &ToUpdate,
25601da42c9fSDmitry Makogon DefiningValueMapTy &DVCache,
25611da42c9fSDmitry Makogon IsKnownBaseMapTy &KnownBases) {
2562d16a9b1fSPhilip Reames #ifndef NDEBUG
25639769e97cSZarko Todorovski // Validate the input
25643160734aSChandler Carruth std::set<CallBase *> Uniqued;
2565b40bd1a9SSanjoy Das Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2566b40bd1a9SSanjoy Das assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2567d16a9b1fSPhilip Reames
25683160734aSChandler Carruth for (CallBase *Call : ToUpdate)
25693160734aSChandler Carruth assert(Call->getFunction() == &F);
2570d16a9b1fSPhilip Reames #endif
2571d16a9b1fSPhilip Reames
257269e51caeSPhilip Reames // When inserting gc.relocates for invokes, we need to be able to insert at
257369e51caeSPhilip Reames // the top of the successor blocks. See the comment on
257469e51caeSPhilip Reames // normalForInvokeSafepoint on exactly what is needed. Note that this step
257569e51caeSPhilip Reames // may restructure the CFG.
25763160734aSChandler Carruth for (CallBase *Call : ToUpdate) {
25773160734aSChandler Carruth auto *II = dyn_cast<InvokeInst>(Call);
25783160734aSChandler Carruth if (!II)
2579f209a153SPhilip Reames continue;
2580b40bd1a9SSanjoy Das normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2581b40bd1a9SSanjoy Das normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
258269e51caeSPhilip Reames }
258369e51caeSPhilip Reames
2584d16a9b1fSPhilip Reames // A list of dummy calls added to the IR to keep various values obviously
2585d16a9b1fSPhilip Reames // live in the IR. We'll remove all of these when done.
2586b40bd1a9SSanjoy Das SmallVector<CallInst *, 64> Holders;
2587d16a9b1fSPhilip Reames
2588b70cecd6SPhilip Reames // Insert a dummy call with all of the deopt operands we'll need for the
2589b70cecd6SPhilip Reames // actual safepoint insertion as arguments. This ensures reference operands
2590b70cecd6SPhilip Reames // in the deopt argument list are considered live through the safepoint (and
2591d16a9b1fSPhilip Reames // thus makes sure they get relocated.)
25923160734aSChandler Carruth for (CallBase *Call : ToUpdate) {
2593d16a9b1fSPhilip Reames SmallVector<Value *, 64> DeoptValues;
259425ec1a3eSSanjoy Das
25953160734aSChandler Carruth for (Value *Arg : GetDeoptBundleOperands(Call)) {
25968531d8c4SPhilip Reames assert(!isUnhandledGCPointerType(Arg->getType()) &&
25978531d8c4SPhilip Reames "support for FCA unimplemented");
25988531d8c4SPhilip Reames if (isHandledGCPointerType(Arg->getType()))
2599d16a9b1fSPhilip Reames DeoptValues.push_back(Arg);
2600d16a9b1fSPhilip Reames }
260125ec1a3eSSanjoy Das
26023160734aSChandler Carruth insertUseHolderAfter(Call, DeoptValues, Holders);
2603d16a9b1fSPhilip Reames }
2604d16a9b1fSPhilip Reames
2605b40bd1a9SSanjoy Das SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2606d16a9b1fSPhilip Reames
2607df005cbeSBenjamin Kramer // A) Identify all gc pointers which are statically live at the given call
2608d16a9b1fSPhilip Reames // site.
2609843fb204SJustin Bogner findLiveReferences(F, DT, ToUpdate, Records);
2610d16a9b1fSPhilip Reames
261128c5e1b7SSerguei Katkov /// Global mapping from live pointers to a base-defining-value.
261228c5e1b7SSerguei Katkov PointerToBaseTy PointerToBase;
261328c5e1b7SSerguei Katkov
2614d16a9b1fSPhilip Reames // B) Find the base pointers for each live pointer
2615b40bd1a9SSanjoy Das for (size_t i = 0; i < Records.size(); i++) {
2616b40bd1a9SSanjoy Das PartiallyConstructedSafepointRecord &info = Records[i];
26171da42c9fSDmitry Makogon findBasePointers(DT, DVCache, ToUpdate[i], info, PointerToBase, KnownBases);
261828c5e1b7SSerguei Katkov }
261928c5e1b7SSerguei Katkov if (PrintBasePointers) {
262028c5e1b7SSerguei Katkov errs() << "Base Pairs (w/o Relocation):\n";
262128c5e1b7SSerguei Katkov for (auto &Pair : PointerToBase) {
262228c5e1b7SSerguei Katkov errs() << " derived ";
262328c5e1b7SSerguei Katkov Pair.first->printAsOperand(errs(), false);
262428c5e1b7SSerguei Katkov errs() << " base ";
262528c5e1b7SSerguei Katkov Pair.second->printAsOperand(errs(), false);
262628c5e1b7SSerguei Katkov errs() << "\n";
262728c5e1b7SSerguei Katkov ;
262828c5e1b7SSerguei Katkov }
2629d16a9b1fSPhilip Reames }
2630d16a9b1fSPhilip Reames
2631d16a9b1fSPhilip Reames // The base phi insertion logic (for any safepoint) may have inserted new
2632d16a9b1fSPhilip Reames // instructions which are now live at some safepoint. The simplest such
2633d16a9b1fSPhilip Reames // example is:
2634d16a9b1fSPhilip Reames // loop:
2635d16a9b1fSPhilip Reames // phi a <-- will be a new base_phi here
2636d16a9b1fSPhilip Reames // safepoint 1 <-- that needs to be live here
2637d16a9b1fSPhilip Reames // gep a + 1
2638d16a9b1fSPhilip Reames // safepoint 2
2639d16a9b1fSPhilip Reames // br loop
2640d16a9b1fSPhilip Reames // We insert some dummy calls after each safepoint to definitely hold live
2641d16a9b1fSPhilip Reames // the base pointers which were identified for that safepoint. We'll then
2642d16a9b1fSPhilip Reames // ask liveness for _every_ base inserted to see what is now live. Then we
2643d16a9b1fSPhilip Reames // remove the dummy calls.
2644b40bd1a9SSanjoy Das Holders.reserve(Holders.size() + Records.size());
2645b40bd1a9SSanjoy Das for (size_t i = 0; i < Records.size(); i++) {
2646b40bd1a9SSanjoy Das PartiallyConstructedSafepointRecord &Info = Records[i];
2647d16a9b1fSPhilip Reames
2648d16a9b1fSPhilip Reames SmallVector<Value *, 128> Bases;
264928c5e1b7SSerguei Katkov for (auto *Derived : Info.LiveSet) {
265028c5e1b7SSerguei Katkov assert(PointerToBase.count(Derived) && "Missed base for derived pointer");
265128c5e1b7SSerguei Katkov Bases.push_back(PointerToBase[Derived]);
265228c5e1b7SSerguei Katkov }
2653b40bd1a9SSanjoy Das
2654b40bd1a9SSanjoy Das insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2655d16a9b1fSPhilip Reames }
2656d16a9b1fSPhilip Reames
2657df1ef08cSPhilip Reames // By selecting base pointers, we've effectively inserted new uses. Thus, we
2658df1ef08cSPhilip Reames // need to rerun liveness. We may *also* have inserted new defs, but that's
2659df1ef08cSPhilip Reames // not the key issue.
266028c5e1b7SSerguei Katkov recomputeLiveInValues(F, DT, ToUpdate, Records, PointerToBase);
2661d16a9b1fSPhilip Reames
2662d16a9b1fSPhilip Reames if (PrintBasePointers) {
2663d16a9b1fSPhilip Reames errs() << "Base Pairs: (w/Relocation)\n";
266428c5e1b7SSerguei Katkov for (auto Pair : PointerToBase) {
2665a4efd8acSManuel Jacob errs() << " derived ";
2666a4efd8acSManuel Jacob Pair.first->printAsOperand(errs(), false);
2667a4efd8acSManuel Jacob errs() << " base ";
2668a4efd8acSManuel Jacob Pair.second->printAsOperand(errs(), false);
2669a4efd8acSManuel Jacob errs() << "\n";
2670a4efd8acSManuel Jacob }
2671d16a9b1fSPhilip Reames }
2672b40bd1a9SSanjoy Das
2673990dfa6fSManuel Jacob // It is possible that non-constant live variables have a constant base. For
2674990dfa6fSManuel Jacob // example, a GEP with a variable offset from a global. In this case we can
2675990dfa6fSManuel Jacob // remove it from the liveset. We already don't add constants to the liveset
2676990dfa6fSManuel Jacob // because we assume they won't move at runtime and the GC doesn't need to be
2677990dfa6fSManuel Jacob // informed about them. The same reasoning applies if the base is constant.
2678990dfa6fSManuel Jacob // Note that the relocation placement code relies on this filtering for
2679990dfa6fSManuel Jacob // correctness as it expects the base to be in the liveset, which isn't true
2680990dfa6fSManuel Jacob // if the base is constant.
268128c5e1b7SSerguei Katkov for (auto &Info : Records) {
268228c5e1b7SSerguei Katkov Info.LiveSet.remove_if([&](Value *LiveV) {
268328c5e1b7SSerguei Katkov assert(PointerToBase.count(LiveV) && "Missed base for derived pointer");
268428c5e1b7SSerguei Katkov return isa<Constant>(PointerToBase[LiveV]);
268528c5e1b7SSerguei Katkov });
268628c5e1b7SSerguei Katkov }
2687990dfa6fSManuel Jacob
2688b40bd1a9SSanjoy Das for (CallInst *CI : Holders)
2689b40bd1a9SSanjoy Das CI->eraseFromParent();
2690b40bd1a9SSanjoy Das
2691b40bd1a9SSanjoy Das Holders.clear();
2692d16a9b1fSPhilip Reames
269366f1c6fcSSerguei Katkov // Compute the cost of possible re-materialization of derived pointers.
269466f1c6fcSSerguei Katkov RematCandTy RematerizationCandidates;
269566f1c6fcSSerguei Katkov findRematerializationCandidates(PointerToBase, RematerizationCandidates, TTI);
269666f1c6fcSSerguei Katkov
2697e0317186SIgor Laevsky // In order to reduce live set of statepoint we might choose to rematerialize
2698df005cbeSBenjamin Kramer // some values instead of relocating them. This is purely an optimization and
2699e0317186SIgor Laevsky // does not influence correctness.
2700b40bd1a9SSanjoy Das for (size_t i = 0; i < Records.size(); i++)
270166f1c6fcSSerguei Katkov rematerializeLiveValues(ToUpdate[i], Records[i], PointerToBase,
270266f1c6fcSSerguei Katkov RematerizationCandidates, TTI);
2703e0317186SIgor Laevsky
270425ec1a3eSSanjoy Das // We need this to safely RAUW and delete call or invoke return values that
270525ec1a3eSSanjoy Das // may themselves be live over a statepoint. For details, please see usage in
270625ec1a3eSSanjoy Das // makeStatepointExplicitImpl.
270725ec1a3eSSanjoy Das std::vector<DeferredReplacement> Replacements;
270825ec1a3eSSanjoy Das
2709d16a9b1fSPhilip Reames // Now run through and replace the existing statepoints with new ones with
2710d16a9b1fSPhilip Reames // the live variables listed. We do not yet update uses of the values being
2711d16a9b1fSPhilip Reames // relocated. We have references to live variables that need to
2712d16a9b1fSPhilip Reames // survive to the last iteration of this loop. (By construction, the
2713d16a9b1fSPhilip Reames // previous statepoint can not be a live variable, thus we can and remove
2714d16a9b1fSPhilip Reames // the old statepoint calls as we go.)
2715b40bd1a9SSanjoy Das for (size_t i = 0; i < Records.size(); i++)
271628c5e1b7SSerguei Katkov makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements,
271728c5e1b7SSerguei Katkov PointerToBase);
2718b40bd1a9SSanjoy Das
27193160734aSChandler Carruth ToUpdate.clear(); // prevent accident use of invalid calls.
2720d16a9b1fSPhilip Reames
272125ec1a3eSSanjoy Das for (auto &PR : Replacements)
272225ec1a3eSSanjoy Das PR.doReplacement();
272325ec1a3eSSanjoy Das
272425ec1a3eSSanjoy Das Replacements.clear();
272525ec1a3eSSanjoy Das
272625ec1a3eSSanjoy Das for (auto &Info : Records) {
272725ec1a3eSSanjoy Das // These live sets may contain state Value pointers, since we replaced calls
272825ec1a3eSSanjoy Das // with operand bundles with calls wrapped in gc.statepoint, and some of
272925ec1a3eSSanjoy Das // those calls may have been def'ing live gc pointers. Clear these out to
273025ec1a3eSSanjoy Das // avoid accidentally using them.
273125ec1a3eSSanjoy Das //
273225ec1a3eSSanjoy Das // TODO: We should create a separate data structure that does not contain
273325ec1a3eSSanjoy Das // these live sets, and migrate to using that data structure from this point
273425ec1a3eSSanjoy Das // onward.
273525ec1a3eSSanjoy Das Info.LiveSet.clear();
273625ec1a3eSSanjoy Das }
273728c5e1b7SSerguei Katkov PointerToBase.clear();
273825ec1a3eSSanjoy Das
2739d16a9b1fSPhilip Reames // Do all the fixups of the original live variables to their relocated selves
2740b40bd1a9SSanjoy Das SmallVector<Value *, 128> Live;
2741b40bd1a9SSanjoy Das for (size_t i = 0; i < Records.size(); i++) {
2742b40bd1a9SSanjoy Das PartiallyConstructedSafepointRecord &Info = Records[i];
274325ec1a3eSSanjoy Das
2744d16a9b1fSPhilip Reames // We can't simply save the live set from the original insertion. One of
2745d16a9b1fSPhilip Reames // the live values might be the result of a call which needs a safepoint.
2746d16a9b1fSPhilip Reames // That Value* no longer exists and we need to use the new gc_result.
2747d16a9b1fSPhilip Reames // Thankfully, the live set is embedded in the statepoint (and updated), so
2748d16a9b1fSPhilip Reames // we just grab that.
27498299fb8fSKazu Hirata llvm::append_range(Live, Info.StatepointToken->gc_args());
27509a2e01d9SPhilip Reames #ifndef NDEBUG
27519769e97cSZarko Todorovski // Do some basic validation checking on our liveness results before
27529769e97cSZarko Todorovski // performing relocation. Relocation can and will turn mistakes in liveness
27539769e97cSZarko Todorovski // results into non-sensical code which is must harder to debug.
27549a2e01d9SPhilip Reames // TODO: It would be nice to test consistency as well
2755b40bd1a9SSanjoy Das assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
27569a2e01d9SPhilip Reames "statepoint must be reachable or liveness is meaningless");
2757a0d2fd4aSPhilip Reames for (Value *V : Info.StatepointToken->gc_args()) {
27589a2e01d9SPhilip Reames if (!isa<Instruction>(V))
27599a2e01d9SPhilip Reames // Non-instruction values trivial dominate all possible uses
27609a2e01d9SPhilip Reames continue;
2761b40bd1a9SSanjoy Das auto *LiveInst = cast<Instruction>(V);
27629a2e01d9SPhilip Reames assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
27639a2e01d9SPhilip Reames "unreachable values should never be live");
2764b40bd1a9SSanjoy Das assert(DT.dominates(LiveInst, Info.StatepointToken) &&
27659a2e01d9SPhilip Reames "basic SSA liveness expectation violated by liveness analysis");
27669a2e01d9SPhilip Reames }
27679a2e01d9SPhilip Reames #endif
2768d16a9b1fSPhilip Reames }
2769b40bd1a9SSanjoy Das unique_unsorted(Live);
2770d16a9b1fSPhilip Reames
2771eb3231eeSNick Lewycky #ifndef NDEBUG
27729769e97cSZarko Todorovski // Validation check
2773b40bd1a9SSanjoy Das for (auto *Ptr : Live)
27745715f576SPhilip Reames assert(isHandledGCPointerType(Ptr->getType()) &&
27755715f576SPhilip Reames "must be a gc pointer type");
2776eb3231eeSNick Lewycky #endif
2777d16a9b1fSPhilip Reames
2778b40bd1a9SSanjoy Das relocationViaAlloca(F, DT, Live, Records);
2779b40bd1a9SSanjoy Das return !Records.empty();
2780d16a9b1fSPhilip Reames }
2781d16a9b1fSPhilip Reames
27829f24f010SNikita Popov // List of all parameter and return attributes which must be stripped when
27839f24f010SNikita Popov // lowering from the abstract machine model. Note that we list attributes
27849f24f010SNikita Popov // here which aren't valid as return attributes, that is okay.
getParamAndReturnAttributesToRemove()27859290ccc3Sserge-sans-paille static AttributeMask getParamAndReturnAttributesToRemove() {
27869290ccc3Sserge-sans-paille AttributeMask R;
27879290ccc3Sserge-sans-paille R.addAttribute(Attribute::Dereferenceable);
27889290ccc3Sserge-sans-paille R.addAttribute(Attribute::DereferenceableOrNull);
27899f24f010SNikita Popov R.addAttribute(Attribute::ReadNone);
27909f24f010SNikita Popov R.addAttribute(Attribute::ReadOnly);
27919f24f010SNikita Popov R.addAttribute(Attribute::WriteOnly);
27929f24f010SNikita Popov R.addAttribute(Attribute::NoAlias);
27939f24f010SNikita Popov R.addAttribute(Attribute::NoFree);
27949f24f010SNikita Popov return R;
27959f77f61eSVasileios Kalintiris }
2796353a19e1SSanjoy Das
stripNonValidAttributesFromPrototype(Function & F)27974b86d790SFedor Sergeev static void stripNonValidAttributesFromPrototype(Function &F) {
2798353a19e1SSanjoy Das LLVMContext &Ctx = F.getContext();
2799353a19e1SSanjoy Das
280001801d52SPhilip Reames // Intrinsics are very delicate. Lowering sometimes depends the presence
280101801d52SPhilip Reames // of certain attributes for correctness, but we may have also inferred
280201801d52SPhilip Reames // additional ones in the abstract machine model which need stripped. This
280301801d52SPhilip Reames // assumes that the attributes defined in Intrinsic.td are conservatively
280401801d52SPhilip Reames // correct for both physical and abstract model.
280501801d52SPhilip Reames if (Intrinsic::ID id = F.getIntrinsicID()) {
280601801d52SPhilip Reames F.setAttributes(Intrinsic::getAttributes(Ctx, id));
280701801d52SPhilip Reames return;
280801801d52SPhilip Reames }
280901801d52SPhilip Reames
28109290ccc3Sserge-sans-paille AttributeMask R = getParamAndReturnAttributesToRemove();
2811353a19e1SSanjoy Das for (Argument &A : F.args())
2812353a19e1SSanjoy Das if (isa<PointerType>(A.getType()))
28139f24f010SNikita Popov F.removeParamAttrs(A.getArgNo(), R);
2814353a19e1SSanjoy Das
2815353a19e1SSanjoy Das if (isa<PointerType>(F.getReturnType()))
28169f24f010SNikita Popov F.removeRetAttrs(R);
2817a505801eSPhilip Reames
28183f1c2183SPhilip Reames for (auto Attr : FnAttrsToStrip)
28192c4548e1SPhilip Reames F.removeFnAttr(Attr);
2820353a19e1SSanjoy Das }
2821353a19e1SSanjoy Das
28224b86d790SFedor Sergeev /// Certain metadata on instructions are invalid after running RS4GC.
28234b86d790SFedor Sergeev /// Optimizations that run after RS4GC can incorrectly use this metadata to
28244b86d790SFedor Sergeev /// optimize functions. We drop such metadata on the instruction.
stripInvalidMetadataFromInstruction(Instruction & I)28254b86d790SFedor Sergeev static void stripInvalidMetadataFromInstruction(Instruction &I) {
28264b027e8fSAnna Thomas if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
28274b027e8fSAnna Thomas return;
28284b027e8fSAnna Thomas // These are the attributes that are still valid on loads and stores after
28294b027e8fSAnna Thomas // RS4GC.
28304b027e8fSAnna Thomas // The metadata implying dereferenceability and noalias are (conservatively)
28314b027e8fSAnna Thomas // dropped. This is because semantically, after RewriteStatepointsForGC runs,
28324b027e8fSAnna Thomas // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
28334b027e8fSAnna Thomas // touch the entire heap including noalias objects. Note: The reasoning is
28344b027e8fSAnna Thomas // same as stripping the dereferenceability and noalias attributes that are
28354b027e8fSAnna Thomas // analogous to the metadata counterparts.
28364b027e8fSAnna Thomas // We also drop the invariant.load metadata on the load because that metadata
28374b027e8fSAnna Thomas // implies the address operand to the load points to memory that is never
28384b027e8fSAnna Thomas // changed once it became dereferenceable. This is no longer true after RS4GC.
28394b027e8fSAnna Thomas // Similar reasoning applies to invariant.group metadata, which applies to
28404b027e8fSAnna Thomas // loads within a group.
28414b027e8fSAnna Thomas unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
28424b027e8fSAnna Thomas LLVMContext::MD_range,
28434b027e8fSAnna Thomas LLVMContext::MD_alias_scope,
28444b027e8fSAnna Thomas LLVMContext::MD_nontemporal,
28454b027e8fSAnna Thomas LLVMContext::MD_nonnull,
28464b027e8fSAnna Thomas LLVMContext::MD_align,
28474b027e8fSAnna Thomas LLVMContext::MD_type};
28484b027e8fSAnna Thomas
28494b027e8fSAnna Thomas // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
28504b027e8fSAnna Thomas I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
28514b027e8fSAnna Thomas }
28524b027e8fSAnna Thomas
stripNonValidDataFromBody(Function & F)28534b86d790SFedor Sergeev static void stripNonValidDataFromBody(Function &F) {
2854353a19e1SSanjoy Das if (F.empty())
2855353a19e1SSanjoy Das return;
2856353a19e1SSanjoy Das
2857353a19e1SSanjoy Das LLVMContext &Ctx = F.getContext();
2858353a19e1SSanjoy Das MDBuilder Builder(Ctx);
2859353a19e1SSanjoy Das
2860729dafc1SAnna Thomas // Set of invariantstart instructions that we need to remove.
2861729dafc1SAnna Thomas // Use this to avoid invalidating the instruction iterator.
2862729dafc1SAnna Thomas SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
2863729dafc1SAnna Thomas
286478199518SNico Rieck for (Instruction &I : instructions(F)) {
2865729dafc1SAnna Thomas // invariant.start on memory location implies that the referenced memory
2866729dafc1SAnna Thomas // location is constant and unchanging. This is no longer true after
2867729dafc1SAnna Thomas // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
2868729dafc1SAnna Thomas // which frees the entire heap and the presence of invariant.start allows
2869729dafc1SAnna Thomas // the optimizer to sink the load of a memory location past a statepoint,
2870729dafc1SAnna Thomas // which is incorrect.
2871729dafc1SAnna Thomas if (auto *II = dyn_cast<IntrinsicInst>(&I))
2872729dafc1SAnna Thomas if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2873729dafc1SAnna Thomas InvariantStartInstructions.push_back(II);
2874729dafc1SAnna Thomas continue;
2875729dafc1SAnna Thomas }
2876729dafc1SAnna Thomas
28774d0ff0c7SIvan A. Kosarev if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
28784d0ff0c7SIvan A. Kosarev MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
2879353a19e1SSanjoy Das I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2880353a19e1SSanjoy Das }
2881353a19e1SSanjoy Das
28824b027e8fSAnna Thomas stripInvalidMetadataFromInstruction(I);
28834b027e8fSAnna Thomas
28849290ccc3Sserge-sans-paille AttributeMask R = getParamAndReturnAttributesToRemove();
28853160734aSChandler Carruth if (auto *Call = dyn_cast<CallBase>(&I)) {
28863160734aSChandler Carruth for (int i = 0, e = Call->arg_size(); i != e; i++)
28873160734aSChandler Carruth if (isa<PointerType>(Call->getArgOperand(i)->getType()))
28889f24f010SNikita Popov Call->removeParamAttrs(i, R);
28893160734aSChandler Carruth if (isa<PointerType>(Call->getType()))
28909f24f010SNikita Popov Call->removeRetAttrs(R);
2891353a19e1SSanjoy Das }
2892353a19e1SSanjoy Das }
2893729dafc1SAnna Thomas
2894729dafc1SAnna Thomas // Delete the invariant.start instructions and RAUW undef.
2895729dafc1SAnna Thomas for (auto *II : InvariantStartInstructions) {
2896729dafc1SAnna Thomas II->replaceAllUsesWith(UndefValue::get(II->getType()));
2897729dafc1SAnna Thomas II->eraseFromParent();
2898729dafc1SAnna Thomas }
2899353a19e1SSanjoy Das }
2900353a19e1SSanjoy Das
2901d16a9b1fSPhilip Reames /// Returns true if this function should be rewritten by this pass. The main
2902d16a9b1fSPhilip Reames /// point of this function is as an extension point for custom logic.
shouldRewriteStatepointsIn(Function & F)2903d16a9b1fSPhilip Reames static bool shouldRewriteStatepointsIn(Function &F) {
2904d16a9b1fSPhilip Reames // TODO: This should check the GCStrategy
29052ef029c7SPhilip Reames if (F.hasGC()) {
2906599ebf27SMehdi Amini const auto &FunctionGCName = F.getGC();
2907665bc9c9SSwaroop Sridhar const StringRef StatepointExampleName("statepoint-example");
2908665bc9c9SSwaroop Sridhar const StringRef CoreCLRName("coreclr");
2909665bc9c9SSwaroop Sridhar return (StatepointExampleName == FunctionGCName) ||
2910665bc9c9SSwaroop Sridhar (CoreCLRName == FunctionGCName);
29115582a6a4SNAKAMURA Takumi } else
29122ef029c7SPhilip Reames return false;
2913d16a9b1fSPhilip Reames }
2914d16a9b1fSPhilip Reames
stripNonValidData(Module & M)29154b86d790SFedor Sergeev static void stripNonValidData(Module &M) {
2916353a19e1SSanjoy Das #ifndef NDEBUG
291775075efeSEugene Zelenko assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
2918353a19e1SSanjoy Das #endif
2919353a19e1SSanjoy Das
2920353a19e1SSanjoy Das for (Function &F : M)
2921dde0029aSIgor Laevsky stripNonValidAttributesFromPrototype(F);
2922353a19e1SSanjoy Das
2923353a19e1SSanjoy Das for (Function &F : M)
2924729dafc1SAnna Thomas stripNonValidDataFromBody(F);
2925353a19e1SSanjoy Das }
2926353a19e1SSanjoy Das
runOnFunction(Function & F,DominatorTree & DT,TargetTransformInfo & TTI,const TargetLibraryInfo & TLI)29274b86d790SFedor Sergeev bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
29284b86d790SFedor Sergeev TargetTransformInfo &TTI,
29294b86d790SFedor Sergeev const TargetLibraryInfo &TLI) {
29304b86d790SFedor Sergeev assert(!F.isDeclaration() && !F.empty() &&
29314b86d790SFedor Sergeev "need function body to rewrite statepoints in");
29324b86d790SFedor Sergeev assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
293385b36a81SPhilip Reames
29342574d7cbSDaniel Neilson auto NeedsRewrite = [&TLI](Instruction &I) {
29356ec2c5e4SArtur Pilipenko if (const auto *Call = dyn_cast<CallBase>(&I)) {
29366ec2c5e4SArtur Pilipenko if (isa<GCStatepointInst>(Call))
29376ec2c5e4SArtur Pilipenko return false;
29386ec2c5e4SArtur Pilipenko if (callsGCLeafFunction(Call, TLI))
29396ec2c5e4SArtur Pilipenko return false;
29406ec2c5e4SArtur Pilipenko
29416ec2c5e4SArtur Pilipenko // Normally it's up to the frontend to make sure that non-leaf calls also
29426ec2c5e4SArtur Pilipenko // have proper deopt state if it is required. We make an exception for
29436ec2c5e4SArtur Pilipenko // element atomic memcpy/memmove intrinsics here. Unlike other intrinsics
29446ec2c5e4SArtur Pilipenko // these are non-leaf by default. They might be generated by the optimizer
29456ec2c5e4SArtur Pilipenko // which doesn't know how to produce a proper deopt state. So if we see a
29466ec2c5e4SArtur Pilipenko // non-leaf memcpy/memmove without deopt state just treat it as a leaf
29476ec2c5e4SArtur Pilipenko // copy and don't produce a statepoint.
29486ec2c5e4SArtur Pilipenko if (!AllowStatepointWithNoDeoptInfo &&
29496ec2c5e4SArtur Pilipenko !Call->getOperandBundle(LLVMContext::OB_deopt)) {
29506ec2c5e4SArtur Pilipenko assert((isa<AtomicMemCpyInst>(Call) || isa<AtomicMemMoveInst>(Call)) &&
29516ec2c5e4SArtur Pilipenko "Don't expect any other calls here!");
29526ec2c5e4SArtur Pilipenko return false;
29536ec2c5e4SArtur Pilipenko }
29546ec2c5e4SArtur Pilipenko return true;
29556ec2c5e4SArtur Pilipenko }
295625ec1a3eSSanjoy Das return false;
295725ec1a3eSSanjoy Das };
295825ec1a3eSSanjoy Das
295982daad31SDaniel Neilson // Delete any unreachable statepoints so that we don't have unrewritten
296082daad31SDaniel Neilson // statepoints surviving this pass. This makes testing easier and the
296182daad31SDaniel Neilson // resulting IR less confusing to human readers.
296221a8b605SChijun Sima DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
2963eb6700b5SFlorian Hahn bool MadeChange = removeUnreachableBlocks(F, &DTU);
296421a8b605SChijun Sima // Flush the Dominator Tree.
296521a8b605SChijun Sima DTU.getDomTree();
296682daad31SDaniel Neilson
296785b36a81SPhilip Reames // Gather all the statepoints which need rewritten. Be careful to only
296885b36a81SPhilip Reames // consider those in reachable code since we need to ask dominance queries
296985b36a81SPhilip Reames // when rewriting. We'll delete the unreachable ones in a moment.
29703160734aSChandler Carruth SmallVector<CallBase *, 64> ParsePointNeeded;
29714d26f41fSYevgeny Rouban SmallVector<CallInst *, 64> Intrinsics;
297278199518SNico Rieck for (Instruction &I : instructions(F)) {
2973d16a9b1fSPhilip Reames // TODO: only the ones with the flag set!
297425ec1a3eSSanjoy Das if (NeedsRewrite(I)) {
297582daad31SDaniel Neilson // NOTE removeUnreachableBlocks() is stronger than
297682daad31SDaniel Neilson // DominatorTree::isReachableFromEntry(). In other words
297782daad31SDaniel Neilson // removeUnreachableBlocks can remove some blocks for which
297882daad31SDaniel Neilson // isReachableFromEntry() returns true.
297982daad31SDaniel Neilson assert(DT.isReachableFromEntry(I.getParent()) &&
298082daad31SDaniel Neilson "no unreachable blocks expected");
29813160734aSChandler Carruth ParsePointNeeded.push_back(cast<CallBase>(&I));
2982d16a9b1fSPhilip Reames }
29834d26f41fSYevgeny Rouban if (auto *CI = dyn_cast<CallInst>(&I))
29844d26f41fSYevgeny Rouban if (CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_base ||
29854d26f41fSYevgeny Rouban CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_offset)
29864d26f41fSYevgeny Rouban Intrinsics.emplace_back(CI);
298785b36a81SPhilip Reames }
298885b36a81SPhilip Reames
2989d16a9b1fSPhilip Reames // Return early if no work to do.
29904d26f41fSYevgeny Rouban if (ParsePointNeeded.empty() && Intrinsics.empty())
299185b36a81SPhilip Reames return MadeChange;
2992d16a9b1fSPhilip Reames
299385b36a81SPhilip Reames // As a prepass, go ahead and aggressively destroy single entry phi nodes.
299485b36a81SPhilip Reames // These are created by LCSSA. They have the effect of increasing the size
299585b36a81SPhilip Reames // of liveness sets for no good reason. It may be harder to do this post
299685b36a81SPhilip Reames // insertion since relocations and base phis can confuse things.
299785b36a81SPhilip Reames for (BasicBlock &BB : F)
2998d76c1d22SYevgeny Rouban if (BB.getUniquePredecessor())
2999d76c1d22SYevgeny Rouban MadeChange |= FoldSingleEntryPHINodes(&BB);
300085b36a81SPhilip Reames
3001971dc3a8SPhilip Reames // Before we start introducing relocations, we want to tweak the IR a bit to
3002971dc3a8SPhilip Reames // avoid unfortunate code generation effects. The main example is that we
3003971dc3a8SPhilip Reames // want to try to make sure the comparison feeding a branch is after any
3004971dc3a8SPhilip Reames // safepoints. Otherwise, we end up with a comparison of pre-relocation
3005971dc3a8SPhilip Reames // values feeding a branch after relocation. This is semantically correct,
3006971dc3a8SPhilip Reames // but results in extra register pressure since both the pre-relocation and
3007971dc3a8SPhilip Reames // post-relocation copies must be available in registers. For code without
3008971dc3a8SPhilip Reames // relocations this is handled elsewhere, but teaching the scheduler to
3009971dc3a8SPhilip Reames // reverse the transform we're about to do would be slightly complex.
3010971dc3a8SPhilip Reames // Note: This may extend the live range of the inputs to the icmp and thus
3011971dc3a8SPhilip Reames // increase the liveset of any statepoint we move over. This is profitable
3012971dc3a8SPhilip Reames // as long as all statepoints are in rare blocks. If we had in-register
3013971dc3a8SPhilip Reames // lowering for live values this would be a much safer transform.
3014edb12a83SChandler Carruth auto getConditionInst = [](Instruction *TI) -> Instruction * {
3015971dc3a8SPhilip Reames if (auto *BI = dyn_cast<BranchInst>(TI))
3016971dc3a8SPhilip Reames if (BI->isConditional())
3017971dc3a8SPhilip Reames return dyn_cast<Instruction>(BI->getCondition());
3018971dc3a8SPhilip Reames // TODO: Extend this to handle switches
3019971dc3a8SPhilip Reames return nullptr;
3020971dc3a8SPhilip Reames };
3021971dc3a8SPhilip Reames for (BasicBlock &BB : F) {
3022edb12a83SChandler Carruth Instruction *TI = BB.getTerminator();
3023971dc3a8SPhilip Reames if (auto *Cond = getConditionInst(TI))
3024971dc3a8SPhilip Reames // TODO: Handle more than just ICmps here. We should be able to move
3025971dc3a8SPhilip Reames // most instructions without side effects or memory access.
3026971dc3a8SPhilip Reames if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
3027971dc3a8SPhilip Reames MadeChange = true;
3028971dc3a8SPhilip Reames Cond->moveBefore(TI);
3029971dc3a8SPhilip Reames }
3030971dc3a8SPhilip Reames }
3031971dc3a8SPhilip Reames
3032a657510eSPhilip Reames // Nasty workaround - The base computation code in the main algorithm doesn't
3033a657510eSPhilip Reames // consider the fact that a GEP can be used to convert a scalar to a vector.
3034a657510eSPhilip Reames // The right fix for this is to integrate GEPs into the base rewriting
3035a657510eSPhilip Reames // algorithm properly, this is just a short term workaround to prevent
3036a657510eSPhilip Reames // crashes by canonicalizing such GEPs into fully vector GEPs.
3037a657510eSPhilip Reames for (Instruction &I : instructions(F)) {
3038a657510eSPhilip Reames if (!isa<GetElementPtrInst>(I))
3039a657510eSPhilip Reames continue;
3040a657510eSPhilip Reames
3041a657510eSPhilip Reames unsigned VF = 0;
3042a657510eSPhilip Reames for (unsigned i = 0; i < I.getNumOperands(); i++)
304319cc9b9dSChristopher Tetreault if (auto *OpndVTy = dyn_cast<VectorType>(I.getOperand(i)->getType())) {
3044c444b1b9SChristopher Tetreault assert(VF == 0 ||
3045c444b1b9SChristopher Tetreault VF == cast<FixedVectorType>(OpndVTy)->getNumElements());
3046c444b1b9SChristopher Tetreault VF = cast<FixedVectorType>(OpndVTy)->getNumElements();
3047a657510eSPhilip Reames }
30484d683ee7SPhilip Reames
30494d683ee7SPhilip Reames // It's the vector to scalar traversal through the pointer operand which
30504d683ee7SPhilip Reames // confuses base pointer rewriting, so limit ourselves to that case.
30514d683ee7SPhilip Reames if (!I.getOperand(0)->getType()->isVectorTy() && VF != 0) {
30524d683ee7SPhilip Reames IRBuilder<> B(&I);
30534d683ee7SPhilip Reames auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
30544d683ee7SPhilip Reames I.setOperand(0, Splat);
30554d683ee7SPhilip Reames MadeChange = true;
3056a657510eSPhilip Reames }
3057a657510eSPhilip Reames }
3058a657510eSPhilip Reames
305988024a72SYevgeny Rouban // Cache the 'defining value' relation used in the computation and
306088024a72SYevgeny Rouban // insertion of base phis and selects. This ensures that we don't insert
306188024a72SYevgeny Rouban // large numbers of duplicate base_phis. Use one cache for both
306288024a72SYevgeny Rouban // inlineGetBaseAndOffset() and insertParsePoints().
306388024a72SYevgeny Rouban DefiningValueMapTy DVCache;
306488024a72SYevgeny Rouban
30651da42c9fSDmitry Makogon // Mapping between a base values and a flag indicating whether it's a known
30661da42c9fSDmitry Makogon // base or not.
30671da42c9fSDmitry Makogon IsKnownBaseMapTy KnownBases;
30681da42c9fSDmitry Makogon
30694d26f41fSYevgeny Rouban if (!Intrinsics.empty())
30704d26f41fSYevgeny Rouban // Inline @gc.get.pointer.base() and @gc.get.pointer.offset() before finding
30714d26f41fSYevgeny Rouban // live references.
30721da42c9fSDmitry Makogon MadeChange |= inlineGetBaseAndOffset(F, Intrinsics, DVCache, KnownBases);
30734d26f41fSYevgeny Rouban
30744d26f41fSYevgeny Rouban if (!ParsePointNeeded.empty())
30751da42c9fSDmitry Makogon MadeChange |=
30761da42c9fSDmitry Makogon insertParsePoints(F, DT, TTI, ParsePointNeeded, DVCache, KnownBases);
307788024a72SYevgeny Rouban
307885b36a81SPhilip Reames return MadeChange;
3079d16a9b1fSPhilip Reames }
3080df1ef08cSPhilip Reames
3081df1ef08cSPhilip Reames // liveness computation via standard dataflow
3082df1ef08cSPhilip Reames // -------------------------------------------------------------------
3083df1ef08cSPhilip Reames
3084df1ef08cSPhilip Reames // TODO: Consider using bitvectors for liveness, the set of potentially
3085df1ef08cSPhilip Reames // interesting values should be small and easy to pre-compute.
3086df1ef08cSPhilip Reames
3087df1ef08cSPhilip Reames /// Compute the live-in set for the location rbegin starting from
3088df1ef08cSPhilip Reames /// the live-out set of the basic block
computeLiveInValues(BasicBlock::reverse_iterator Begin,BasicBlock::reverse_iterator End,SetVector<Value * > & LiveTmp)308961c76e3bSSanjoy Das static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
309061c76e3bSSanjoy Das BasicBlock::reverse_iterator End,
3091fb1811d3SIgor Laevsky SetVector<Value *> &LiveTmp) {
309261c76e3bSSanjoy Das for (auto &I : make_range(Begin, End)) {
3093df1ef08cSPhilip Reames // KILL/Def - Remove this definition from LiveIn
309461c76e3bSSanjoy Das LiveTmp.remove(&I);
3095df1ef08cSPhilip Reames
3096df1ef08cSPhilip Reames // Don't consider *uses* in PHI nodes, we handle their contribution to
3097df1ef08cSPhilip Reames // predecessor blocks when we seed the LiveOut sets
3098df1ef08cSPhilip Reames if (isa<PHINode>(I))
3099df1ef08cSPhilip Reames continue;
3100df1ef08cSPhilip Reames
3101df1ef08cSPhilip Reames // USE - Add to the LiveIn set for this instruction
310261c76e3bSSanjoy Das for (Value *V : I.operands()) {
3103df1ef08cSPhilip Reames assert(!isUnhandledGCPointerType(V->getType()) &&
3104df1ef08cSPhilip Reames "support for FCA unimplemented");
310563294cbbSPhilip Reames if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
310663294cbbSPhilip Reames // The choice to exclude all things constant here is slightly subtle.
3107df005cbeSBenjamin Kramer // There are two independent reasons:
310863294cbbSPhilip Reames // - We assume that things which are constant (from LLVM's definition)
310963294cbbSPhilip Reames // do not move at runtime. For example, the address of a global
311063294cbbSPhilip Reames // variable is fixed, even though it's contents may not be.
311163294cbbSPhilip Reames // - Second, we can't disallow arbitrary inttoptr constants even
311263294cbbSPhilip Reames // if the language frontend does. Optimization passes are free to
311363294cbbSPhilip Reames // locally exploit facts without respect to global reachability. This
311463294cbbSPhilip Reames // can create sections of code which are dynamically unreachable and
311563294cbbSPhilip Reames // contain just about anything. (see constants.ll in tests)
3116df1ef08cSPhilip Reames LiveTmp.insert(V);
3117df1ef08cSPhilip Reames }
3118df1ef08cSPhilip Reames }
3119df1ef08cSPhilip Reames }
3120df1ef08cSPhilip Reames }
3121df1ef08cSPhilip Reames
computeLiveOutSeed(BasicBlock * BB,SetVector<Value * > & LiveTmp)3122fb1811d3SIgor Laevsky static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
3123df1ef08cSPhilip Reames for (BasicBlock *Succ : successors(BB)) {
312476f6b125SOliver Stannard for (auto &I : *Succ) {
312576f6b125SOliver Stannard PHINode *PN = dyn_cast<PHINode>(&I);
312676f6b125SOliver Stannard if (!PN)
312776f6b125SOliver Stannard break;
312876f6b125SOliver Stannard
312976f6b125SOliver Stannard Value *V = PN->getIncomingValueForBlock(BB);
3130df1ef08cSPhilip Reames assert(!isUnhandledGCPointerType(V->getType()) &&
3131df1ef08cSPhilip Reames "support for FCA unimplemented");
313283186b06SSanjoy Das if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
3133df1ef08cSPhilip Reames LiveTmp.insert(V);
3134df1ef08cSPhilip Reames }
3135df1ef08cSPhilip Reames }
3136df1ef08cSPhilip Reames }
3137df1ef08cSPhilip Reames
computeKillSet(BasicBlock * BB)3138fb1811d3SIgor Laevsky static SetVector<Value *> computeKillSet(BasicBlock *BB) {
3139fb1811d3SIgor Laevsky SetVector<Value *> KillSet;
3140df1ef08cSPhilip Reames for (Instruction &I : *BB)
3141df1ef08cSPhilip Reames if (isHandledGCPointerType(I.getType()))
3142df1ef08cSPhilip Reames KillSet.insert(&I);
3143df1ef08cSPhilip Reames return KillSet;
3144df1ef08cSPhilip Reames }
3145df1ef08cSPhilip Reames
31469638ff9bSPhilip Reames #ifndef NDEBUG
3147df1ef08cSPhilip Reames /// Check that the items in 'Live' dominate 'TI'. This is used as a basic
31489769e97cSZarko Todorovski /// validation check for the liveness computation.
checkBasicSSA(DominatorTree & DT,SetVector<Value * > & Live,Instruction * TI,bool TermOkay=false)3149fb1811d3SIgor Laevsky static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
3150edb12a83SChandler Carruth Instruction *TI, bool TermOkay = false) {
3151df1ef08cSPhilip Reames for (Value *V : Live) {
3152df1ef08cSPhilip Reames if (auto *I = dyn_cast<Instruction>(V)) {
3153df1ef08cSPhilip Reames // The terminator can be a member of the LiveOut set. LLVM's definition
3154df1ef08cSPhilip Reames // of instruction dominance states that V does not dominate itself. As
3155df1ef08cSPhilip Reames // such, we need to special case this to allow it.
3156df1ef08cSPhilip Reames if (TermOkay && TI == I)
3157df1ef08cSPhilip Reames continue;
3158df1ef08cSPhilip Reames assert(DT.dominates(I, TI) &&
3159df1ef08cSPhilip Reames "basic SSA liveness expectation violated by liveness analysis");
3160df1ef08cSPhilip Reames }
3161df1ef08cSPhilip Reames }
3162df1ef08cSPhilip Reames }
3163df1ef08cSPhilip Reames
3164df1ef08cSPhilip Reames /// Check that all the liveness sets used during the computation of liveness
3165df1ef08cSPhilip Reames /// obey basic SSA properties. This is useful for finding cases where we miss
3166df1ef08cSPhilip Reames /// a def.
checkBasicSSA(DominatorTree & DT,GCPtrLivenessData & Data,BasicBlock & BB)3167df1ef08cSPhilip Reames static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
3168df1ef08cSPhilip Reames BasicBlock &BB) {
3169df1ef08cSPhilip Reames checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
3170df1ef08cSPhilip Reames checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
3171df1ef08cSPhilip Reames checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
3172df1ef08cSPhilip Reames }
31739638ff9bSPhilip Reames #endif
3174df1ef08cSPhilip Reames
computeLiveInValues(DominatorTree & DT,Function & F,GCPtrLivenessData & Data)3175df1ef08cSPhilip Reames static void computeLiveInValues(DominatorTree &DT, Function &F,
3176df1ef08cSPhilip Reames GCPtrLivenessData &Data) {
3177b30f2f51SMatthias Braun SmallSetVector<BasicBlock *, 32> Worklist;
3178df1ef08cSPhilip Reames
3179df1ef08cSPhilip Reames // Seed the liveness for each individual block
3180df1ef08cSPhilip Reames for (BasicBlock &BB : F) {
3181df1ef08cSPhilip Reames Data.KillSet[&BB] = computeKillSet(&BB);
3182df1ef08cSPhilip Reames Data.LiveSet[&BB].clear();
3183df1ef08cSPhilip Reames computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
3184df1ef08cSPhilip Reames
3185df1ef08cSPhilip Reames #ifndef NDEBUG
3186df1ef08cSPhilip Reames for (Value *Kill : Data.KillSet[&BB])
3187df1ef08cSPhilip Reames assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
3188df1ef08cSPhilip Reames #endif
3189df1ef08cSPhilip Reames
3190fb1811d3SIgor Laevsky Data.LiveOut[&BB] = SetVector<Value *>();
3191df1ef08cSPhilip Reames computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
3192df1ef08cSPhilip Reames Data.LiveIn[&BB] = Data.LiveSet[&BB];
3193fb1811d3SIgor Laevsky Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
3194fb1811d3SIgor Laevsky Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
3195df1ef08cSPhilip Reames if (!Data.LiveIn[&BB].empty())
3196b2df57afSSanjoy Das Worklist.insert(pred_begin(&BB), pred_end(&BB));
3197df1ef08cSPhilip Reames }
3198df1ef08cSPhilip Reames
3199df1ef08cSPhilip Reames // Propagate that liveness until stable
3200df1ef08cSPhilip Reames while (!Worklist.empty()) {
3201b2df57afSSanjoy Das BasicBlock *BB = Worklist.pop_back_val();
3202df1ef08cSPhilip Reames
3203b2df57afSSanjoy Das // Compute our new liveout set, then exit early if it hasn't changed despite
3204b2df57afSSanjoy Das // the contribution of our successor.
3205fb1811d3SIgor Laevsky SetVector<Value *> LiveOut = Data.LiveOut[BB];
3206df1ef08cSPhilip Reames const auto OldLiveOutSize = LiveOut.size();
3207df1ef08cSPhilip Reames for (BasicBlock *Succ : successors(BB)) {
3208df1ef08cSPhilip Reames assert(Data.LiveIn.count(Succ));
3209fb1811d3SIgor Laevsky LiveOut.set_union(Data.LiveIn[Succ]);
3210df1ef08cSPhilip Reames }
3211df1ef08cSPhilip Reames // assert OutLiveOut is a subset of LiveOut
3212df1ef08cSPhilip Reames if (OldLiveOutSize == LiveOut.size()) {
3213df1ef08cSPhilip Reames // If the sets are the same size, then we didn't actually add anything
3214b2df57afSSanjoy Das // when unioning our successors LiveIn. Thus, the LiveIn of this block
3215df1ef08cSPhilip Reames // hasn't changed.
3216df1ef08cSPhilip Reames continue;
3217df1ef08cSPhilip Reames }
3218df1ef08cSPhilip Reames Data.LiveOut[BB] = LiveOut;
3219df1ef08cSPhilip Reames
3220df1ef08cSPhilip Reames // Apply the effects of this basic block
3221fb1811d3SIgor Laevsky SetVector<Value *> LiveTmp = LiveOut;
3222fb1811d3SIgor Laevsky LiveTmp.set_union(Data.LiveSet[BB]);
3223fb1811d3SIgor Laevsky LiveTmp.set_subtract(Data.KillSet[BB]);
3224df1ef08cSPhilip Reames
3225df1ef08cSPhilip Reames assert(Data.LiveIn.count(BB));
3226fb1811d3SIgor Laevsky const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
3227df1ef08cSPhilip Reames // assert: OldLiveIn is a subset of LiveTmp
3228df1ef08cSPhilip Reames if (OldLiveIn.size() != LiveTmp.size()) {
3229df1ef08cSPhilip Reames Data.LiveIn[BB] = LiveTmp;
3230b2df57afSSanjoy Das Worklist.insert(pred_begin(BB), pred_end(BB));
3231df1ef08cSPhilip Reames }
3232b2df57afSSanjoy Das } // while (!Worklist.empty())
3233df1ef08cSPhilip Reames
3234df1ef08cSPhilip Reames #ifndef NDEBUG
32359769e97cSZarko Todorovski // Verify our output against SSA properties. This helps catch any
3236df1ef08cSPhilip Reames // missing kills during the above iteration.
3237b2df57afSSanjoy Das for (BasicBlock &BB : F)
3238df1ef08cSPhilip Reames checkBasicSSA(DT, Data, BB);
3239df1ef08cSPhilip Reames #endif
3240df1ef08cSPhilip Reames }
3241df1ef08cSPhilip Reames
findLiveSetAtInst(Instruction * Inst,GCPtrLivenessData & Data,StatepointLiveSetTy & Out)3242df1ef08cSPhilip Reames static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
3243df1ef08cSPhilip Reames StatepointLiveSetTy &Out) {
3244df1ef08cSPhilip Reames BasicBlock *BB = Inst->getParent();
3245df1ef08cSPhilip Reames
3246df1ef08cSPhilip Reames // Note: The copy is intentional and required
3247df1ef08cSPhilip Reames assert(Data.LiveOut.count(BB));
3248fb1811d3SIgor Laevsky SetVector<Value *> LiveOut = Data.LiveOut[BB];
3249df1ef08cSPhilip Reames
3250df1ef08cSPhilip Reames // We want to handle the statepoint itself oddly. It's
3251df1ef08cSPhilip Reames // call result is not live (normal), nor are it's arguments
3252df1ef08cSPhilip Reames // (unless they're used again later). This adjustment is
3253df1ef08cSPhilip Reames // specifically what we need to relocate
32545c001c36SDuncan P. N. Exon Smith computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
32555c001c36SDuncan P. N. Exon Smith LiveOut);
3256fb1811d3SIgor Laevsky LiveOut.remove(Inst);
3257df1ef08cSPhilip Reames Out.insert(LiveOut.begin(), LiveOut.end());
3258df1ef08cSPhilip Reames }
3259df1ef08cSPhilip Reames
recomputeLiveInValues(GCPtrLivenessData & RevisedLivenessData,CallBase * Call,PartiallyConstructedSafepointRecord & Info,PointerToBaseTy & PointerToBase)3260df1ef08cSPhilip Reames static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
32613160734aSChandler Carruth CallBase *Call,
326228c5e1b7SSerguei Katkov PartiallyConstructedSafepointRecord &Info,
326328c5e1b7SSerguei Katkov PointerToBaseTy &PointerToBase) {
3264df1ef08cSPhilip Reames StatepointLiveSetTy Updated;
32653160734aSChandler Carruth findLiveSetAtInst(Call, RevisedLivenessData, Updated);
3266df1ef08cSPhilip Reames
3267df1ef08cSPhilip Reames // We may have base pointers which are now live that weren't before. We need
3268df1ef08cSPhilip Reames // to update the PointerToBase structure to reflect this.
3269df1ef08cSPhilip Reames for (auto V : Updated)
327028c5e1b7SSerguei Katkov PointerToBase.insert({ V, V });
3271df1ef08cSPhilip Reames
3272b40bd1a9SSanjoy Das Info.LiveSet = Updated;
3273df1ef08cSPhilip Reames }
3274