Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1 | //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // Rewrite an existing set of gc.statepoints such that they make potential |
| 11 | // relocations performed by the garbage collector explicit in the IR. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "llvm/Pass.h" |
| 16 | #include "llvm/Analysis/CFG.h" |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 17 | #include "llvm/Analysis/InstructionSimplify.h" |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/TargetTransformInfo.h" |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/SetOperations.h" |
| 20 | #include "llvm/ADT/Statistic.h" |
| 21 | #include "llvm/ADT/DenseSet.h" |
Philip Reames | 4d80ede | 2015-04-10 23:11:26 +0000 | [diff] [blame] | 22 | #include "llvm/ADT/SetVector.h" |
Swaroop Sridhar | 665bc9c | 2015-05-20 01:07:23 +0000 | [diff] [blame] | 23 | #include "llvm/ADT/StringRef.h" |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 24 | #include "llvm/IR/BasicBlock.h" |
| 25 | #include "llvm/IR/CallSite.h" |
| 26 | #include "llvm/IR/Dominators.h" |
| 27 | #include "llvm/IR/Function.h" |
| 28 | #include "llvm/IR/IRBuilder.h" |
| 29 | #include "llvm/IR/InstIterator.h" |
| 30 | #include "llvm/IR/Instructions.h" |
| 31 | #include "llvm/IR/Intrinsics.h" |
| 32 | #include "llvm/IR/IntrinsicInst.h" |
| 33 | #include "llvm/IR/Module.h" |
Sanjoy Das | 353a19e | 2015-06-02 22:33:37 +0000 | [diff] [blame] | 34 | #include "llvm/IR/MDBuilder.h" |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 35 | #include "llvm/IR/Statepoint.h" |
| 36 | #include "llvm/IR/Value.h" |
| 37 | #include "llvm/IR/Verifier.h" |
| 38 | #include "llvm/Support/Debug.h" |
| 39 | #include "llvm/Support/CommandLine.h" |
| 40 | #include "llvm/Transforms/Scalar.h" |
| 41 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 42 | #include "llvm/Transforms/Utils/Cloning.h" |
| 43 | #include "llvm/Transforms/Utils/Local.h" |
| 44 | #include "llvm/Transforms/Utils/PromoteMemToReg.h" |
| 45 | |
| 46 | #define DEBUG_TYPE "rewrite-statepoints-for-gc" |
| 47 | |
| 48 | using namespace llvm; |
| 49 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 50 | // Print the liveset found at the insert location |
| 51 | static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden, |
| 52 | cl::init(false)); |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 53 | static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden, |
| 54 | cl::init(false)); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 55 | // Print out the base pointers for debugging |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 56 | static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden, |
| 57 | cl::init(false)); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 58 | |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 59 | // Cost threshold measuring when it is profitable to rematerialize value instead |
| 60 | // of relocating it |
| 61 | static cl::opt<unsigned> |
| 62 | RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden, |
| 63 | cl::init(6)); |
| 64 | |
Philip Reames | e73300b | 2015-04-13 16:41:32 +0000 | [diff] [blame] | 65 | #ifdef XDEBUG |
| 66 | static bool ClobberNonLive = true; |
| 67 | #else |
| 68 | static bool ClobberNonLive = false; |
| 69 | #endif |
| 70 | static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live", |
| 71 | cl::location(ClobberNonLive), |
| 72 | cl::Hidden); |
| 73 | |
Benjamin Kramer | 6f66545 | 2015-02-20 14:00:58 +0000 | [diff] [blame] | 74 | namespace { |
Sanjoy Das | ea45f0e | 2015-06-02 22:33:34 +0000 | [diff] [blame] | 75 | struct RewriteStatepointsForGC : public ModulePass { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 76 | static char ID; // Pass identification, replacement for typeid |
| 77 | |
Sanjoy Das | ea45f0e | 2015-06-02 22:33:34 +0000 | [diff] [blame] | 78 | RewriteStatepointsForGC() : ModulePass(ID) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 79 | initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry()); |
| 80 | } |
Sanjoy Das | ea45f0e | 2015-06-02 22:33:34 +0000 | [diff] [blame] | 81 | bool runOnFunction(Function &F); |
| 82 | bool runOnModule(Module &M) override { |
| 83 | bool Changed = false; |
| 84 | for (Function &F : M) |
| 85 | Changed |= runOnFunction(F); |
Sanjoy Das | 353a19e | 2015-06-02 22:33:37 +0000 | [diff] [blame] | 86 | |
| 87 | if (Changed) { |
| 88 | // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn |
| 89 | // returns true for at least one function in the module. Since at least |
| 90 | // one function changed, we know that the precondition is satisfied. |
| 91 | stripDereferenceabilityInfo(M); |
| 92 | } |
| 93 | |
Sanjoy Das | ea45f0e | 2015-06-02 22:33:34 +0000 | [diff] [blame] | 94 | return Changed; |
| 95 | } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 96 | |
| 97 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 98 | // We add and rewrite a bunch of instructions, but don't really do much |
| 99 | // else. We could in theory preserve a lot more analyses here. |
| 100 | AU.addRequired<DominatorTreeWrapperPass>(); |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 101 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 102 | } |
Sanjoy Das | 353a19e | 2015-06-02 22:33:37 +0000 | [diff] [blame] | 103 | |
| 104 | /// The IR fed into RewriteStatepointsForGC may have had attributes implying |
| 105 | /// dereferenceability that are no longer valid/correct after |
| 106 | /// RewriteStatepointsForGC has run. This is because semantically, after |
| 107 | /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire |
| 108 | /// heap. stripDereferenceabilityInfo (conservatively) restores correctness |
| 109 | /// by erasing all attributes in the module that externally imply |
| 110 | /// dereferenceability. |
| 111 | /// |
| 112 | void stripDereferenceabilityInfo(Module &M); |
| 113 | |
| 114 | // Helpers for stripDereferenceabilityInfo |
| 115 | void stripDereferenceabilityInfoFromBody(Function &F); |
| 116 | void stripDereferenceabilityInfoFromPrototype(Function &F); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 117 | }; |
Benjamin Kramer | 6f66545 | 2015-02-20 14:00:58 +0000 | [diff] [blame] | 118 | } // namespace |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 119 | |
| 120 | char RewriteStatepointsForGC::ID = 0; |
| 121 | |
Sanjoy Das | ea45f0e | 2015-06-02 22:33:34 +0000 | [diff] [blame] | 122 | ModulePass *llvm::createRewriteStatepointsForGCPass() { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 123 | return new RewriteStatepointsForGC(); |
| 124 | } |
| 125 | |
| 126 | INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc", |
| 127 | "Make relocations explicit at statepoints", false, false) |
| 128 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 129 | INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc", |
| 130 | "Make relocations explicit at statepoints", false, false) |
| 131 | |
| 132 | namespace { |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 133 | struct GCPtrLivenessData { |
| 134 | /// Values defined in this block. |
| 135 | DenseMap<BasicBlock *, DenseSet<Value *>> KillSet; |
| 136 | /// Values used in this block (and thus live); does not included values |
| 137 | /// killed within this block. |
| 138 | DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet; |
| 139 | |
| 140 | /// Values live into this basic block (i.e. used by any |
| 141 | /// instruction in this basic block or ones reachable from here) |
| 142 | DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn; |
| 143 | |
| 144 | /// Values live out of this basic block (i.e. live into |
| 145 | /// any successor block) |
| 146 | DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut; |
| 147 | }; |
| 148 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 149 | // The type of the internal cache used inside the findBasePointers family |
| 150 | // of functions. From the callers perspective, this is an opaque type and |
| 151 | // should not be inspected. |
| 152 | // |
| 153 | // In the actual implementation this caches two relations: |
| 154 | // - The base relation itself (i.e. this pointer is based on that one) |
| 155 | // - The base defining value relation (i.e. before base_phi insertion) |
| 156 | // Generally, after the execution of a full findBasePointer call, only the |
| 157 | // base relation will remain. Internally, we add a mixture of the two |
| 158 | // types, then update all the second type to the first type |
Philip Reames | e9c3b9b | 2015-02-20 22:48:20 +0000 | [diff] [blame] | 159 | typedef DenseMap<Value *, Value *> DefiningValueMapTy; |
Philip Reames | 1f01754 | 2015-02-20 23:16:52 +0000 | [diff] [blame] | 160 | typedef DenseSet<llvm::Value *> StatepointLiveSetTy; |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 161 | typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 162 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 163 | struct PartiallyConstructedSafepointRecord { |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 164 | /// The set of values known to be live across this safepoint |
Philip Reames | 860660e | 2015-02-20 22:05:18 +0000 | [diff] [blame] | 165 | StatepointLiveSetTy liveset; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 166 | |
| 167 | /// Mapping from live pointers to a base-defining-value |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 168 | DenseMap<llvm::Value *, llvm::Value *> PointerToBase; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 169 | |
Philip Reames | 0a3240f | 2015-02-20 21:34:11 +0000 | [diff] [blame] | 170 | /// The *new* gc.statepoint instruction itself. This produces the token |
| 171 | /// that normal path gc.relocates and the gc.result are tied to. |
| 172 | Instruction *StatepointToken; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 173 | |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 174 | /// Instruction to which exceptional gc relocates are attached |
| 175 | /// Makes it easier to iterate through them during relocationViaAlloca. |
| 176 | Instruction *UnwindToken; |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 177 | |
| 178 | /// Record live values we are rematerialized instead of relocating. |
| 179 | /// They are not included into 'liveset' field. |
| 180 | /// Maps rematerialized copy to it's original value. |
| 181 | RematerializedValueMapTy RematerializedValues; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 182 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 183 | } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 184 | |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 185 | /// Compute the live-in set for every basic block in the function |
| 186 | static void computeLiveInValues(DominatorTree &DT, Function &F, |
| 187 | GCPtrLivenessData &Data); |
| 188 | |
| 189 | /// Given results from the dataflow liveness computation, find the set of live |
| 190 | /// Values at a particular instruction. |
| 191 | static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data, |
| 192 | StatepointLiveSetTy &out); |
| 193 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 194 | // TODO: Once we can get to the GCStrategy, this becomes |
| 195 | // Optional<bool> isGCManagedPointer(const Value *V) const override { |
| 196 | |
Craig Topper | e3dcce9 | 2015-08-01 22:20:21 +0000 | [diff] [blame] | 197 | static bool isGCPointerType(Type *T) { |
| 198 | if (auto *PT = dyn_cast<PointerType>(T)) |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 199 | // For the sake of this example GC, we arbitrarily pick addrspace(1) as our |
| 200 | // GC managed heap. We know that a pointer into this heap needs to be |
| 201 | // updated and that no other pointer does. |
| 202 | return (1 == PT->getAddressSpace()); |
| 203 | return false; |
| 204 | } |
| 205 | |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 206 | // Return true if this type is one which a) is a gc pointer or contains a GC |
| 207 | // pointer and b) is of a type this code expects to encounter as a live value. |
| 208 | // (The insertion code will assert that a type which matches (a) and not (b) |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 209 | // is not encountered.) |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 210 | static bool isHandledGCPointerType(Type *T) { |
| 211 | // We fully support gc pointers |
| 212 | if (isGCPointerType(T)) |
| 213 | return true; |
| 214 | // We partially support vectors of gc pointers. The code will assert if it |
| 215 | // can't handle something. |
| 216 | if (auto VT = dyn_cast<VectorType>(T)) |
| 217 | if (isGCPointerType(VT->getElementType())) |
| 218 | return true; |
| 219 | return false; |
| 220 | } |
| 221 | |
| 222 | #ifndef NDEBUG |
| 223 | /// Returns true if this type contains a gc pointer whether we know how to |
| 224 | /// handle that type or not. |
| 225 | static bool containsGCPtrType(Type *Ty) { |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 226 | if (isGCPointerType(Ty)) |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 227 | return true; |
| 228 | if (VectorType *VT = dyn_cast<VectorType>(Ty)) |
| 229 | return isGCPointerType(VT->getScalarType()); |
| 230 | if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) |
| 231 | return containsGCPtrType(AT->getElementType()); |
| 232 | if (StructType *ST = dyn_cast<StructType>(Ty)) |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 233 | return std::any_of( |
| 234 | ST->subtypes().begin(), ST->subtypes().end(), |
| 235 | [](Type *SubType) { return containsGCPtrType(SubType); }); |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 236 | return false; |
| 237 | } |
| 238 | |
| 239 | // Returns true if this is a type which a) is a gc pointer or contains a GC |
| 240 | // pointer and b) is of a type which the code doesn't expect (i.e. first class |
| 241 | // aggregates). Used to trip assertions. |
| 242 | static bool isUnhandledGCPointerType(Type *Ty) { |
| 243 | return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty); |
| 244 | } |
| 245 | #endif |
| 246 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 247 | static bool order_by_name(llvm::Value *a, llvm::Value *b) { |
| 248 | if (a->hasName() && b->hasName()) { |
| 249 | return -1 == a->getName().compare(b->getName()); |
| 250 | } else if (a->hasName() && !b->hasName()) { |
| 251 | return true; |
| 252 | } else if (!a->hasName() && b->hasName()) { |
| 253 | return false; |
| 254 | } else { |
| 255 | // Better than nothing, but not stable |
| 256 | return a < b; |
| 257 | } |
| 258 | } |
| 259 | |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 260 | // Conservatively identifies any definitions which might be live at the |
| 261 | // given instruction. The analysis is performed immediately before the |
| 262 | // given instruction. Values defined by that instruction are not considered |
| 263 | // live. Values used by that instruction are considered live. |
| 264 | static void analyzeParsePointLiveness( |
| 265 | DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, |
| 266 | const CallSite &CS, PartiallyConstructedSafepointRecord &result) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 267 | Instruction *inst = CS.getInstruction(); |
| 268 | |
Philip Reames | 1f01754 | 2015-02-20 23:16:52 +0000 | [diff] [blame] | 269 | StatepointLiveSetTy liveset; |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 270 | findLiveSetAtInst(inst, OriginalLivenessData, liveset); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 271 | |
| 272 | if (PrintLiveSet) { |
| 273 | // Note: This output is used by several of the test cases |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 274 | // The order of elements in a set is not stable, put them in a vec and sort |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 275 | // by name |
Philip Reames | dab35f3 | 2015-09-02 21:11:44 +0000 | [diff] [blame] | 276 | SmallVector<Value *, 64> Temp; |
| 277 | Temp.insert(Temp.end(), liveset.begin(), liveset.end()); |
| 278 | std::sort(Temp.begin(), Temp.end(), order_by_name); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 279 | errs() << "Live Variables:\n"; |
Philip Reames | dab35f3 | 2015-09-02 21:11:44 +0000 | [diff] [blame] | 280 | for (Value *V : Temp) |
| 281 | dbgs() << " " << V->getName() << " " << *V << "\n"; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 282 | } |
| 283 | if (PrintLiveSetSize) { |
| 284 | errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n"; |
| 285 | errs() << "Number live values: " << liveset.size() << "\n"; |
| 286 | } |
| 287 | result.liveset = liveset; |
| 288 | } |
| 289 | |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 290 | static bool isKnownBaseResult(Value *V); |
| 291 | namespace { |
| 292 | /// A single base defining value - An immediate base defining value for an |
| 293 | /// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'. |
| 294 | /// For instructions which have multiple pointer [vector] inputs or that |
| 295 | /// transition between vector and scalar types, there is no immediate base |
| 296 | /// defining value. The 'base defining value' for 'Def' is the transitive |
| 297 | /// closure of this relation stopping at the first instruction which has no |
| 298 | /// immediate base defining value. The b.d.v. might itself be a base pointer, |
| 299 | /// but it can also be an arbitrary derived pointer. |
| 300 | struct BaseDefiningValueResult { |
| 301 | /// Contains the value which is the base defining value. |
| 302 | Value * const BDV; |
| 303 | /// True if the base defining value is also known to be an actual base |
| 304 | /// pointer. |
| 305 | const bool IsKnownBase; |
| 306 | BaseDefiningValueResult(Value *BDV, bool IsKnownBase) |
| 307 | : BDV(BDV), IsKnownBase(IsKnownBase) { |
| 308 | #ifndef NDEBUG |
| 309 | // Check consistency between new and old means of checking whether a BDV is |
| 310 | // a base. |
| 311 | bool MustBeBase = isKnownBaseResult(BDV); |
| 312 | assert(!MustBeBase || MustBeBase == IsKnownBase); |
| 313 | #endif |
| 314 | } |
| 315 | }; |
| 316 | } |
| 317 | |
| 318 | static BaseDefiningValueResult findBaseDefiningValue(Value *I); |
Philip Reames | 311f710 | 2015-05-12 22:19:52 +0000 | [diff] [blame] | 319 | |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 320 | /// Return a base defining value for the 'Index' element of the given vector |
| 321 | /// instruction 'I'. If Index is null, returns a BDV for the entire vector |
| 322 | /// 'I'. As an optimization, this method will try to determine when the |
| 323 | /// element is known to already be a base pointer. If this can be established, |
| 324 | /// the second value in the returned pair will be true. Note that either a |
| 325 | /// vector or a pointer typed value can be returned. For the former, the |
| 326 | /// vector returned is a BDV (and possibly a base) of the entire vector 'I'. |
| 327 | /// If the later, the return pointer is a BDV (or possibly a base) for the |
| 328 | /// particular element in 'I'. |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 329 | static BaseDefiningValueResult |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 330 | findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) { |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 331 | assert(I->getType()->isVectorTy() && |
| 332 | cast<VectorType>(I->getType())->getElementType()->isPointerTy() && |
| 333 | "Illegal to ask for the base pointer of a non-pointer type"); |
| 334 | |
| 335 | // Each case parallels findBaseDefiningValue below, see that code for |
| 336 | // detailed motivation. |
| 337 | |
| 338 | if (isa<Argument>(I)) |
| 339 | // An incoming argument to the function is a base pointer |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 340 | return BaseDefiningValueResult(I, true); |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 341 | |
| 342 | // We shouldn't see the address of a global as a vector value? |
| 343 | assert(!isa<GlobalVariable>(I) && |
| 344 | "unexpected global variable found in base of vector"); |
| 345 | |
| 346 | // inlining could possibly introduce phi node that contains |
| 347 | // undef if callee has multiple returns |
| 348 | if (isa<UndefValue>(I)) |
| 349 | // utterly meaningless, but useful for dealing with partially optimized |
| 350 | // code. |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 351 | return BaseDefiningValueResult(I, true); |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 352 | |
| 353 | // Due to inheritance, this must be _after_ the global variable and undef |
| 354 | // checks |
| 355 | if (Constant *Con = dyn_cast<Constant>(I)) { |
| 356 | assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) && |
| 357 | "order of checks wrong!"); |
| 358 | assert(Con->isNullValue() && "null is the only case which makes sense"); |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 359 | return BaseDefiningValueResult(Con, true); |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 360 | } |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 361 | |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 362 | if (isa<LoadInst>(I)) |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 363 | return BaseDefiningValueResult(I, true); |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 364 | |
Philip Reames | 311f710 | 2015-05-12 22:19:52 +0000 | [diff] [blame] | 365 | // For an insert element, we might be able to look through it if we know |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 366 | // something about the indexes. |
Philip Reames | 311f710 | 2015-05-12 22:19:52 +0000 | [diff] [blame] | 367 | if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) { |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 368 | if (Index) { |
| 369 | Value *InsertIndex = IEI->getOperand(2); |
| 370 | // This index is inserting the value, look for its BDV |
| 371 | if (InsertIndex == Index) |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 372 | return findBaseDefiningValue(IEI->getOperand(1)); |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 373 | // Both constant, and can't be equal per above. This insert is definitely |
| 374 | // not relevant, look back at the rest of the vector and keep trying. |
| 375 | if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex)) |
| 376 | return findBaseDefiningValueOfVector(IEI->getOperand(0), Index); |
| 377 | } |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 378 | |
| 379 | // If both inputs to the insertelement are known bases, then so is the |
| 380 | // insertelement itself. NOTE: This should be handled within the generic |
| 381 | // base pointer inference code and after http://reviews.llvm.org/D12583, |
| 382 | // will be. However, when strengthening asserts I needed to add this to |
| 383 | // keep an existing test passing which was 'working'. FIXME |
| 384 | if (findBaseDefiningValue(IEI->getOperand(0)).IsKnownBase && |
| 385 | findBaseDefiningValue(IEI->getOperand(1)).IsKnownBase) |
| 386 | return BaseDefiningValueResult(IEI, true); |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 387 | |
| 388 | // We don't know whether this vector contains entirely base pointers or |
| 389 | // not. To be conservatively correct, we treat it as a BDV and will |
| 390 | // duplicate code as needed to construct a parallel vector of bases. |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 391 | return BaseDefiningValueResult(IEI, false); |
Philip Reames | 311f710 | 2015-05-12 22:19:52 +0000 | [diff] [blame] | 392 | } |
NAKAMURA Takumi | fb3bd71 | 2015-05-25 01:43:23 +0000 | [diff] [blame] | 393 | |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 394 | if (isa<ShuffleVectorInst>(I)) |
| 395 | // We don't know whether this vector contains entirely base pointers or |
| 396 | // not. To be conservatively correct, we treat it as a BDV and will |
| 397 | // duplicate code as needed to construct a parallel vector of bases. |
| 398 | // TODO: There a number of local optimizations which could be applied here |
| 399 | // for particular sufflevector patterns. |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 400 | return BaseDefiningValueResult(I, false); |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 401 | |
| 402 | // A PHI or Select is a base defining value. The outer findBasePointer |
| 403 | // algorithm is responsible for constructing a base value for this BDV. |
| 404 | assert((isa<SelectInst>(I) || isa<PHINode>(I)) && |
| 405 | "unknown vector instruction - no base found for vector element"); |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 406 | return BaseDefiningValueResult(I, false); |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 407 | } |
| 408 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 409 | /// Helper function for findBasePointer - Will return a value which either a) |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 410 | /// defines the base pointer for the input, b) blocks the simple search |
| 411 | /// (i.e. a PHI or Select of two derived pointers), or c) involves a change |
| 412 | /// from pointer to vector type or back. |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 413 | static BaseDefiningValueResult findBaseDefiningValue(Value *I) { |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 414 | if (I->getType()->isVectorTy()) |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 415 | return findBaseDefiningValueOfVector(I); |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 416 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 417 | assert(I->getType()->isPointerTy() && |
| 418 | "Illegal to ask for the base pointer of a non-pointer type"); |
| 419 | |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 420 | if (isa<Argument>(I)) |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 421 | // An incoming argument to the function is a base pointer |
| 422 | // We should have never reached here if this argument isn't an gc value |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 423 | return BaseDefiningValueResult(I, true); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 424 | |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 425 | if (isa<GlobalVariable>(I)) |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 426 | // base case |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 427 | return BaseDefiningValueResult(I, true); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 428 | |
| 429 | // inlining could possibly introduce phi node that contains |
| 430 | // undef if callee has multiple returns |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 431 | if (isa<UndefValue>(I)) |
| 432 | // utterly meaningless, but useful for dealing with |
| 433 | // partially optimized code. |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 434 | return BaseDefiningValueResult(I, true); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 435 | |
| 436 | // Due to inheritance, this must be _after_ the global variable and undef |
| 437 | // checks |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 438 | if (isa<Constant>(I)) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 439 | assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) && |
| 440 | "order of checks wrong!"); |
| 441 | // Note: Finding a constant base for something marked for relocation |
| 442 | // doesn't really make sense. The most likely case is either a) some |
| 443 | // screwed up the address space usage or b) your validating against |
| 444 | // compiled C++ code w/o the proper separation. The only real exception |
| 445 | // is a null pointer. You could have generic code written to index of |
| 446 | // off a potentially null value and have proven it null. We also use |
| 447 | // null pointers in dead paths of relocation phis (which we might later |
| 448 | // want to find a base pointer for). |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 449 | assert(isa<ConstantPointerNull>(I) && |
Philip Reames | 24c6cd5 | 2015-03-27 05:47:00 +0000 | [diff] [blame] | 450 | "null is the only case which makes sense"); |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 451 | return BaseDefiningValueResult(I, true); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 452 | } |
| 453 | |
| 454 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 455 | Value *Def = CI->stripPointerCasts(); |
David Blaikie | 82ad787 | 2015-02-20 23:44:24 +0000 | [diff] [blame] | 456 | // If we find a cast instruction here, it means we've found a cast which is |
| 457 | // not simply a pointer cast (i.e. an inttoptr). We don't know how to |
| 458 | // handle int->ptr conversion. |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 459 | assert(!isa<CastInst>(Def) && "shouldn't find another cast here"); |
| 460 | return findBaseDefiningValue(Def); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 461 | } |
| 462 | |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 463 | if (isa<LoadInst>(I)) |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 464 | // The value loaded is an gc base itself |
| 465 | return BaseDefiningValueResult(I, true); |
| 466 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 467 | |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 468 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) |
| 469 | // The base of this GEP is the base |
| 470 | return findBaseDefiningValue(GEP->getPointerOperand()); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 471 | |
| 472 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { |
| 473 | switch (II->getIntrinsicID()) { |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 474 | case Intrinsic::experimental_gc_result_ptr: |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 475 | default: |
| 476 | // fall through to general call handling |
| 477 | break; |
| 478 | case Intrinsic::experimental_gc_statepoint: |
| 479 | case Intrinsic::experimental_gc_result_float: |
| 480 | case Intrinsic::experimental_gc_result_int: |
| 481 | llvm_unreachable("these don't produce pointers"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 482 | case Intrinsic::experimental_gc_relocate: { |
| 483 | // Rerunning safepoint insertion after safepoints are already |
| 484 | // inserted is not supported. It could probably be made to work, |
| 485 | // but why are you doing this? There's no good reason. |
| 486 | llvm_unreachable("repeat safepoint insertion is not supported"); |
| 487 | } |
| 488 | case Intrinsic::gcroot: |
| 489 | // Currently, this mechanism hasn't been extended to work with gcroot. |
| 490 | // There's no reason it couldn't be, but I haven't thought about the |
| 491 | // implications much. |
| 492 | llvm_unreachable( |
| 493 | "interaction with the gcroot mechanism is not supported"); |
| 494 | } |
| 495 | } |
| 496 | // We assume that functions in the source language only return base |
| 497 | // pointers. This should probably be generalized via attributes to support |
| 498 | // both source language and internal functions. |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 499 | if (isa<CallInst>(I) || isa<InvokeInst>(I)) |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 500 | return BaseDefiningValueResult(I, true); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 501 | |
| 502 | // I have absolutely no idea how to implement this part yet. It's not |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 503 | // necessarily hard, I just haven't really looked at it yet. |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 504 | assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented"); |
| 505 | |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 506 | if (isa<AtomicCmpXchgInst>(I)) |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 507 | // A CAS is effectively a atomic store and load combined under a |
| 508 | // predicate. From the perspective of base pointers, we just treat it |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 509 | // like a load. |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 510 | return BaseDefiningValueResult(I, true); |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 511 | |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 512 | assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are " |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 513 | "binary ops which don't apply to pointers"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 514 | |
| 515 | // The aggregate ops. Aggregates can either be in the heap or on the |
| 516 | // stack, but in either case, this is simply a field load. As a result, |
| 517 | // this is a defining definition of the base just like a load is. |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 518 | if (isa<ExtractValueInst>(I)) |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 519 | return BaseDefiningValueResult(I, true); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 520 | |
| 521 | // We should never see an insert vector since that would require we be |
| 522 | // tracing back a struct value not a pointer value. |
| 523 | assert(!isa<InsertValueInst>(I) && |
| 524 | "Base pointer for a struct is meaningless"); |
| 525 | |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 526 | // An extractelement produces a base result exactly when it's input does. |
| 527 | // We may need to insert a parallel instruction to extract the appropriate |
| 528 | // element out of the base vector corresponding to the input. Given this, |
| 529 | // it's analogous to the phi and select case even though it's not a merge. |
| 530 | if (auto *EEI = dyn_cast<ExtractElementInst>(I)) { |
| 531 | Value *VectorOperand = EEI->getVectorOperand(); |
| 532 | Value *Index = EEI->getIndexOperand(); |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 533 | auto VecResult = findBaseDefiningValueOfVector(VectorOperand, Index); |
| 534 | Value *VectorBase = VecResult.BDV; |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 535 | if (VectorBase->getType()->isPointerTy()) |
| 536 | // We found a BDV for this specific element with the vector. This is an |
| 537 | // optimization, but in practice it covers most of the useful cases |
| 538 | // created via scalarization. Note: The peephole optimization here is |
| 539 | // currently needed for correctness since the general algorithm doesn't |
| 540 | // yet handle insertelements. That will change shortly. |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 541 | return BaseDefiningValueResult(VectorBase, VecResult.IsKnownBase); |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 542 | else { |
| 543 | assert(VectorBase->getType()->isVectorTy()); |
| 544 | // Otherwise, we have an instruction which potentially produces a |
| 545 | // derived pointer and we need findBasePointers to clone code for us |
| 546 | // such that we can create an instruction which produces the |
| 547 | // accompanying base pointer. |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 548 | return BaseDefiningValueResult(I, VecResult.IsKnownBase); |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 549 | } |
| 550 | } |
| 551 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 552 | // The last two cases here don't return a base pointer. Instead, they |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 553 | // return a value which dynamically selects from among several base |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 554 | // derived pointers (each with it's own base potentially). It's the job of |
| 555 | // the caller to resolve these. |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 556 | assert((isa<SelectInst>(I) || isa<PHINode>(I)) && |
Philip Reames | aa66dfa | 2015-03-27 05:34:44 +0000 | [diff] [blame] | 557 | "missing instruction case in findBaseDefiningValing"); |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 558 | return BaseDefiningValueResult(I, false); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 559 | } |
| 560 | |
| 561 | /// Returns the base defining value for this value. |
Philip Reames | 18d0feb | 2015-03-27 05:39:32 +0000 | [diff] [blame] | 562 | static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) { |
| 563 | Value *&Cached = Cache[I]; |
Benjamin Kramer | 6f66545 | 2015-02-20 14:00:58 +0000 | [diff] [blame] | 564 | if (!Cached) { |
Philip Reames | f5b8e47 | 2015-09-03 21:34:30 +0000 | [diff] [blame] | 565 | Cached = findBaseDefiningValue(I).BDV; |
Philip Reames | 2a892a6 | 2015-07-23 22:25:26 +0000 | [diff] [blame] | 566 | DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> " |
| 567 | << Cached->getName() << "\n"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 568 | } |
Philip Reames | 18d0feb | 2015-03-27 05:39:32 +0000 | [diff] [blame] | 569 | assert(Cache[I] != nullptr); |
Benjamin Kramer | 6f66545 | 2015-02-20 14:00:58 +0000 | [diff] [blame] | 570 | return Cached; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 571 | } |
| 572 | |
| 573 | /// Return a base pointer for this value if known. Otherwise, return it's |
| 574 | /// base defining value. |
Philip Reames | 18d0feb | 2015-03-27 05:39:32 +0000 | [diff] [blame] | 575 | static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) { |
| 576 | Value *Def = findBaseDefiningValueCached(I, Cache); |
| 577 | auto Found = Cache.find(Def); |
| 578 | if (Found != Cache.end()) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 579 | // Either a base-of relation, or a self reference. Caller must check. |
Benjamin Kramer | 6f66545 | 2015-02-20 14:00:58 +0000 | [diff] [blame] | 580 | return Found->second; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 581 | } |
| 582 | // Only a BDV available |
Philip Reames | 18d0feb | 2015-03-27 05:39:32 +0000 | [diff] [blame] | 583 | return Def; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 584 | } |
| 585 | |
| 586 | /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV, |
| 587 | /// is it known to be a base pointer? Or do we need to continue searching. |
Philip Reames | 18d0feb | 2015-03-27 05:39:32 +0000 | [diff] [blame] | 588 | static bool isKnownBaseResult(Value *V) { |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 589 | if (!isa<PHINode>(V) && !isa<SelectInst>(V) && !isa<ExtractElementInst>(V)) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 590 | // no recursion possible |
| 591 | return true; |
| 592 | } |
Philip Reames | 18d0feb | 2015-03-27 05:39:32 +0000 | [diff] [blame] | 593 | if (isa<Instruction>(V) && |
| 594 | cast<Instruction>(V)->getMetadata("is_base_value")) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 595 | // This is a previously inserted base phi or select. We know |
| 596 | // that this is a base value. |
| 597 | return true; |
| 598 | } |
| 599 | |
| 600 | // We need to keep searching |
| 601 | return false; |
| 602 | } |
| 603 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 604 | namespace { |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 605 | /// Models the state of a single base defining value in the findBasePointer |
| 606 | /// algorithm for determining where a new instruction is needed to propagate |
| 607 | /// the base of this BDV. |
| 608 | class BDVState { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 609 | public: |
| 610 | enum Status { Unknown, Base, Conflict }; |
| 611 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 612 | BDVState(Status s, Value *b = nullptr) : status(s), base(b) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 613 | assert(status != Base || b); |
| 614 | } |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 615 | explicit BDVState(Value *b) : status(Base), base(b) {} |
| 616 | BDVState() : status(Unknown), base(nullptr) {} |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 617 | |
| 618 | Status getStatus() const { return status; } |
| 619 | Value *getBase() const { return base; } |
| 620 | |
| 621 | bool isBase() const { return getStatus() == Base; } |
| 622 | bool isUnknown() const { return getStatus() == Unknown; } |
| 623 | bool isConflict() const { return getStatus() == Conflict; } |
| 624 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 625 | bool operator==(const BDVState &other) const { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 626 | return base == other.base && status == other.status; |
| 627 | } |
| 628 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 629 | bool operator!=(const BDVState &other) const { return !(*this == other); } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 630 | |
Philip Reames | 2a892a6 | 2015-07-23 22:25:26 +0000 | [diff] [blame] | 631 | LLVM_DUMP_METHOD |
| 632 | void dump() const { print(dbgs()); dbgs() << '\n'; } |
| 633 | |
| 634 | void print(raw_ostream &OS) const { |
Philip Reames | dab35f3 | 2015-09-02 21:11:44 +0000 | [diff] [blame] | 635 | switch (status) { |
| 636 | case Unknown: |
| 637 | OS << "U"; |
| 638 | break; |
| 639 | case Base: |
| 640 | OS << "B"; |
| 641 | break; |
| 642 | case Conflict: |
| 643 | OS << "C"; |
| 644 | break; |
| 645 | }; |
| 646 | OS << " (" << base << " - " |
Philip Reames | 2a892a6 | 2015-07-23 22:25:26 +0000 | [diff] [blame] | 647 | << (base ? base->getName() : "nullptr") << "): "; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 648 | } |
| 649 | |
| 650 | private: |
| 651 | Status status; |
| 652 | Value *base; // non null only if status == base |
| 653 | }; |
Philip Reames | b3967cd | 2015-09-02 22:30:53 +0000 | [diff] [blame] | 654 | } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 655 | |
Philip Reames | 6906e92 | 2015-09-02 21:57:17 +0000 | [diff] [blame] | 656 | #ifndef NDEBUG |
Philip Reames | b3967cd | 2015-09-02 22:30:53 +0000 | [diff] [blame] | 657 | static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) { |
Philip Reames | 2a892a6 | 2015-07-23 22:25:26 +0000 | [diff] [blame] | 658 | State.print(OS); |
| 659 | return OS; |
| 660 | } |
Philip Reames | 6906e92 | 2015-09-02 21:57:17 +0000 | [diff] [blame] | 661 | #endif |
Philip Reames | 2a892a6 | 2015-07-23 22:25:26 +0000 | [diff] [blame] | 662 | |
Philip Reames | b3967cd | 2015-09-02 22:30:53 +0000 | [diff] [blame] | 663 | namespace { |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 664 | typedef DenseMap<Value *, BDVState> ConflictStateMapTy; |
| 665 | // Values of type BDVState form a lattice, and this is a helper |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 666 | // class that implementes the meet operation. The meat of the meet |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 667 | // operation is implemented in MeetBDVStates::pureMeet |
| 668 | class MeetBDVStates { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 669 | public: |
Philip Reames | 273e6bb | 2015-07-23 21:41:27 +0000 | [diff] [blame] | 670 | /// Initializes the currentResult to the TOP state so that if can be met with |
| 671 | /// any other state to produce that state. |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 672 | MeetBDVStates() {} |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 673 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 674 | // Destructively meet the current result with the given BDVState |
| 675 | void meetWith(BDVState otherState) { |
Philip Reames | 273e6bb | 2015-07-23 21:41:27 +0000 | [diff] [blame] | 676 | currentResult = meet(otherState, currentResult); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 677 | } |
| 678 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 679 | BDVState getResult() const { return currentResult; } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 680 | |
| 681 | private: |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 682 | BDVState currentResult; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 683 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 684 | /// Perform a meet operation on two elements of the BDVState lattice. |
| 685 | static BDVState meet(BDVState LHS, BDVState RHS) { |
Philip Reames | 273e6bb | 2015-07-23 21:41:27 +0000 | [diff] [blame] | 686 | assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) && |
| 687 | "math is wrong: meet does not commute!"); |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 688 | BDVState Result = pureMeet(LHS, RHS); |
Philip Reames | 2a892a6 | 2015-07-23 22:25:26 +0000 | [diff] [blame] | 689 | DEBUG(dbgs() << "meet of " << LHS << " with " << RHS |
| 690 | << " produced " << Result << "\n"); |
| 691 | return Result; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 692 | } |
| 693 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 694 | static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 695 | switch (stateA.getStatus()) { |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 696 | case BDVState::Unknown: |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 697 | return stateB; |
| 698 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 699 | case BDVState::Base: |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 700 | assert(stateA.getBase() && "can't be null"); |
David Blaikie | 82ad787 | 2015-02-20 23:44:24 +0000 | [diff] [blame] | 701 | if (stateB.isUnknown()) |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 702 | return stateA; |
David Blaikie | 82ad787 | 2015-02-20 23:44:24 +0000 | [diff] [blame] | 703 | |
| 704 | if (stateB.isBase()) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 705 | if (stateA.getBase() == stateB.getBase()) { |
| 706 | assert(stateA == stateB && "equality broken!"); |
| 707 | return stateA; |
| 708 | } |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 709 | return BDVState(BDVState::Conflict); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 710 | } |
David Blaikie | 82ad787 | 2015-02-20 23:44:24 +0000 | [diff] [blame] | 711 | assert(stateB.isConflict() && "only three states!"); |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 712 | return BDVState(BDVState::Conflict); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 713 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 714 | case BDVState::Conflict: |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 715 | return stateA; |
| 716 | } |
Reid Kleckner | a070ee5 | 2015-02-20 19:46:02 +0000 | [diff] [blame] | 717 | llvm_unreachable("only three states!"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 718 | } |
| 719 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 720 | } |
Philip Reames | b3967cd | 2015-09-02 22:30:53 +0000 | [diff] [blame] | 721 | |
| 722 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 723 | /// For a given value or instruction, figure out what base ptr it's derived |
| 724 | /// from. For gc objects, this is simply itself. On success, returns a value |
| 725 | /// which is the base pointer. (This is reliable and can be used for |
| 726 | /// relocation.) On failure, returns nullptr. |
Philip Reames | ba19849 | 2015-04-14 00:41:34 +0000 | [diff] [blame] | 727 | static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 728 | Value *def = findBaseOrBDV(I, cache); |
| 729 | |
| 730 | if (isKnownBaseResult(def)) { |
| 731 | return def; |
| 732 | } |
| 733 | |
| 734 | // Here's the rough algorithm: |
| 735 | // - For every SSA value, construct a mapping to either an actual base |
| 736 | // pointer or a PHI which obscures the base pointer. |
| 737 | // - Construct a mapping from PHI to unknown TOP state. Use an |
| 738 | // optimistic algorithm to propagate base pointer information. Lattice |
| 739 | // looks like: |
| 740 | // UNKNOWN |
| 741 | // b1 b2 b3 b4 |
| 742 | // CONFLICT |
| 743 | // When algorithm terminates, all PHIs will either have a single concrete |
| 744 | // base or be in a conflict state. |
| 745 | // - For every conflict, insert a dummy PHI node without arguments. Add |
| 746 | // these to the base[Instruction] = BasePtr mapping. For every |
| 747 | // non-conflict, add the actual base. |
| 748 | // - For every conflict, add arguments for the base[a] of each input |
| 749 | // arguments. |
| 750 | // |
| 751 | // Note: A simpler form of this would be to add the conflict form of all |
| 752 | // PHIs without running the optimistic algorithm. This would be |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 753 | // analogous to pessimistic data flow and would likely lead to an |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 754 | // overall worse solution. |
| 755 | |
Philip Reames | 29e9ae7 | 2015-07-24 00:42:55 +0000 | [diff] [blame] | 756 | #ifndef NDEBUG |
Philip Reames | 88958b2 | 2015-07-24 00:02:11 +0000 | [diff] [blame] | 757 | auto isExpectedBDVType = [](Value *BDV) { |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 758 | return isa<PHINode>(BDV) || isa<SelectInst>(BDV) || isa<ExtractElementInst>(BDV); |
Philip Reames | 88958b2 | 2015-07-24 00:02:11 +0000 | [diff] [blame] | 759 | }; |
Philip Reames | 29e9ae7 | 2015-07-24 00:42:55 +0000 | [diff] [blame] | 760 | #endif |
Philip Reames | 88958b2 | 2015-07-24 00:02:11 +0000 | [diff] [blame] | 761 | |
| 762 | // Once populated, will contain a mapping from each potentially non-base BDV |
| 763 | // to a lattice value (described above) which corresponds to that BDV. |
Philip Reames | 860660e | 2015-02-20 22:05:18 +0000 | [diff] [blame] | 764 | ConflictStateMapTy states; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 765 | // Recursively fill in all phis & selects reachable from the initial one |
| 766 | // for which we don't already know a definite base value for |
Philip Reames | 88958b2 | 2015-07-24 00:02:11 +0000 | [diff] [blame] | 767 | /* scope */ { |
| 768 | DenseSet<Value *> Visited; |
| 769 | SmallVector<Value*, 16> Worklist; |
| 770 | Worklist.push_back(def); |
| 771 | Visited.insert(def); |
| 772 | while (!Worklist.empty()) { |
| 773 | Value *Current = Worklist.pop_back_val(); |
| 774 | assert(!isKnownBaseResult(Current) && "why did it get added?"); |
| 775 | |
| 776 | auto visitIncomingValue = [&](Value *InVal) { |
| 777 | Value *Base = findBaseOrBDV(InVal, cache); |
| 778 | if (isKnownBaseResult(Base)) |
| 779 | // Known bases won't need new instructions introduced and can be |
| 780 | // ignored safely |
| 781 | return; |
| 782 | assert(isExpectedBDVType(Base) && "the only non-base values " |
| 783 | "we see should be base defining values"); |
| 784 | if (Visited.insert(Base).second) |
| 785 | Worklist.push_back(Base); |
| 786 | }; |
| 787 | if (PHINode *Phi = dyn_cast<PHINode>(Current)) { |
| 788 | for (Value *InVal : Phi->incoming_values()) |
| 789 | visitIncomingValue(InVal); |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 790 | } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) { |
Philip Reames | 88958b2 | 2015-07-24 00:02:11 +0000 | [diff] [blame] | 791 | visitIncomingValue(Sel->getTrueValue()); |
| 792 | visitIncomingValue(Sel->getFalseValue()); |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 793 | } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) { |
| 794 | visitIncomingValue(EE->getVectorOperand()); |
| 795 | } else { |
| 796 | // There are two classes of instructions we know we don't handle. |
| 797 | assert(isa<ShuffleVectorInst>(Current) || |
| 798 | isa<InsertElementInst>(Current)); |
| 799 | llvm_unreachable("unimplemented instruction case"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 800 | } |
| 801 | } |
Philip Reames | 88958b2 | 2015-07-24 00:02:11 +0000 | [diff] [blame] | 802 | // The frontier of visited instructions are the ones we might need to |
| 803 | // duplicate, so fill in the starting state for the optimistic algorithm |
| 804 | // that follows. |
| 805 | for (Value *BDV : Visited) { |
| 806 | states[BDV] = BDVState(); |
| 807 | } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 808 | } |
| 809 | |
Philip Reames | dab35f3 | 2015-09-02 21:11:44 +0000 | [diff] [blame] | 810 | #ifndef NDEBUG |
| 811 | DEBUG(dbgs() << "States after initialization:\n"); |
| 812 | for (auto Pair : states) { |
| 813 | DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 814 | } |
Philip Reames | dab35f3 | 2015-09-02 21:11:44 +0000 | [diff] [blame] | 815 | #endif |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 816 | |
Philip Reames | 273e6bb | 2015-07-23 21:41:27 +0000 | [diff] [blame] | 817 | // Return a phi state for a base defining value. We'll generate a new |
| 818 | // base state for known bases and expect to find a cached state otherwise. |
| 819 | auto getStateForBDV = [&](Value *baseValue) { |
| 820 | if (isKnownBaseResult(baseValue)) |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 821 | return BDVState(baseValue); |
Philip Reames | 273e6bb | 2015-07-23 21:41:27 +0000 | [diff] [blame] | 822 | auto I = states.find(baseValue); |
| 823 | assert(I != states.end() && "lookup failed!"); |
| 824 | return I->second; |
| 825 | }; |
| 826 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 827 | bool progress = true; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 828 | while (progress) { |
Yaron Keren | 42a7adf | 2015-02-28 13:11:24 +0000 | [diff] [blame] | 829 | #ifndef NDEBUG |
| 830 | size_t oldSize = states.size(); |
| 831 | #endif |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 832 | progress = false; |
Philip Reames | a226e61 | 2015-02-28 00:47:50 +0000 | [diff] [blame] | 833 | // We're only changing keys in this loop, thus safe to keep iterators |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 834 | for (auto Pair : states) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 835 | Value *v = Pair.first; |
| 836 | assert(!isKnownBaseResult(v) && "why did it get added?"); |
Philip Reames | 273e6bb | 2015-07-23 21:41:27 +0000 | [diff] [blame] | 837 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 838 | // Given an input value for the current instruction, return a BDVState |
Philip Reames | 273e6bb | 2015-07-23 21:41:27 +0000 | [diff] [blame] | 839 | // instance which represents the BDV of that value. |
| 840 | auto getStateForInput = [&](Value *V) mutable { |
| 841 | Value *BDV = findBaseOrBDV(V, cache); |
| 842 | return getStateForBDV(BDV); |
| 843 | }; |
| 844 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 845 | MeetBDVStates calculateMeet; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 846 | if (SelectInst *select = dyn_cast<SelectInst>(v)) { |
Philip Reames | 273e6bb | 2015-07-23 21:41:27 +0000 | [diff] [blame] | 847 | calculateMeet.meetWith(getStateForInput(select->getTrueValue())); |
| 848 | calculateMeet.meetWith(getStateForInput(select->getFalseValue())); |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 849 | } else if (PHINode *Phi = dyn_cast<PHINode>(v)) { |
| 850 | for (Value *Val : Phi->incoming_values()) |
Philip Reames | 273e6bb | 2015-07-23 21:41:27 +0000 | [diff] [blame] | 851 | calculateMeet.meetWith(getStateForInput(Val)); |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 852 | } else { |
| 853 | // The 'meet' for an extractelement is slightly trivial, but it's still |
| 854 | // useful in that it drives us to conflict if our input is. |
| 855 | auto *EE = cast<ExtractElementInst>(v); |
| 856 | calculateMeet.meetWith(getStateForInput(EE->getVectorOperand())); |
| 857 | } |
| 858 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 859 | |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 860 | BDVState oldState = states[v]; |
| 861 | BDVState newState = calculateMeet.getResult(); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 862 | if (oldState != newState) { |
| 863 | progress = true; |
| 864 | states[v] = newState; |
| 865 | } |
| 866 | } |
| 867 | |
| 868 | assert(oldSize <= states.size()); |
| 869 | assert(oldSize == states.size() || progress); |
| 870 | } |
| 871 | |
Philip Reames | dab35f3 | 2015-09-02 21:11:44 +0000 | [diff] [blame] | 872 | #ifndef NDEBUG |
| 873 | DEBUG(dbgs() << "States after meet iteration:\n"); |
| 874 | for (auto Pair : states) { |
| 875 | DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 876 | } |
Philip Reames | dab35f3 | 2015-09-02 21:11:44 +0000 | [diff] [blame] | 877 | #endif |
| 878 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 879 | // Insert Phis for all conflicts |
Philip Reames | 2e5bcbe | 2015-02-28 01:52:09 +0000 | [diff] [blame] | 880 | // We want to keep naming deterministic in the loop that follows, so |
| 881 | // sort the keys before iteration. This is useful in allowing us to |
| 882 | // write stable tests. Note that there is no invalidation issue here. |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 883 | SmallVector<Value *, 16> Keys; |
Philip Reames | 2e5bcbe | 2015-02-28 01:52:09 +0000 | [diff] [blame] | 884 | Keys.reserve(states.size()); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 885 | for (auto Pair : states) { |
Philip Reames | 2e5bcbe | 2015-02-28 01:52:09 +0000 | [diff] [blame] | 886 | Value *V = Pair.first; |
| 887 | Keys.push_back(V); |
| 888 | } |
| 889 | std::sort(Keys.begin(), Keys.end(), order_by_name); |
| 890 | // TODO: adjust naming patterns to avoid this order of iteration dependency |
| 891 | for (Value *V : Keys) { |
Philip Reames | 6ff1a1e3 | 2015-07-21 19:04:38 +0000 | [diff] [blame] | 892 | Instruction *I = cast<Instruction>(V); |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 893 | BDVState State = states[I]; |
Philip Reames | 6ff1a1e3 | 2015-07-21 19:04:38 +0000 | [diff] [blame] | 894 | assert(!isKnownBaseResult(I) && "why did it get added?"); |
| 895 | assert(!State.isUnknown() && "Optimistic algorithm didn't complete!"); |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 896 | |
| 897 | // extractelement instructions are a bit special in that we may need to |
| 898 | // insert an extract even when we know an exact base for the instruction. |
| 899 | // The problem is that we need to convert from a vector base to a scalar |
| 900 | // base for the particular indice we're interested in. |
| 901 | if (State.isBase() && isa<ExtractElementInst>(I) && |
| 902 | isa<VectorType>(State.getBase()->getType())) { |
| 903 | auto *EE = cast<ExtractElementInst>(I); |
| 904 | // TODO: In many cases, the new instruction is just EE itself. We should |
| 905 | // exploit this, but can't do it here since it would break the invariant |
| 906 | // about the BDV not being known to be a base. |
| 907 | auto *BaseInst = ExtractElementInst::Create(State.getBase(), |
| 908 | EE->getIndexOperand(), |
| 909 | "base_ee", EE); |
| 910 | BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {})); |
| 911 | states[I] = BDVState(BDVState::Base, BaseInst); |
| 912 | } |
| 913 | |
Philip Reames | 6ff1a1e3 | 2015-07-21 19:04:38 +0000 | [diff] [blame] | 914 | if (!State.isConflict()) |
Philip Reames | f986d68 | 2015-02-28 00:54:41 +0000 | [diff] [blame] | 915 | continue; |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 916 | |
Philip Reames | 6ff1a1e3 | 2015-07-21 19:04:38 +0000 | [diff] [blame] | 917 | /// Create and insert a new instruction which will represent the base of |
| 918 | /// the given instruction 'I'. |
| 919 | auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* { |
| 920 | if (isa<PHINode>(I)) { |
| 921 | BasicBlock *BB = I->getParent(); |
| 922 | int NumPreds = std::distance(pred_begin(BB), pred_end(BB)); |
| 923 | assert(NumPreds > 0 && "how did we reach here"); |
Philip Reames | fa2c630 | 2015-07-24 19:01:39 +0000 | [diff] [blame] | 924 | std::string Name = I->hasName() ? |
| 925 | (I->getName() + ".base").str() : "base_phi"; |
| 926 | return PHINode::Create(I->getType(), NumPreds, Name, I); |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 927 | } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) { |
| 928 | // The undef will be replaced later |
| 929 | UndefValue *Undef = UndefValue::get(Sel->getType()); |
| 930 | std::string Name = I->hasName() ? |
| 931 | (I->getName() + ".base").str() : "base_select"; |
| 932 | return SelectInst::Create(Sel->getCondition(), Undef, |
| 933 | Undef, Name, Sel); |
| 934 | } else { |
| 935 | auto *EE = cast<ExtractElementInst>(I); |
| 936 | UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType()); |
| 937 | std::string Name = I->hasName() ? |
| 938 | (I->getName() + ".base").str() : "base_ee"; |
| 939 | return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name, |
| 940 | EE); |
Philip Reames | 6ff1a1e3 | 2015-07-21 19:04:38 +0000 | [diff] [blame] | 941 | } |
Philip Reames | 6ff1a1e3 | 2015-07-21 19:04:38 +0000 | [diff] [blame] | 942 | }; |
| 943 | Instruction *BaseInst = MakeBaseInstPlaceholder(I); |
| 944 | // Add metadata marking this as a base value |
| 945 | BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {})); |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 946 | states[I] = BDVState(BDVState::Conflict, BaseInst); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 947 | } |
| 948 | |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 949 | // Returns a instruction which produces the base pointer for a given |
| 950 | // instruction. The instruction is assumed to be an input to one of the BDVs |
| 951 | // seen in the inference algorithm above. As such, we must either already |
| 952 | // know it's base defining value is a base, or have inserted a new |
| 953 | // instruction to propagate the base of it's BDV and have entered that newly |
| 954 | // introduced instruction into the state table. In either case, we are |
| 955 | // assured to be able to determine an instruction which produces it's base |
| 956 | // pointer. |
| 957 | auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) { |
| 958 | Value *BDV = findBaseOrBDV(Input, cache); |
| 959 | Value *Base = nullptr; |
| 960 | if (isKnownBaseResult(BDV)) { |
| 961 | Base = BDV; |
| 962 | } else { |
| 963 | // Either conflict or base. |
| 964 | assert(states.count(BDV)); |
| 965 | Base = states[BDV].getBase(); |
| 966 | } |
| 967 | assert(Base && "can't be null"); |
| 968 | // The cast is needed since base traversal may strip away bitcasts |
| 969 | if (Base->getType() != Input->getType() && |
| 970 | InsertPt) { |
| 971 | Base = new BitCastInst(Base, Input->getType(), "cast", |
| 972 | InsertPt); |
| 973 | } |
| 974 | return Base; |
| 975 | }; |
| 976 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 977 | // Fixup all the inputs of the new PHIs |
| 978 | for (auto Pair : states) { |
| 979 | Instruction *v = cast<Instruction>(Pair.first); |
Philip Reames | 9b141ed | 2015-07-23 22:49:14 +0000 | [diff] [blame] | 980 | BDVState state = Pair.second; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 981 | |
| 982 | assert(!isKnownBaseResult(v) && "why did it get added?"); |
| 983 | assert(!state.isUnknown() && "Optimistic algorithm didn't complete!"); |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 984 | if (!state.isConflict()) |
| 985 | continue; |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 986 | |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 987 | if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) { |
| 988 | PHINode *phi = cast<PHINode>(v); |
| 989 | unsigned NumPHIValues = phi->getNumIncomingValues(); |
| 990 | for (unsigned i = 0; i < NumPHIValues; i++) { |
| 991 | Value *InVal = phi->getIncomingValue(i); |
| 992 | BasicBlock *InBB = phi->getIncomingBlock(i); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 993 | |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 994 | // If we've already seen InBB, add the same incoming value |
| 995 | // we added for it earlier. The IR verifier requires phi |
| 996 | // nodes with multiple entries from the same basic block |
| 997 | // to have the same incoming value for each of those |
| 998 | // entries. If we don't do this check here and basephi |
| 999 | // has a different type than base, we'll end up adding two |
| 1000 | // bitcasts (and hence two distinct values) as incoming |
| 1001 | // values for the same basic block. |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1002 | |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 1003 | int blockIndex = basephi->getBasicBlockIndex(InBB); |
| 1004 | if (blockIndex != -1) { |
| 1005 | Value *oldBase = basephi->getIncomingValue(blockIndex); |
| 1006 | basephi->addIncoming(oldBase, InBB); |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 1007 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1008 | #ifndef NDEBUG |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 1009 | Value *Base = getBaseForInput(InVal, nullptr); |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1010 | // In essence this assert states: the only way two |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 1011 | // values incoming from the same basic block may be |
| 1012 | // different is by being different bitcasts of the same |
| 1013 | // value. A cleanup that remains TODO is changing |
| 1014 | // findBaseOrBDV to return an llvm::Value of the correct |
| 1015 | // type (and still remain pure). This will remove the |
| 1016 | // need to add bitcasts. |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 1017 | assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() && |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 1018 | "sanity -- findBaseOrBDV should be pure!"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1019 | #endif |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 1020 | continue; |
| 1021 | } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1022 | |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 1023 | // Find the instruction which produces the base for each input. We may |
| 1024 | // need to insert a bitcast in the incoming block. |
| 1025 | // TODO: Need to split critical edges if insertion is needed |
| 1026 | Value *Base = getBaseForInput(InVal, InBB->getTerminator()); |
| 1027 | basephi->addIncoming(Base, InBB); |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 1028 | } |
| 1029 | assert(basephi->getNumIncomingValues() == NumPHIValues); |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 1030 | } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(state.getBase())) { |
| 1031 | SelectInst *Sel = cast<SelectInst>(v); |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 1032 | // Operand 1 & 2 are true, false path respectively. TODO: refactor to |
| 1033 | // something more safe and less hacky. |
| 1034 | for (int i = 1; i <= 2; i++) { |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 1035 | Value *InVal = Sel->getOperand(i); |
| 1036 | // Find the instruction which produces the base for each input. We may |
| 1037 | // need to insert a bitcast. |
| 1038 | Value *Base = getBaseForInput(InVal, BaseSel); |
| 1039 | BaseSel->setOperand(i, Base); |
Philip Reames | 28e61ce | 2015-02-28 01:57:44 +0000 | [diff] [blame] | 1040 | } |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 1041 | } else { |
| 1042 | auto *BaseEE = cast<ExtractElementInst>(state.getBase()); |
| 1043 | Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand(); |
Philip Reames | 3ea1589 | 2015-09-03 21:57:40 +0000 | [diff] [blame] | 1044 | // Find the instruction which produces the base for each input. We may |
| 1045 | // need to insert a bitcast. |
| 1046 | Value *Base = getBaseForInput(InVal, BaseEE); |
Philip Reames | 9ac4e38 | 2015-08-12 21:00:20 +0000 | [diff] [blame] | 1047 | BaseEE->setOperand(0, Base); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1048 | } |
| 1049 | } |
| 1050 | |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 1051 | // Now that we're done with the algorithm, see if we can optimize the |
| 1052 | // results slightly by reducing the number of new instructions needed. |
| 1053 | // Arguably, this should be integrated into the algorithm above, but |
| 1054 | // doing as a post process step is easier to reason about for the moment. |
| 1055 | DenseMap<Value *, Value *> ReverseMap; |
| 1056 | SmallPtrSet<Instruction *, 16> NewInsts; |
Philip Reames | 9546f36 | 2015-09-02 22:25:07 +0000 | [diff] [blame] | 1057 | SmallSetVector<AssertingVH<Instruction>, 16> Worklist; |
Philip Reames | 246e618 | 2015-09-03 20:24:29 +0000 | [diff] [blame] | 1058 | // Note: We need to visit the states in a deterministic order. We uses the |
| 1059 | // Keys we sorted above for this purpose. Note that we are papering over a |
| 1060 | // bigger problem with the algorithm above - it's visit order is not |
| 1061 | // deterministic. A larger change is needed to fix this. |
| 1062 | for (auto Key : Keys) { |
| 1063 | Value *V = Key; |
| 1064 | auto State = states[Key]; |
| 1065 | Value *Base = State.getBase(); |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 1066 | assert(V && Base); |
| 1067 | assert(!isKnownBaseResult(V) && "why did it get added?"); |
| 1068 | assert(isKnownBaseResult(Base) && |
| 1069 | "must be something we 'know' is a base pointer"); |
Philip Reames | 246e618 | 2015-09-03 20:24:29 +0000 | [diff] [blame] | 1070 | if (!State.isConflict()) |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 1071 | continue; |
| 1072 | |
| 1073 | ReverseMap[Base] = V; |
| 1074 | if (auto *BaseI = dyn_cast<Instruction>(Base)) { |
| 1075 | NewInsts.insert(BaseI); |
| 1076 | Worklist.insert(BaseI); |
| 1077 | } |
| 1078 | } |
Philip Reames | 9546f36 | 2015-09-02 22:25:07 +0000 | [diff] [blame] | 1079 | auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI, |
| 1080 | Value *Replacement) { |
| 1081 | // Add users which are new instructions (excluding self references) |
| 1082 | for (User *U : BaseI->users()) |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 1083 | if (auto *UI = dyn_cast<Instruction>(U)) |
Philip Reames | 9546f36 | 2015-09-02 22:25:07 +0000 | [diff] [blame] | 1084 | if (NewInsts.count(UI) && UI != BaseI) |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 1085 | Worklist.insert(UI); |
Philip Reames | 9546f36 | 2015-09-02 22:25:07 +0000 | [diff] [blame] | 1086 | // Then do the actual replacement |
| 1087 | NewInsts.erase(BaseI); |
| 1088 | ReverseMap.erase(BaseI); |
| 1089 | BaseI->replaceAllUsesWith(Replacement); |
| 1090 | BaseI->eraseFromParent(); |
| 1091 | assert(states.count(BDV)); |
| 1092 | assert(states[BDV].isConflict() && states[BDV].getBase() == BaseI); |
| 1093 | states[BDV] = BDVState(BDVState::Conflict, Replacement); |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 1094 | }; |
| 1095 | const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout(); |
| 1096 | while (!Worklist.empty()) { |
| 1097 | Instruction *BaseI = Worklist.pop_back_val(); |
Philip Reames | dab35f3 | 2015-09-02 21:11:44 +0000 | [diff] [blame] | 1098 | assert(NewInsts.count(BaseI)); |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 1099 | Value *Bdv = ReverseMap[BaseI]; |
| 1100 | if (auto *BdvI = dyn_cast<Instruction>(Bdv)) |
| 1101 | if (BaseI->isIdenticalTo(BdvI)) { |
| 1102 | DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n"); |
Philip Reames | 9546f36 | 2015-09-02 22:25:07 +0000 | [diff] [blame] | 1103 | ReplaceBaseInstWith(Bdv, BaseI, Bdv); |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 1104 | continue; |
| 1105 | } |
| 1106 | if (Value *V = SimplifyInstruction(BaseI, DL)) { |
| 1107 | DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n"); |
Philip Reames | 9546f36 | 2015-09-02 22:25:07 +0000 | [diff] [blame] | 1108 | ReplaceBaseInstWith(Bdv, BaseI, V); |
Philip Reames | abcdc5e | 2015-08-27 01:02:28 +0000 | [diff] [blame] | 1109 | continue; |
| 1110 | } |
| 1111 | } |
| 1112 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1113 | // Cache all of our results so we can cheaply reuse them |
| 1114 | // NOTE: This is actually two caches: one of the base defining value |
| 1115 | // relation and one of the base pointer relation! FIXME |
| 1116 | for (auto item : states) { |
| 1117 | Value *v = item.first; |
| 1118 | Value *base = item.second.getBase(); |
| 1119 | assert(v && base); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1120 | |
Philip Reames | dab35f3 | 2015-09-02 21:11:44 +0000 | [diff] [blame] | 1121 | std::string fromstr = |
| 1122 | cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "") |
| 1123 | : "none"; |
| 1124 | DEBUG(dbgs() << "Updating base value cache" |
| 1125 | << " for: " << (v->hasName() ? v->getName() : "") |
| 1126 | << " from: " << fromstr |
| 1127 | << " to: " << (base->hasName() ? base->getName() : "") << "\n"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1128 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1129 | if (cache.count(v)) { |
| 1130 | // Once we transition from the BDV relation being store in the cache to |
| 1131 | // the base relation being stored, it must be stable |
| 1132 | assert((!isKnownBaseResult(cache[v]) || cache[v] == base) && |
| 1133 | "base relation should be stable"); |
| 1134 | } |
| 1135 | cache[v] = base; |
| 1136 | } |
| 1137 | assert(cache.find(def) != cache.end()); |
| 1138 | return cache[def]; |
| 1139 | } |
| 1140 | |
| 1141 | // For a set of live pointers (base and/or derived), identify the base |
| 1142 | // pointer of the object which they are derived from. This routine will |
| 1143 | // mutate the IR graph as needed to make the 'base' pointer live at the |
| 1144 | // definition site of 'derived'. This ensures that any use of 'derived' can |
| 1145 | // also use 'base'. This may involve the insertion of a number of |
| 1146 | // additional PHI nodes. |
| 1147 | // |
| 1148 | // preconditions: live is a set of pointer type Values |
| 1149 | // |
| 1150 | // side effects: may insert PHI nodes into the existing CFG, will preserve |
| 1151 | // CFG, will not remove or mutate any existing nodes |
| 1152 | // |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 1153 | // post condition: PointerToBase contains one (derived, base) pair for every |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1154 | // pointer in live. Note that derived can be equal to base if the original |
| 1155 | // pointer was a base pointer. |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1156 | static void |
| 1157 | findBasePointers(const StatepointLiveSetTy &live, |
| 1158 | DenseMap<llvm::Value *, llvm::Value *> &PointerToBase, |
Philip Reames | ba19849 | 2015-04-14 00:41:34 +0000 | [diff] [blame] | 1159 | DominatorTree *DT, DefiningValueMapTy &DVCache) { |
Philip Reames | 2e5bcbe | 2015-02-28 01:52:09 +0000 | [diff] [blame] | 1160 | // For the naming of values inserted to be deterministic - which makes for |
| 1161 | // much cleaner and more stable tests - we need to assign an order to the |
| 1162 | // live values. DenseSets do not provide a deterministic order across runs. |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1163 | SmallVector<Value *, 64> Temp; |
Philip Reames | 2e5bcbe | 2015-02-28 01:52:09 +0000 | [diff] [blame] | 1164 | Temp.insert(Temp.end(), live.begin(), live.end()); |
| 1165 | std::sort(Temp.begin(), Temp.end(), order_by_name); |
| 1166 | for (Value *ptr : Temp) { |
Philip Reames | ba19849 | 2015-04-14 00:41:34 +0000 | [diff] [blame] | 1167 | Value *base = findBasePointer(ptr, DVCache); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1168 | assert(base && "failed to find base pointer"); |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 1169 | PointerToBase[ptr] = base; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1170 | assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) || |
| 1171 | DT->dominates(cast<Instruction>(base)->getParent(), |
| 1172 | cast<Instruction>(ptr)->getParent())) && |
| 1173 | "The base we found better dominate the derived pointer"); |
| 1174 | |
David Blaikie | 82ad787 | 2015-02-20 23:44:24 +0000 | [diff] [blame] | 1175 | // If you see this trip and like to live really dangerously, the code should |
| 1176 | // be correct, just with idioms the verifier can't handle. You can try |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1177 | // disabling the verifier at your own substantial risk. |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1178 | assert(!isa<ConstantPointerNull>(base) && |
Philip Reames | 24c6cd5 | 2015-03-27 05:47:00 +0000 | [diff] [blame] | 1179 | "the relocation code needs adjustment to handle the relocation of " |
| 1180 | "a null pointer constant without causing false positives in the " |
| 1181 | "safepoint ir verifier."); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1182 | } |
| 1183 | } |
| 1184 | |
| 1185 | /// Find the required based pointers (and adjust the live set) for the given |
| 1186 | /// parse point. |
| 1187 | static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache, |
| 1188 | const CallSite &CS, |
| 1189 | PartiallyConstructedSafepointRecord &result) { |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 1190 | DenseMap<llvm::Value *, llvm::Value *> PointerToBase; |
Philip Reames | ba19849 | 2015-04-14 00:41:34 +0000 | [diff] [blame] | 1191 | findBasePointers(result.liveset, PointerToBase, &DT, DVCache); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1192 | |
| 1193 | if (PrintBasePointers) { |
Philip Reames | a5aeaf4 | 2015-02-28 00:20:48 +0000 | [diff] [blame] | 1194 | // Note: Need to print these in a stable order since this is checked in |
| 1195 | // some tests. |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1196 | errs() << "Base Pairs (w/o Relocation):\n"; |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1197 | SmallVector<Value *, 64> Temp; |
Philip Reames | a5aeaf4 | 2015-02-28 00:20:48 +0000 | [diff] [blame] | 1198 | Temp.reserve(PointerToBase.size()); |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 1199 | for (auto Pair : PointerToBase) { |
Philip Reames | a5aeaf4 | 2015-02-28 00:20:48 +0000 | [diff] [blame] | 1200 | Temp.push_back(Pair.first); |
| 1201 | } |
| 1202 | std::sort(Temp.begin(), Temp.end(), order_by_name); |
| 1203 | for (Value *Ptr : Temp) { |
| 1204 | Value *Base = PointerToBase[Ptr]; |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1205 | errs() << " derived %" << Ptr->getName() << " base %" << Base->getName() |
| 1206 | << "\n"; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1207 | } |
| 1208 | } |
| 1209 | |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 1210 | result.PointerToBase = PointerToBase; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1211 | } |
| 1212 | |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 1213 | /// Given an updated version of the dataflow liveness results, update the |
| 1214 | /// liveset and base pointer maps for the call site CS. |
| 1215 | static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData, |
| 1216 | const CallSite &CS, |
| 1217 | PartiallyConstructedSafepointRecord &result); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1218 | |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 1219 | static void recomputeLiveInValues( |
| 1220 | Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate, |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 1221 | MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) { |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 1222 | // TODO-PERF: reuse the original liveness, then simply run the dataflow |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1223 | // again. The old values are still live and will help it stabilize quickly. |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 1224 | GCPtrLivenessData RevisedLivenessData; |
| 1225 | computeLiveInValues(DT, F, RevisedLivenessData); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1226 | for (size_t i = 0; i < records.size(); i++) { |
| 1227 | struct PartiallyConstructedSafepointRecord &info = records[i]; |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 1228 | const CallSite &CS = toUpdate[i]; |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 1229 | recomputeLiveInValues(RevisedLivenessData, CS, info); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1230 | } |
| 1231 | } |
| 1232 | |
Philip Reames | 69e51ca | 2015-04-13 18:07:21 +0000 | [diff] [blame] | 1233 | // When inserting gc.relocate calls, we need to ensure there are no uses |
| 1234 | // of the original value between the gc.statepoint and the gc.relocate call. |
| 1235 | // One case which can arise is a phi node starting one of the successor blocks. |
| 1236 | // We also need to be able to insert the gc.relocates only on the path which |
| 1237 | // goes through the statepoint. We might need to split an edge to make this |
Philip Reames | f209a15 | 2015-04-13 20:00:30 +0000 | [diff] [blame] | 1238 | // possible. |
| 1239 | static BasicBlock * |
Sanjoy Das | ea45f0e | 2015-06-02 22:33:34 +0000 | [diff] [blame] | 1240 | normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent, |
| 1241 | DominatorTree &DT) { |
Philip Reames | 69e51ca | 2015-04-13 18:07:21 +0000 | [diff] [blame] | 1242 | BasicBlock *Ret = BB; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1243 | if (!BB->getUniquePredecessor()) { |
Chandler Carruth | 96ada25 | 2015-07-22 09:52:54 +0000 | [diff] [blame] | 1244 | Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1245 | } |
| 1246 | |
Philip Reames | 69e51ca | 2015-04-13 18:07:21 +0000 | [diff] [blame] | 1247 | // Now that 'ret' has unique predecessor we can safely remove all phi nodes |
| 1248 | // from it |
| 1249 | FoldSingleEntryPHINodes(Ret); |
| 1250 | assert(!isa<PHINode>(Ret->begin())); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1251 | |
Philip Reames | 69e51ca | 2015-04-13 18:07:21 +0000 | [diff] [blame] | 1252 | // At this point, we can safely insert a gc.relocate as the first instruction |
| 1253 | // in Ret if needed. |
| 1254 | return Ret; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1255 | } |
| 1256 | |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 1257 | static int find_index(ArrayRef<Value *> livevec, Value *val) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1258 | auto itr = std::find(livevec.begin(), livevec.end(), val); |
| 1259 | assert(livevec.end() != itr); |
| 1260 | size_t index = std::distance(livevec.begin(), itr); |
| 1261 | assert(index < livevec.size()); |
| 1262 | return index; |
| 1263 | } |
| 1264 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1265 | // Create new attribute set containing only attributes which can be transferred |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1266 | // from original call to the safepoint. |
| 1267 | static AttributeSet legalizeCallAttributes(AttributeSet AS) { |
| 1268 | AttributeSet ret; |
| 1269 | |
| 1270 | for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) { |
| 1271 | unsigned index = AS.getSlotIndex(Slot); |
| 1272 | |
| 1273 | if (index == AttributeSet::ReturnIndex || |
| 1274 | index == AttributeSet::FunctionIndex) { |
| 1275 | |
| 1276 | for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end; |
| 1277 | ++it) { |
| 1278 | Attribute attr = *it; |
| 1279 | |
| 1280 | // Do not allow certain attributes - just skip them |
| 1281 | // Safepoint can not be read only or read none. |
| 1282 | if (attr.hasAttribute(Attribute::ReadNone) || |
| 1283 | attr.hasAttribute(Attribute::ReadOnly)) |
| 1284 | continue; |
| 1285 | |
| 1286 | ret = ret.addAttributes( |
| 1287 | AS.getContext(), index, |
| 1288 | AttributeSet::get(AS.getContext(), index, AttrBuilder(attr))); |
| 1289 | } |
| 1290 | } |
| 1291 | |
| 1292 | // Just skip parameter attributes for now |
| 1293 | } |
| 1294 | |
| 1295 | return ret; |
| 1296 | } |
| 1297 | |
| 1298 | /// Helper function to place all gc relocates necessary for the given |
| 1299 | /// statepoint. |
| 1300 | /// Inputs: |
| 1301 | /// liveVariables - list of variables to be relocated. |
| 1302 | /// liveStart - index of the first live variable. |
| 1303 | /// basePtrs - base pointers. |
| 1304 | /// statepointToken - statepoint instruction to which relocates should be |
| 1305 | /// bound. |
| 1306 | /// Builder - Llvm IR builder to be used to construct new calls. |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1307 | static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables, |
| 1308 | const int LiveStart, |
| 1309 | ArrayRef<llvm::Value *> BasePtrs, |
| 1310 | Instruction *StatepointToken, |
Benjamin Kramer | f044d3f | 2015-03-09 16:23:46 +0000 | [diff] [blame] | 1311 | IRBuilder<> Builder) { |
Philip Reames | 94babb7 | 2015-07-21 17:18:03 +0000 | [diff] [blame] | 1312 | if (LiveVariables.empty()) |
| 1313 | return; |
| 1314 | |
| 1315 | // All gc_relocate are set to i8 addrspace(1)* type. We originally generated |
| 1316 | // unique declarations for each pointer type, but this proved problematic |
| 1317 | // because the intrinsic mangling code is incomplete and fragile. Since |
| 1318 | // we're moving towards a single unified pointer type anyways, we can just |
| 1319 | // cast everything to an i8* of the right address space. A bitcast is added |
| 1320 | // later to convert gc_relocate to the actual value's type. |
Philip Reames | 74ce2e7 | 2015-07-21 16:51:17 +0000 | [diff] [blame] | 1321 | Module *M = StatepointToken->getModule(); |
Philip Reames | 94babb7 | 2015-07-21 17:18:03 +0000 | [diff] [blame] | 1322 | auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace(); |
| 1323 | Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)}; |
| 1324 | Value *GCRelocateDecl = |
| 1325 | Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1326 | |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1327 | for (unsigned i = 0; i < LiveVariables.size(); i++) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1328 | // Generate the gc.relocate call and save the result |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1329 | Value *BaseIdx = |
Philip Reames | f388050 | 2015-07-21 00:49:55 +0000 | [diff] [blame] | 1330 | Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i])); |
| 1331 | Value *LiveIdx = |
| 1332 | Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i])); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1333 | |
| 1334 | // only specify a debug name if we can give a useful one |
Philip Reames | 74ce2e7 | 2015-07-21 16:51:17 +0000 | [diff] [blame] | 1335 | CallInst *Reloc = Builder.CreateCall( |
David Blaikie | ff6409d | 2015-05-18 22:13:54 +0000 | [diff] [blame] | 1336 | GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx}, |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1337 | LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated" |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1338 | : ""); |
| 1339 | // Trick CodeGen into thinking there are lots of free registers at this |
| 1340 | // fake call. |
Philip Reames | 74ce2e7 | 2015-07-21 16:51:17 +0000 | [diff] [blame] | 1341 | Reloc->setCallingConv(CallingConv::Cold); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1342 | } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1343 | } |
| 1344 | |
| 1345 | static void |
| 1346 | makeStatepointExplicitImpl(const CallSite &CS, /* to replace */ |
| 1347 | const SmallVectorImpl<llvm::Value *> &basePtrs, |
| 1348 | const SmallVectorImpl<llvm::Value *> &liveVariables, |
| 1349 | Pass *P, |
| 1350 | PartiallyConstructedSafepointRecord &result) { |
| 1351 | assert(basePtrs.size() == liveVariables.size()); |
| 1352 | assert(isStatepoint(CS) && |
| 1353 | "This method expects to be rewriting a statepoint"); |
| 1354 | |
| 1355 | BasicBlock *BB = CS.getInstruction()->getParent(); |
| 1356 | assert(BB); |
| 1357 | Function *F = BB->getParent(); |
| 1358 | assert(F && "must be set"); |
| 1359 | Module *M = F->getParent(); |
Nick Lewycky | eb3231e | 2015-02-20 07:14:02 +0000 | [diff] [blame] | 1360 | (void)M; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1361 | assert(M && "must be set"); |
| 1362 | |
| 1363 | // We're not changing the function signature of the statepoint since the gc |
| 1364 | // arguments go into the var args section. |
| 1365 | Function *gc_statepoint_decl = CS.getCalledFunction(); |
| 1366 | |
| 1367 | // Then go ahead and use the builder do actually do the inserts. We insert |
| 1368 | // immediately before the previous instruction under the assumption that all |
| 1369 | // arguments will be available here. We can't insert afterwards since we may |
| 1370 | // be replacing a terminator. |
| 1371 | Instruction *insertBefore = CS.getInstruction(); |
| 1372 | IRBuilder<> Builder(insertBefore); |
| 1373 | // Copy all of the arguments from the original statepoint - this includes the |
| 1374 | // target, call args, and deopt args |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 1375 | SmallVector<llvm::Value *, 64> args; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1376 | args.insert(args.end(), CS.arg_begin(), CS.arg_end()); |
| 1377 | // TODO: Clear the 'needs rewrite' flag |
| 1378 | |
| 1379 | // add all the pointers to be relocated (gc arguments) |
| 1380 | // Capture the start of the live variable list for use in the gc_relocates |
| 1381 | const int live_start = args.size(); |
| 1382 | args.insert(args.end(), liveVariables.begin(), liveVariables.end()); |
| 1383 | |
| 1384 | // Create the statepoint given all the arguments |
| 1385 | Instruction *token = nullptr; |
| 1386 | AttributeSet return_attributes; |
| 1387 | if (CS.isCall()) { |
| 1388 | CallInst *toReplace = cast<CallInst>(CS.getInstruction()); |
| 1389 | CallInst *call = |
| 1390 | Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token"); |
| 1391 | call->setTailCall(toReplace->isTailCall()); |
| 1392 | call->setCallingConv(toReplace->getCallingConv()); |
| 1393 | |
| 1394 | // Currently we will fail on parameter attributes and on certain |
| 1395 | // function attributes. |
| 1396 | AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes()); |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1397 | // In case if we can handle this set of attributes - set up function attrs |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1398 | // directly on statepoint and return attrs later for gc_result intrinsic. |
| 1399 | call->setAttributes(new_attrs.getFnAttributes()); |
| 1400 | return_attributes = new_attrs.getRetAttributes(); |
| 1401 | |
| 1402 | token = call; |
| 1403 | |
| 1404 | // Put the following gc_result and gc_relocate calls immediately after the |
| 1405 | // the old call (which we're about to delete) |
| 1406 | BasicBlock::iterator next(toReplace); |
| 1407 | assert(BB->end() != next && "not a terminator, must have next"); |
| 1408 | next++; |
| 1409 | Instruction *IP = &*(next); |
| 1410 | Builder.SetInsertPoint(IP); |
| 1411 | Builder.SetCurrentDebugLocation(IP->getDebugLoc()); |
| 1412 | |
David Blaikie | 82ad787 | 2015-02-20 23:44:24 +0000 | [diff] [blame] | 1413 | } else { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1414 | InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction()); |
| 1415 | |
| 1416 | // Insert the new invoke into the old block. We'll remove the old one in a |
| 1417 | // moment at which point this will become the new terminator for the |
| 1418 | // original block. |
| 1419 | InvokeInst *invoke = InvokeInst::Create( |
| 1420 | gc_statepoint_decl, toReplace->getNormalDest(), |
Philip Reames | fa2c630 | 2015-07-24 19:01:39 +0000 | [diff] [blame] | 1421 | toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent()); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1422 | invoke->setCallingConv(toReplace->getCallingConv()); |
| 1423 | |
| 1424 | // Currently we will fail on parameter attributes and on certain |
| 1425 | // function attributes. |
| 1426 | AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes()); |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1427 | // In case if we can handle this set of attributes - set up function attrs |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1428 | // directly on statepoint and return attrs later for gc_result intrinsic. |
| 1429 | invoke->setAttributes(new_attrs.getFnAttributes()); |
| 1430 | return_attributes = new_attrs.getRetAttributes(); |
| 1431 | |
| 1432 | token = invoke; |
| 1433 | |
| 1434 | // Generate gc relocates in exceptional path |
Philip Reames | 69e51ca | 2015-04-13 18:07:21 +0000 | [diff] [blame] | 1435 | BasicBlock *unwindBlock = toReplace->getUnwindDest(); |
| 1436 | assert(!isa<PHINode>(unwindBlock->begin()) && |
| 1437 | unwindBlock->getUniquePredecessor() && |
| 1438 | "can't safely insert in this block!"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1439 | |
| 1440 | Instruction *IP = &*(unwindBlock->getFirstInsertionPt()); |
| 1441 | Builder.SetInsertPoint(IP); |
| 1442 | Builder.SetCurrentDebugLocation(toReplace->getDebugLoc()); |
| 1443 | |
| 1444 | // Extract second element from landingpad return value. We will attach |
| 1445 | // exceptional gc relocates to it. |
| 1446 | const unsigned idx = 1; |
| 1447 | Instruction *exceptional_token = |
| 1448 | cast<Instruction>(Builder.CreateExtractValue( |
| 1449 | unwindBlock->getLandingPadInst(), idx, "relocate_token")); |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 1450 | result.UnwindToken = exceptional_token; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1451 | |
Philip Reames | 6ff1a1e3 | 2015-07-21 19:04:38 +0000 | [diff] [blame] | 1452 | CreateGCRelocates(liveVariables, live_start, basePtrs, |
| 1453 | exceptional_token, Builder); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1454 | |
| 1455 | // Generate gc relocates and returns for normal block |
Philip Reames | 69e51ca | 2015-04-13 18:07:21 +0000 | [diff] [blame] | 1456 | BasicBlock *normalDest = toReplace->getNormalDest(); |
| 1457 | assert(!isa<PHINode>(normalDest->begin()) && |
| 1458 | normalDest->getUniquePredecessor() && |
| 1459 | "can't safely insert in this block!"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1460 | |
| 1461 | IP = &*(normalDest->getFirstInsertionPt()); |
| 1462 | Builder.SetInsertPoint(IP); |
| 1463 | |
| 1464 | // gc relocates will be generated later as if it were regular call |
| 1465 | // statepoint |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1466 | } |
| 1467 | assert(token); |
| 1468 | |
| 1469 | // Take the name of the original value call if it had one. |
| 1470 | token->takeName(CS.getInstruction()); |
| 1471 | |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1472 | // The GCResult is already inserted, we just need to find it |
David Blaikie | 5e5d784 | 2015-02-22 20:58:38 +0000 | [diff] [blame] | 1473 | #ifndef NDEBUG |
| 1474 | Instruction *toReplace = CS.getInstruction(); |
| 1475 | assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) && |
| 1476 | "only valid use before rewrite is gc.result"); |
| 1477 | assert(!toReplace->hasOneUse() || |
| 1478 | isGCResult(cast<Instruction>(*toReplace->user_begin()))); |
| 1479 | #endif |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1480 | |
| 1481 | // Update the gc.result of the original statepoint (if any) to use the newly |
| 1482 | // inserted statepoint. This is safe to do here since the token can't be |
| 1483 | // considered a live reference. |
| 1484 | CS.getInstruction()->replaceAllUsesWith(token); |
| 1485 | |
Philip Reames | 0a3240f | 2015-02-20 21:34:11 +0000 | [diff] [blame] | 1486 | result.StatepointToken = token; |
| 1487 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1488 | // Second, create a gc.relocate for every live variable |
Philip Reames | 0a3240f | 2015-02-20 21:34:11 +0000 | [diff] [blame] | 1489 | CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1490 | } |
| 1491 | |
| 1492 | namespace { |
| 1493 | struct name_ordering { |
| 1494 | Value *base; |
| 1495 | Value *derived; |
| 1496 | bool operator()(name_ordering const &a, name_ordering const &b) { |
| 1497 | return -1 == a.derived->getName().compare(b.derived->getName()); |
| 1498 | } |
| 1499 | }; |
| 1500 | } |
| 1501 | static void stablize_order(SmallVectorImpl<Value *> &basevec, |
| 1502 | SmallVectorImpl<Value *> &livevec) { |
| 1503 | assert(basevec.size() == livevec.size()); |
| 1504 | |
Philip Reames | 860660e | 2015-02-20 22:05:18 +0000 | [diff] [blame] | 1505 | SmallVector<name_ordering, 64> temp; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1506 | for (size_t i = 0; i < basevec.size(); i++) { |
| 1507 | name_ordering v; |
| 1508 | v.base = basevec[i]; |
| 1509 | v.derived = livevec[i]; |
| 1510 | temp.push_back(v); |
| 1511 | } |
| 1512 | std::sort(temp.begin(), temp.end(), name_ordering()); |
| 1513 | for (size_t i = 0; i < basevec.size(); i++) { |
| 1514 | basevec[i] = temp[i].base; |
| 1515 | livevec[i] = temp[i].derived; |
| 1516 | } |
| 1517 | } |
| 1518 | |
| 1519 | // Replace an existing gc.statepoint with a new one and a set of gc.relocates |
| 1520 | // which make the relocations happening at this safepoint explicit. |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1521 | // |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1522 | // WARNING: Does not do any fixup to adjust users of the original live |
| 1523 | // values. That's the callers responsibility. |
| 1524 | static void |
| 1525 | makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P, |
| 1526 | PartiallyConstructedSafepointRecord &result) { |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 1527 | auto liveset = result.liveset; |
| 1528 | auto PointerToBase = result.PointerToBase; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1529 | |
| 1530 | // Convert to vector for efficient cross referencing. |
| 1531 | SmallVector<Value *, 64> basevec, livevec; |
| 1532 | livevec.reserve(liveset.size()); |
| 1533 | basevec.reserve(liveset.size()); |
| 1534 | for (Value *L : liveset) { |
| 1535 | livevec.push_back(L); |
Philip Reames | 74ce2e7 | 2015-07-21 16:51:17 +0000 | [diff] [blame] | 1536 | assert(PointerToBase.count(L)); |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 1537 | Value *base = PointerToBase[L]; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1538 | basevec.push_back(base); |
| 1539 | } |
| 1540 | assert(livevec.size() == basevec.size()); |
| 1541 | |
| 1542 | // To make the output IR slightly more stable (for use in diffs), ensure a |
| 1543 | // fixed order of the values in the safepoint (by sorting the value name). |
| 1544 | // The order is otherwise meaningless. |
| 1545 | stablize_order(basevec, livevec); |
| 1546 | |
| 1547 | // Do the actual rewriting and delete the old statepoint |
| 1548 | makeStatepointExplicitImpl(CS, basevec, livevec, P, result); |
| 1549 | CS.getInstruction()->eraseFromParent(); |
| 1550 | } |
| 1551 | |
| 1552 | // Helper function for the relocationViaAlloca. |
| 1553 | // It receives iterator to the statepoint gc relocates and emits store to the |
| 1554 | // assigned |
| 1555 | // location (via allocaMap) for the each one of them. |
| 1556 | // Add visited values into the visitedLiveValues set we will later use them |
| 1557 | // for sanity check. |
| 1558 | static void |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1559 | insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs, |
| 1560 | DenseMap<Value *, Value *> &AllocaMap, |
| 1561 | DenseSet<Value *> &VisitedLiveValues) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1562 | |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1563 | for (User *U : GCRelocs) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1564 | if (!isa<IntrinsicInst>(U)) |
| 1565 | continue; |
| 1566 | |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1567 | IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1568 | |
| 1569 | // We only care about relocates |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1570 | if (RelocatedValue->getIntrinsicID() != |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1571 | Intrinsic::experimental_gc_relocate) { |
| 1572 | continue; |
| 1573 | } |
| 1574 | |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1575 | GCRelocateOperands RelocateOperands(RelocatedValue); |
| 1576 | Value *OriginalValue = |
| 1577 | const_cast<Value *>(RelocateOperands.getDerivedPtr()); |
| 1578 | assert(AllocaMap.count(OriginalValue)); |
| 1579 | Value *Alloca = AllocaMap[OriginalValue]; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1580 | |
| 1581 | // Emit store into the related alloca |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1582 | // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to |
| 1583 | // the correct type according to alloca. |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1584 | assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator"); |
| 1585 | IRBuilder<> Builder(RelocatedValue->getNextNode()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1586 | Value *CastedRelocatedValue = |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1587 | Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(), |
| 1588 | RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : ""); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1589 | |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1590 | StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca); |
| 1591 | Store->insertAfter(cast<Instruction>(CastedRelocatedValue)); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1592 | |
| 1593 | #ifndef NDEBUG |
Sanjoy Das | 5665c99 | 2015-05-11 23:47:27 +0000 | [diff] [blame] | 1594 | VisitedLiveValues.insert(OriginalValue); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1595 | #endif |
| 1596 | } |
| 1597 | } |
| 1598 | |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1599 | // Helper function for the "relocationViaAlloca". Similar to the |
| 1600 | // "insertRelocationStores" but works for rematerialized values. |
| 1601 | static void |
| 1602 | insertRematerializationStores( |
| 1603 | RematerializedValueMapTy RematerializedValues, |
| 1604 | DenseMap<Value *, Value *> &AllocaMap, |
| 1605 | DenseSet<Value *> &VisitedLiveValues) { |
| 1606 | |
| 1607 | for (auto RematerializedValuePair: RematerializedValues) { |
| 1608 | Instruction *RematerializedValue = RematerializedValuePair.first; |
| 1609 | Value *OriginalValue = RematerializedValuePair.second; |
| 1610 | |
| 1611 | assert(AllocaMap.count(OriginalValue) && |
| 1612 | "Can not find alloca for rematerialized value"); |
| 1613 | Value *Alloca = AllocaMap[OriginalValue]; |
| 1614 | |
| 1615 | StoreInst *Store = new StoreInst(RematerializedValue, Alloca); |
| 1616 | Store->insertAfter(RematerializedValue); |
| 1617 | |
| 1618 | #ifndef NDEBUG |
| 1619 | VisitedLiveValues.insert(OriginalValue); |
| 1620 | #endif |
| 1621 | } |
| 1622 | } |
| 1623 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1624 | /// do all the relocation update via allocas and mem2reg |
| 1625 | static void relocationViaAlloca( |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1626 | Function &F, DominatorTree &DT, ArrayRef<Value *> Live, |
| 1627 | ArrayRef<struct PartiallyConstructedSafepointRecord> Records) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1628 | #ifndef NDEBUG |
Philip Reames | a6ebf07 | 2015-03-27 05:53:16 +0000 | [diff] [blame] | 1629 | // record initial number of (static) allocas; we'll check we have the same |
| 1630 | // number when we get done. |
| 1631 | int InitialAllocaNum = 0; |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1632 | for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E; |
| 1633 | I++) |
Philip Reames | a6ebf07 | 2015-03-27 05:53:16 +0000 | [diff] [blame] | 1634 | if (isa<AllocaInst>(*I)) |
| 1635 | InitialAllocaNum++; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1636 | #endif |
| 1637 | |
| 1638 | // TODO-PERF: change data structures, reserve |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1639 | DenseMap<Value *, Value *> AllocaMap; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1640 | SmallVector<AllocaInst *, 200> PromotableAllocas; |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1641 | // Used later to chack that we have enough allocas to store all values |
| 1642 | std::size_t NumRematerializedValues = 0; |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1643 | PromotableAllocas.reserve(Live.size()); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1644 | |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1645 | // Emit alloca for "LiveValue" and record it in "allocaMap" and |
| 1646 | // "PromotableAllocas" |
| 1647 | auto emitAllocaFor = [&](Value *LiveValue) { |
| 1648 | AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "", |
| 1649 | F.getEntryBlock().getFirstNonPHI()); |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1650 | AllocaMap[LiveValue] = Alloca; |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1651 | PromotableAllocas.push_back(Alloca); |
| 1652 | }; |
| 1653 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1654 | // emit alloca for each live gc pointer |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1655 | for (unsigned i = 0; i < Live.size(); i++) { |
| 1656 | emitAllocaFor(Live[i]); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1657 | } |
| 1658 | |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1659 | // emit allocas for rematerialized values |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1660 | for (size_t i = 0; i < Records.size(); i++) { |
| 1661 | const struct PartiallyConstructedSafepointRecord &Info = Records[i]; |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1662 | |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1663 | for (auto RematerializedValuePair : Info.RematerializedValues) { |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1664 | Value *OriginalValue = RematerializedValuePair.second; |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1665 | if (AllocaMap.count(OriginalValue) != 0) |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1666 | continue; |
| 1667 | |
| 1668 | emitAllocaFor(OriginalValue); |
| 1669 | ++NumRematerializedValues; |
| 1670 | } |
| 1671 | } |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1672 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1673 | // The next two loops are part of the same conceptual operation. We need to |
| 1674 | // insert a store to the alloca after the original def and at each |
| 1675 | // redefinition. We need to insert a load before each use. These are split |
| 1676 | // into distinct loops for performance reasons. |
| 1677 | |
| 1678 | // update gc pointer after each statepoint |
| 1679 | // either store a relocated value or null (if no relocated value found for |
| 1680 | // this gc pointer and it is not a gc_result) |
| 1681 | // this must happen before we update the statepoint with load of alloca |
| 1682 | // otherwise we lose the link between statepoint and old def |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1683 | for (size_t i = 0; i < Records.size(); i++) { |
| 1684 | const struct PartiallyConstructedSafepointRecord &Info = Records[i]; |
| 1685 | Value *Statepoint = Info.StatepointToken; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1686 | |
| 1687 | // This will be used for consistency check |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1688 | DenseSet<Value *> VisitedLiveValues; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1689 | |
| 1690 | // Insert stores for normal statepoint gc relocates |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1691 | insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1692 | |
| 1693 | // In case if it was invoke statepoint |
| 1694 | // we will insert stores for exceptional path gc relocates. |
Philip Reames | 0a3240f | 2015-02-20 21:34:11 +0000 | [diff] [blame] | 1695 | if (isa<InvokeInst>(Statepoint)) { |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1696 | insertRelocationStores(Info.UnwindToken->users(), AllocaMap, |
| 1697 | VisitedLiveValues); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1698 | } |
| 1699 | |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1700 | // Do similar thing with rematerialized values |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1701 | insertRematerializationStores(Info.RematerializedValues, AllocaMap, |
| 1702 | VisitedLiveValues); |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 1703 | |
Philip Reames | e73300b | 2015-04-13 16:41:32 +0000 | [diff] [blame] | 1704 | if (ClobberNonLive) { |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1705 | // As a debugging aid, pretend that an unrelocated pointer becomes null at |
Philip Reames | e73300b | 2015-04-13 16:41:32 +0000 | [diff] [blame] | 1706 | // the gc.statepoint. This will turn some subtle GC problems into |
| 1707 | // slightly easier to debug SEGVs. Note that on large IR files with |
| 1708 | // lots of gc.statepoints this is extremely costly both memory and time |
| 1709 | // wise. |
| 1710 | SmallVector<AllocaInst *, 64> ToClobber; |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1711 | for (auto Pair : AllocaMap) { |
Philip Reames | e73300b | 2015-04-13 16:41:32 +0000 | [diff] [blame] | 1712 | Value *Def = Pair.first; |
| 1713 | AllocaInst *Alloca = cast<AllocaInst>(Pair.second); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1714 | |
Philip Reames | e73300b | 2015-04-13 16:41:32 +0000 | [diff] [blame] | 1715 | // This value was relocated |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1716 | if (VisitedLiveValues.count(Def)) { |
Philip Reames | e73300b | 2015-04-13 16:41:32 +0000 | [diff] [blame] | 1717 | continue; |
| 1718 | } |
| 1719 | ToClobber.push_back(Alloca); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1720 | } |
Philip Reames | fa2fcf17 | 2015-02-20 19:51:56 +0000 | [diff] [blame] | 1721 | |
Philip Reames | e73300b | 2015-04-13 16:41:32 +0000 | [diff] [blame] | 1722 | auto InsertClobbersAt = [&](Instruction *IP) { |
| 1723 | for (auto *AI : ToClobber) { |
| 1724 | auto AIType = cast<PointerType>(AI->getType()); |
| 1725 | auto PT = cast<PointerType>(AIType->getElementType()); |
| 1726 | Constant *CPN = ConstantPointerNull::get(PT); |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1727 | StoreInst *Store = new StoreInst(CPN, AI); |
| 1728 | Store->insertBefore(IP); |
Philip Reames | e73300b | 2015-04-13 16:41:32 +0000 | [diff] [blame] | 1729 | } |
| 1730 | }; |
| 1731 | |
| 1732 | // Insert the clobbering stores. These may get intermixed with the |
| 1733 | // gc.results and gc.relocates, but that's fine. |
| 1734 | if (auto II = dyn_cast<InvokeInst>(Statepoint)) { |
| 1735 | InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt()); |
| 1736 | InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt()); |
| 1737 | } else { |
| 1738 | BasicBlock::iterator Next(cast<CallInst>(Statepoint)); |
| 1739 | Next++; |
| 1740 | InsertClobbersAt(Next); |
Philip Reames | fa2fcf17 | 2015-02-20 19:51:56 +0000 | [diff] [blame] | 1741 | } |
David Blaikie | 82ad787 | 2015-02-20 23:44:24 +0000 | [diff] [blame] | 1742 | } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1743 | } |
| 1744 | // update use with load allocas and add store for gc_relocated |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1745 | for (auto Pair : AllocaMap) { |
| 1746 | Value *Def = Pair.first; |
| 1747 | Value *Alloca = Pair.second; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1748 | |
| 1749 | // we pre-record the uses of allocas so that we dont have to worry about |
| 1750 | // later update |
| 1751 | // that change the user information. |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1752 | SmallVector<Instruction *, 20> Uses; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1753 | // PERF: trade a linear scan for repeated reallocation |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1754 | Uses.reserve(std::distance(Def->user_begin(), Def->user_end())); |
| 1755 | for (User *U : Def->users()) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1756 | if (!isa<ConstantExpr>(U)) { |
| 1757 | // If the def has a ConstantExpr use, then the def is either a |
| 1758 | // ConstantExpr use itself or null. In either case |
| 1759 | // (recursively in the first, directly in the second), the oop |
| 1760 | // it is ultimately dependent on is null and this particular |
| 1761 | // use does not need to be fixed up. |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1762 | Uses.push_back(cast<Instruction>(U)); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1763 | } |
| 1764 | } |
| 1765 | |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1766 | std::sort(Uses.begin(), Uses.end()); |
| 1767 | auto Last = std::unique(Uses.begin(), Uses.end()); |
| 1768 | Uses.erase(Last, Uses.end()); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1769 | |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1770 | for (Instruction *Use : Uses) { |
| 1771 | if (isa<PHINode>(Use)) { |
| 1772 | PHINode *Phi = cast<PHINode>(Use); |
| 1773 | for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) { |
| 1774 | if (Def == Phi->getIncomingValue(i)) { |
| 1775 | LoadInst *Load = new LoadInst( |
| 1776 | Alloca, "", Phi->getIncomingBlock(i)->getTerminator()); |
| 1777 | Phi->setIncomingValue(i, Load); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1778 | } |
| 1779 | } |
| 1780 | } else { |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1781 | LoadInst *Load = new LoadInst(Alloca, "", Use); |
| 1782 | Use->replaceUsesOfWith(Def, Load); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1783 | } |
| 1784 | } |
| 1785 | |
| 1786 | // emit store for the initial gc value |
| 1787 | // store must be inserted after load, otherwise store will be in alloca's |
| 1788 | // use list and an extra load will be inserted before it |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1789 | StoreInst *Store = new StoreInst(Def, Alloca); |
| 1790 | if (Instruction *Inst = dyn_cast<Instruction>(Def)) { |
| 1791 | if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) { |
Philip Reames | 6da3785 | 2015-03-04 00:13:52 +0000 | [diff] [blame] | 1792 | // InvokeInst is a TerminatorInst so the store need to be inserted |
| 1793 | // into its normal destination block. |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1794 | BasicBlock *NormalDest = Invoke->getNormalDest(); |
| 1795 | Store->insertBefore(NormalDest->getFirstNonPHI()); |
Philip Reames | 6da3785 | 2015-03-04 00:13:52 +0000 | [diff] [blame] | 1796 | } else { |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1797 | assert(!Inst->isTerminator() && |
Philip Reames | 6da3785 | 2015-03-04 00:13:52 +0000 | [diff] [blame] | 1798 | "The only TerminatorInst that can produce a value is " |
| 1799 | "InvokeInst which is handled above."); |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1800 | Store->insertAfter(Inst); |
Philip Reames | 6da3785 | 2015-03-04 00:13:52 +0000 | [diff] [blame] | 1801 | } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1802 | } else { |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1803 | assert(isa<Argument>(Def)); |
| 1804 | Store->insertAfter(cast<Instruction>(Alloca)); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1805 | } |
| 1806 | } |
| 1807 | |
Igor Laevsky | 285fe84 | 2015-05-19 16:29:43 +0000 | [diff] [blame] | 1808 | assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues && |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1809 | "we must have the same allocas with lives"); |
| 1810 | if (!PromotableAllocas.empty()) { |
| 1811 | // apply mem2reg to promote alloca to SSA |
| 1812 | PromoteMemToReg(PromotableAllocas, DT); |
| 1813 | } |
| 1814 | |
| 1815 | #ifndef NDEBUG |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1816 | for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E; |
| 1817 | I++) |
Philip Reames | a6ebf07 | 2015-03-27 05:53:16 +0000 | [diff] [blame] | 1818 | if (isa<AllocaInst>(*I)) |
| 1819 | InitialAllocaNum--; |
| 1820 | assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas"); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1821 | #endif |
| 1822 | } |
| 1823 | |
| 1824 | /// Implement a unique function which doesn't require we sort the input |
| 1825 | /// vector. Doing so has the effect of changing the output of a couple of |
| 1826 | /// tests in ways which make them less useful in testing fused safepoints. |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 1827 | template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) { |
Benjamin Kramer | 258ea0d | 2015-06-13 19:50:38 +0000 | [diff] [blame] | 1828 | SmallSet<T, 8> Seen; |
| 1829 | Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) { |
| 1830 | return !Seen.insert(V).second; |
| 1831 | }), Vec.end()); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1832 | } |
| 1833 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1834 | /// Insert holders so that each Value is obviously live through the entire |
Philip Reames | f209a15 | 2015-04-13 20:00:30 +0000 | [diff] [blame] | 1835 | /// lifetime of the call. |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1836 | static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values, |
Philip Reames | f209a15 | 2015-04-13 20:00:30 +0000 | [diff] [blame] | 1837 | SmallVectorImpl<CallInst *> &Holders) { |
Philip Reames | 2114275 | 2015-04-13 19:07:47 +0000 | [diff] [blame] | 1838 | if (Values.empty()) |
| 1839 | // No values to hold live, might as well not insert the empty holder |
| 1840 | return; |
| 1841 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1842 | Module *M = CS.getInstruction()->getParent()->getParent()->getParent(); |
Philip Reames | f209a15 | 2015-04-13 20:00:30 +0000 | [diff] [blame] | 1843 | // Use a dummy vararg function to actually hold the values live |
| 1844 | Function *Func = cast<Function>(M->getOrInsertFunction( |
| 1845 | "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true))); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1846 | if (CS.isCall()) { |
| 1847 | // For call safepoints insert dummy calls right after safepoint |
Philip Reames | f209a15 | 2015-04-13 20:00:30 +0000 | [diff] [blame] | 1848 | BasicBlock::iterator Next(CS.getInstruction()); |
| 1849 | Next++; |
| 1850 | Holders.push_back(CallInst::Create(Func, Values, "", Next)); |
| 1851 | return; |
| 1852 | } |
| 1853 | // For invoke safepooints insert dummy calls both in normal and |
| 1854 | // exceptional destination blocks |
| 1855 | auto *II = cast<InvokeInst>(CS.getInstruction()); |
| 1856 | Holders.push_back(CallInst::Create( |
| 1857 | Func, Values, "", II->getNormalDest()->getFirstInsertionPt())); |
| 1858 | Holders.push_back(CallInst::Create( |
| 1859 | Func, Values, "", II->getUnwindDest()->getFirstInsertionPt())); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1860 | } |
| 1861 | |
| 1862 | static void findLiveReferences( |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 1863 | Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate, |
| 1864 | MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) { |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 1865 | GCPtrLivenessData OriginalLivenessData; |
| 1866 | computeLiveInValues(DT, F, OriginalLivenessData); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1867 | for (size_t i = 0; i < records.size(); i++) { |
| 1868 | struct PartiallyConstructedSafepointRecord &info = records[i]; |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 1869 | const CallSite &CS = toUpdate[i]; |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 1870 | analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 1871 | } |
| 1872 | } |
| 1873 | |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1874 | /// Remove any vector of pointers from the liveset by scalarizing them over the |
| 1875 | /// statepoint instruction. Adds the scalarized pieces to the liveset. It |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1876 | /// would be preferable to include the vector in the statepoint itself, but |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1877 | /// the lowering code currently does not handle that. Extending it would be |
| 1878 | /// slightly non-trivial since it requires a format change. Given how rare |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1879 | /// such cases are (for the moment?) scalarizing is an acceptable compromise. |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1880 | static void splitVectorValues(Instruction *StatepointInst, |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 1881 | StatepointLiveSetTy &LiveSet, |
| 1882 | DenseMap<Value *, Value *>& PointerToBase, |
| 1883 | DominatorTree &DT) { |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1884 | SmallVector<Value *, 16> ToSplit; |
| 1885 | for (Value *V : LiveSet) |
| 1886 | if (isa<VectorType>(V->getType())) |
| 1887 | ToSplit.push_back(V); |
| 1888 | |
| 1889 | if (ToSplit.empty()) |
| 1890 | return; |
| 1891 | |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 1892 | DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping; |
| 1893 | |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1894 | Function &F = *(StatepointInst->getParent()->getParent()); |
| 1895 | |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1896 | DenseMap<Value *, AllocaInst *> AllocaMap; |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1897 | // First is normal return, second is exceptional return (invoke only) |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1898 | DenseMap<Value *, std::pair<Value *, Value *>> Replacements; |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1899 | for (Value *V : ToSplit) { |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1900 | AllocaInst *Alloca = |
| 1901 | new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI()); |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1902 | AllocaMap[V] = Alloca; |
| 1903 | |
| 1904 | VectorType *VT = cast<VectorType>(V->getType()); |
| 1905 | IRBuilder<> Builder(StatepointInst); |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1906 | SmallVector<Value *, 16> Elements; |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1907 | for (unsigned i = 0; i < VT->getNumElements(); i++) |
| 1908 | Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i))); |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 1909 | ElementMapping[V] = Elements; |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1910 | |
| 1911 | auto InsertVectorReform = [&](Instruction *IP) { |
| 1912 | Builder.SetInsertPoint(IP); |
| 1913 | Builder.SetCurrentDebugLocation(IP->getDebugLoc()); |
| 1914 | Value *ResultVec = UndefValue::get(VT); |
| 1915 | for (unsigned i = 0; i < VT->getNumElements(); i++) |
| 1916 | ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i], |
| 1917 | Builder.getInt32(i)); |
| 1918 | return ResultVec; |
| 1919 | }; |
| 1920 | |
| 1921 | if (isa<CallInst>(StatepointInst)) { |
| 1922 | BasicBlock::iterator Next(StatepointInst); |
| 1923 | Next++; |
| 1924 | Instruction *IP = &*(Next); |
| 1925 | Replacements[V].first = InsertVectorReform(IP); |
| 1926 | Replacements[V].second = nullptr; |
| 1927 | } else { |
| 1928 | InvokeInst *Invoke = cast<InvokeInst>(StatepointInst); |
| 1929 | // We've already normalized - check that we don't have shared destination |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1930 | // blocks |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1931 | BasicBlock *NormalDest = Invoke->getNormalDest(); |
| 1932 | assert(!isa<PHINode>(NormalDest->begin())); |
| 1933 | BasicBlock *UnwindDest = Invoke->getUnwindDest(); |
| 1934 | assert(!isa<PHINode>(UnwindDest->begin())); |
| 1935 | // Insert insert element sequences in both successors |
| 1936 | Instruction *IP = &*(NormalDest->getFirstInsertionPt()); |
| 1937 | Replacements[V].first = InsertVectorReform(IP); |
| 1938 | IP = &*(UnwindDest->getFirstInsertionPt()); |
| 1939 | Replacements[V].second = InsertVectorReform(IP); |
| 1940 | } |
| 1941 | } |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 1942 | |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1943 | for (Value *V : ToSplit) { |
| 1944 | AllocaInst *Alloca = AllocaMap[V]; |
| 1945 | |
| 1946 | // Capture all users before we start mutating use lists |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1947 | SmallVector<Instruction *, 16> Users; |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1948 | for (User *U : V->users()) |
| 1949 | Users.push_back(cast<Instruction>(U)); |
| 1950 | |
| 1951 | for (Instruction *I : Users) { |
| 1952 | if (auto Phi = dyn_cast<PHINode>(I)) { |
| 1953 | for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) |
| 1954 | if (V == Phi->getIncomingValue(i)) { |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1955 | LoadInst *Load = new LoadInst( |
| 1956 | Alloca, "", Phi->getIncomingBlock(i)->getTerminator()); |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1957 | Phi->setIncomingValue(i, Load); |
| 1958 | } |
| 1959 | } else { |
| 1960 | LoadInst *Load = new LoadInst(Alloca, "", I); |
| 1961 | I->replaceUsesOfWith(V, Load); |
| 1962 | } |
| 1963 | } |
| 1964 | |
| 1965 | // Store the original value and the replacement value into the alloca |
| 1966 | StoreInst *Store = new StoreInst(V, Alloca); |
| 1967 | if (auto I = dyn_cast<Instruction>(V)) |
| 1968 | Store->insertAfter(I); |
| 1969 | else |
| 1970 | Store->insertAfter(Alloca); |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1971 | |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1972 | // Normal return for invoke, or call return |
| 1973 | Instruction *Replacement = cast<Instruction>(Replacements[V].first); |
| 1974 | (new StoreInst(Replacement, Alloca))->insertAfter(Replacement); |
| 1975 | // Unwind return for invoke only |
| 1976 | Replacement = cast_or_null<Instruction>(Replacements[V].second); |
| 1977 | if (Replacement) |
| 1978 | (new StoreInst(Replacement, Alloca))->insertAfter(Replacement); |
| 1979 | } |
| 1980 | |
| 1981 | // apply mem2reg to promote alloca to SSA |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 1982 | SmallVector<AllocaInst *, 16> Allocas; |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 1983 | for (Value *V : ToSplit) |
| 1984 | Allocas.push_back(AllocaMap[V]); |
| 1985 | PromoteMemToReg(Allocas, DT); |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 1986 | |
| 1987 | // Update our tracking of live pointers and base mappings to account for the |
| 1988 | // changes we just made. |
| 1989 | for (Value *V : ToSplit) { |
| 1990 | auto &Elements = ElementMapping[V]; |
| 1991 | |
| 1992 | LiveSet.erase(V); |
| 1993 | LiveSet.insert(Elements.begin(), Elements.end()); |
| 1994 | // We need to update the base mapping as well. |
| 1995 | assert(PointerToBase.count(V)); |
| 1996 | Value *OldBase = PointerToBase[V]; |
| 1997 | auto &BaseElements = ElementMapping[OldBase]; |
| 1998 | PointerToBase.erase(V); |
| 1999 | assert(Elements.size() == BaseElements.size()); |
| 2000 | for (unsigned i = 0; i < Elements.size(); i++) { |
| 2001 | Value *Elem = Elements[i]; |
| 2002 | PointerToBase[Elem] = BaseElements[i]; |
| 2003 | } |
| 2004 | } |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 2005 | } |
| 2006 | |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 2007 | // Helper function for the "rematerializeLiveValues". It walks use chain |
| 2008 | // starting from the "CurrentValue" until it meets "BaseValue". Only "simple" |
| 2009 | // values are visited (currently it is GEP's and casts). Returns true if it |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 2010 | // successfully reached "BaseValue" and false otherwise. |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 2011 | // Fills "ChainToBase" array with all visited values. "BaseValue" is not |
| 2012 | // recorded. |
| 2013 | static bool findRematerializableChainToBasePointer( |
| 2014 | SmallVectorImpl<Instruction*> &ChainToBase, |
| 2015 | Value *CurrentValue, Value *BaseValue) { |
| 2016 | |
| 2017 | // We have found a base value |
| 2018 | if (CurrentValue == BaseValue) { |
| 2019 | return true; |
| 2020 | } |
| 2021 | |
| 2022 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) { |
| 2023 | ChainToBase.push_back(GEP); |
| 2024 | return findRematerializableChainToBasePointer(ChainToBase, |
| 2025 | GEP->getPointerOperand(), |
| 2026 | BaseValue); |
| 2027 | } |
| 2028 | |
| 2029 | if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) { |
| 2030 | Value *Def = CI->stripPointerCasts(); |
| 2031 | |
| 2032 | // This two checks are basically similar. First one is here for the |
| 2033 | // consistency with findBasePointers logic. |
| 2034 | assert(!isa<CastInst>(Def) && "not a pointer cast found"); |
| 2035 | if (!CI->isNoopCast(CI->getModule()->getDataLayout())) |
| 2036 | return false; |
| 2037 | |
| 2038 | ChainToBase.push_back(CI); |
| 2039 | return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue); |
| 2040 | } |
| 2041 | |
| 2042 | // Not supported instruction in the chain |
| 2043 | return false; |
| 2044 | } |
| 2045 | |
| 2046 | // Helper function for the "rematerializeLiveValues". Compute cost of the use |
| 2047 | // chain we are going to rematerialize. |
| 2048 | static unsigned |
| 2049 | chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain, |
| 2050 | TargetTransformInfo &TTI) { |
| 2051 | unsigned Cost = 0; |
| 2052 | |
| 2053 | for (Instruction *Instr : Chain) { |
| 2054 | if (CastInst *CI = dyn_cast<CastInst>(Instr)) { |
| 2055 | assert(CI->isNoopCast(CI->getModule()->getDataLayout()) && |
| 2056 | "non noop cast is found during rematerialization"); |
| 2057 | |
| 2058 | Type *SrcTy = CI->getOperand(0)->getType(); |
| 2059 | Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy); |
| 2060 | |
| 2061 | } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) { |
| 2062 | // Cost of the address calculation |
| 2063 | Type *ValTy = GEP->getPointerOperandType()->getPointerElementType(); |
| 2064 | Cost += TTI.getAddressComputationCost(ValTy); |
| 2065 | |
| 2066 | // And cost of the GEP itself |
| 2067 | // TODO: Use TTI->getGEPCost here (it exists, but appears to be not |
| 2068 | // allowed for the external usage) |
| 2069 | if (!GEP->hasAllConstantIndices()) |
| 2070 | Cost += 2; |
| 2071 | |
| 2072 | } else { |
| 2073 | llvm_unreachable("unsupported instruciton type during rematerialization"); |
| 2074 | } |
| 2075 | } |
| 2076 | |
| 2077 | return Cost; |
| 2078 | } |
| 2079 | |
| 2080 | // From the statepoint liveset pick values that are cheaper to recompute then to |
| 2081 | // relocate. Remove this values from the liveset, rematerialize them after |
| 2082 | // statepoint and record them in "Info" structure. Note that similar to |
| 2083 | // relocated values we don't do any user adjustments here. |
| 2084 | static void rematerializeLiveValues(CallSite CS, |
| 2085 | PartiallyConstructedSafepointRecord &Info, |
| 2086 | TargetTransformInfo &TTI) { |
Aaron Ballman | ff7d4fa | 2015-05-20 14:53:50 +0000 | [diff] [blame] | 2087 | const unsigned int ChainLengthThreshold = 10; |
NAKAMURA Takumi | fb3bd71 | 2015-05-25 01:43:23 +0000 | [diff] [blame] | 2088 | |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 2089 | // Record values we are going to delete from this statepoint live set. |
| 2090 | // We can not di this in following loop due to iterator invalidation. |
| 2091 | SmallVector<Value *, 32> LiveValuesToBeDeleted; |
| 2092 | |
| 2093 | for (Value *LiveValue: Info.liveset) { |
| 2094 | // For each live pointer find it's defining chain |
| 2095 | SmallVector<Instruction *, 3> ChainToBase; |
Philip Reames | 74ce2e7 | 2015-07-21 16:51:17 +0000 | [diff] [blame] | 2096 | assert(Info.PointerToBase.count(LiveValue)); |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 2097 | bool FoundChain = |
| 2098 | findRematerializableChainToBasePointer(ChainToBase, |
| 2099 | LiveValue, |
| 2100 | Info.PointerToBase[LiveValue]); |
| 2101 | // Nothing to do, or chain is too long |
| 2102 | if (!FoundChain || |
| 2103 | ChainToBase.size() == 0 || |
| 2104 | ChainToBase.size() > ChainLengthThreshold) |
| 2105 | continue; |
| 2106 | |
| 2107 | // Compute cost of this chain |
| 2108 | unsigned Cost = chainToBasePointerCost(ChainToBase, TTI); |
| 2109 | // TODO: We can also account for cases when we will be able to remove some |
| 2110 | // of the rematerialized values by later optimization passes. I.e if |
| 2111 | // we rematerialized several intersecting chains. Or if original values |
| 2112 | // don't have any uses besides this statepoint. |
| 2113 | |
| 2114 | // For invokes we need to rematerialize each chain twice - for normal and |
| 2115 | // for unwind basic blocks. Model this by multiplying cost by two. |
| 2116 | if (CS.isInvoke()) { |
| 2117 | Cost *= 2; |
| 2118 | } |
| 2119 | // If it's too expensive - skip it |
| 2120 | if (Cost >= RematerializationThreshold) |
| 2121 | continue; |
| 2122 | |
| 2123 | // Remove value from the live set |
| 2124 | LiveValuesToBeDeleted.push_back(LiveValue); |
| 2125 | |
| 2126 | // Clone instructions and record them inside "Info" structure |
| 2127 | |
| 2128 | // Walk backwards to visit top-most instructions first |
| 2129 | std::reverse(ChainToBase.begin(), ChainToBase.end()); |
| 2130 | |
| 2131 | // Utility function which clones all instructions from "ChainToBase" |
| 2132 | // and inserts them before "InsertBefore". Returns rematerialized value |
| 2133 | // which should be used after statepoint. |
| 2134 | auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) { |
| 2135 | Instruction *LastClonedValue = nullptr; |
| 2136 | Instruction *LastValue = nullptr; |
| 2137 | for (Instruction *Instr: ChainToBase) { |
| 2138 | // Only GEP's and casts are suported as we need to be careful to not |
| 2139 | // introduce any new uses of pointers not in the liveset. |
| 2140 | // Note that it's fine to introduce new uses of pointers which were |
| 2141 | // otherwise not used after this statepoint. |
| 2142 | assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr)); |
| 2143 | |
| 2144 | Instruction *ClonedValue = Instr->clone(); |
| 2145 | ClonedValue->insertBefore(InsertBefore); |
| 2146 | ClonedValue->setName(Instr->getName() + ".remat"); |
| 2147 | |
| 2148 | // If it is not first instruction in the chain then it uses previously |
| 2149 | // cloned value. We should update it to use cloned value. |
| 2150 | if (LastClonedValue) { |
| 2151 | assert(LastValue); |
| 2152 | ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue); |
| 2153 | #ifndef NDEBUG |
Igor Laevsky | d83f697 | 2015-05-21 13:02:14 +0000 | [diff] [blame] | 2154 | // Assert that cloned instruction does not use any instructions from |
| 2155 | // this chain other than LastClonedValue |
| 2156 | for (auto OpValue : ClonedValue->operand_values()) { |
| 2157 | assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) == |
| 2158 | ChainToBase.end() && |
| 2159 | "incorrect use in rematerialization chain"); |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 2160 | } |
| 2161 | #endif |
| 2162 | } |
| 2163 | |
| 2164 | LastClonedValue = ClonedValue; |
| 2165 | LastValue = Instr; |
| 2166 | } |
| 2167 | assert(LastClonedValue); |
| 2168 | return LastClonedValue; |
| 2169 | }; |
| 2170 | |
| 2171 | // Different cases for calls and invokes. For invokes we need to clone |
| 2172 | // instructions both on normal and unwind path. |
| 2173 | if (CS.isCall()) { |
| 2174 | Instruction *InsertBefore = CS.getInstruction()->getNextNode(); |
| 2175 | assert(InsertBefore); |
| 2176 | Instruction *RematerializedValue = rematerializeChain(InsertBefore); |
| 2177 | Info.RematerializedValues[RematerializedValue] = LiveValue; |
| 2178 | } else { |
| 2179 | InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction()); |
| 2180 | |
| 2181 | Instruction *NormalInsertBefore = |
| 2182 | Invoke->getNormalDest()->getFirstInsertionPt(); |
| 2183 | Instruction *UnwindInsertBefore = |
| 2184 | Invoke->getUnwindDest()->getFirstInsertionPt(); |
| 2185 | |
| 2186 | Instruction *NormalRematerializedValue = |
| 2187 | rematerializeChain(NormalInsertBefore); |
| 2188 | Instruction *UnwindRematerializedValue = |
| 2189 | rematerializeChain(UnwindInsertBefore); |
| 2190 | |
| 2191 | Info.RematerializedValues[NormalRematerializedValue] = LiveValue; |
| 2192 | Info.RematerializedValues[UnwindRematerializedValue] = LiveValue; |
| 2193 | } |
| 2194 | } |
| 2195 | |
| 2196 | // Remove rematerializaed values from the live set |
| 2197 | for (auto LiveValue: LiveValuesToBeDeleted) { |
| 2198 | Info.liveset.erase(LiveValue); |
| 2199 | } |
| 2200 | } |
| 2201 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2202 | static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P, |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 2203 | SmallVectorImpl<CallSite> &toUpdate) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2204 | #ifndef NDEBUG |
| 2205 | // sanity check the input |
| 2206 | std::set<CallSite> uniqued; |
| 2207 | uniqued.insert(toUpdate.begin(), toUpdate.end()); |
| 2208 | assert(uniqued.size() == toUpdate.size() && "no duplicates please!"); |
| 2209 | |
| 2210 | for (size_t i = 0; i < toUpdate.size(); i++) { |
| 2211 | CallSite &CS = toUpdate[i]; |
| 2212 | assert(CS.getInstruction()->getParent()->getParent() == &F); |
| 2213 | assert(isStatepoint(CS) && "expected to already be a deopt statepoint"); |
| 2214 | } |
| 2215 | #endif |
| 2216 | |
Philip Reames | 69e51ca | 2015-04-13 18:07:21 +0000 | [diff] [blame] | 2217 | // When inserting gc.relocates for invokes, we need to be able to insert at |
| 2218 | // the top of the successor blocks. See the comment on |
| 2219 | // normalForInvokeSafepoint on exactly what is needed. Note that this step |
Philip Reames | f209a15 | 2015-04-13 20:00:30 +0000 | [diff] [blame] | 2220 | // may restructure the CFG. |
| 2221 | for (CallSite CS : toUpdate) { |
| 2222 | if (!CS.isInvoke()) |
| 2223 | continue; |
| 2224 | InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction()); |
| 2225 | normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(), |
Sanjoy Das | ea45f0e | 2015-06-02 22:33:34 +0000 | [diff] [blame] | 2226 | DT); |
Philip Reames | f209a15 | 2015-04-13 20:00:30 +0000 | [diff] [blame] | 2227 | normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(), |
Sanjoy Das | ea45f0e | 2015-06-02 22:33:34 +0000 | [diff] [blame] | 2228 | DT); |
Philip Reames | f209a15 | 2015-04-13 20:00:30 +0000 | [diff] [blame] | 2229 | } |
Philip Reames | 69e51ca | 2015-04-13 18:07:21 +0000 | [diff] [blame] | 2230 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2231 | // A list of dummy calls added to the IR to keep various values obviously |
| 2232 | // live in the IR. We'll remove all of these when done. |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 2233 | SmallVector<CallInst *, 64> holders; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2234 | |
| 2235 | // Insert a dummy call with all of the arguments to the vm_state we'll need |
| 2236 | // for the actual safepoint insertion. This ensures reference arguments in |
| 2237 | // the deopt argument list are considered live through the safepoint (and |
| 2238 | // thus makes sure they get relocated.) |
| 2239 | for (size_t i = 0; i < toUpdate.size(); i++) { |
| 2240 | CallSite &CS = toUpdate[i]; |
| 2241 | Statepoint StatepointCS(CS); |
| 2242 | |
| 2243 | SmallVector<Value *, 64> DeoptValues; |
| 2244 | for (Use &U : StatepointCS.vm_state_args()) { |
| 2245 | Value *Arg = cast<Value>(&U); |
Philip Reames | 8531d8c | 2015-04-10 21:48:25 +0000 | [diff] [blame] | 2246 | assert(!isUnhandledGCPointerType(Arg->getType()) && |
| 2247 | "support for FCA unimplemented"); |
| 2248 | if (isHandledGCPointerType(Arg->getType())) |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2249 | DeoptValues.push_back(Arg); |
| 2250 | } |
| 2251 | insertUseHolderAfter(CS, DeoptValues, holders); |
| 2252 | } |
| 2253 | |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 2254 | SmallVector<struct PartiallyConstructedSafepointRecord, 64> records; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2255 | records.reserve(toUpdate.size()); |
| 2256 | for (size_t i = 0; i < toUpdate.size(); i++) { |
| 2257 | struct PartiallyConstructedSafepointRecord info; |
| 2258 | records.push_back(info); |
| 2259 | } |
| 2260 | assert(records.size() == toUpdate.size()); |
| 2261 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 2262 | // A) Identify all gc pointers which are statically live at the given call |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2263 | // site. |
| 2264 | findLiveReferences(F, DT, P, toUpdate, records); |
| 2265 | |
| 2266 | // B) Find the base pointers for each live pointer |
| 2267 | /* scope for caching */ { |
| 2268 | // Cache the 'defining value' relation used in the computation and |
| 2269 | // insertion of base phis and selects. This ensures that we don't insert |
| 2270 | // large numbers of duplicate base_phis. |
| 2271 | DefiningValueMapTy DVCache; |
| 2272 | |
| 2273 | for (size_t i = 0; i < records.size(); i++) { |
| 2274 | struct PartiallyConstructedSafepointRecord &info = records[i]; |
| 2275 | CallSite &CS = toUpdate[i]; |
| 2276 | findBasePointers(DT, DVCache, CS, info); |
| 2277 | } |
| 2278 | } // end of cache scope |
| 2279 | |
| 2280 | // The base phi insertion logic (for any safepoint) may have inserted new |
| 2281 | // instructions which are now live at some safepoint. The simplest such |
| 2282 | // example is: |
| 2283 | // loop: |
| 2284 | // phi a <-- will be a new base_phi here |
| 2285 | // safepoint 1 <-- that needs to be live here |
| 2286 | // gep a + 1 |
| 2287 | // safepoint 2 |
| 2288 | // br loop |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2289 | // We insert some dummy calls after each safepoint to definitely hold live |
| 2290 | // the base pointers which were identified for that safepoint. We'll then |
| 2291 | // ask liveness for _every_ base inserted to see what is now live. Then we |
| 2292 | // remove the dummy calls. |
| 2293 | holders.reserve(holders.size() + records.size()); |
| 2294 | for (size_t i = 0; i < records.size(); i++) { |
| 2295 | struct PartiallyConstructedSafepointRecord &info = records[i]; |
| 2296 | CallSite &CS = toUpdate[i]; |
| 2297 | |
| 2298 | SmallVector<Value *, 128> Bases; |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 2299 | for (auto Pair : info.PointerToBase) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2300 | Bases.push_back(Pair.second); |
| 2301 | } |
| 2302 | insertUseHolderAfter(CS, Bases, holders); |
| 2303 | } |
| 2304 | |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2305 | // By selecting base pointers, we've effectively inserted new uses. Thus, we |
| 2306 | // need to rerun liveness. We may *also* have inserted new defs, but that's |
| 2307 | // not the key issue. |
| 2308 | recomputeLiveInValues(F, DT, P, toUpdate, records); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2309 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2310 | if (PrintBasePointers) { |
| 2311 | for (size_t i = 0; i < records.size(); i++) { |
| 2312 | struct PartiallyConstructedSafepointRecord &info = records[i]; |
| 2313 | errs() << "Base Pairs: (w/Relocation)\n"; |
Philip Reames | f204132 | 2015-02-20 19:26:04 +0000 | [diff] [blame] | 2314 | for (auto Pair : info.PointerToBase) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2315 | errs() << " derived %" << Pair.first->getName() << " base %" |
| 2316 | << Pair.second->getName() << "\n"; |
| 2317 | } |
| 2318 | } |
| 2319 | } |
| 2320 | for (size_t i = 0; i < holders.size(); i++) { |
| 2321 | holders[i]->eraseFromParent(); |
| 2322 | holders[i] = nullptr; |
| 2323 | } |
| 2324 | holders.clear(); |
| 2325 | |
Philip Reames | 8fe7f13 | 2015-06-26 22:47:37 +0000 | [diff] [blame] | 2326 | // Do a limited scalarization of any live at safepoint vector values which |
| 2327 | // contain pointers. This enables this pass to run after vectorization at |
| 2328 | // the cost of some possible performance loss. TODO: it would be nice to |
| 2329 | // natively support vectors all the way through the backend so we don't need |
| 2330 | // to scalarize here. |
| 2331 | for (size_t i = 0; i < records.size(); i++) { |
| 2332 | struct PartiallyConstructedSafepointRecord &info = records[i]; |
| 2333 | Instruction *statepoint = toUpdate[i].getInstruction(); |
| 2334 | splitVectorValues(cast<Instruction>(statepoint), info.liveset, |
| 2335 | info.PointerToBase, DT); |
| 2336 | } |
| 2337 | |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 2338 | // In order to reduce live set of statepoint we might choose to rematerialize |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 2339 | // some values instead of relocating them. This is purely an optimization and |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 2340 | // does not influence correctness. |
| 2341 | TargetTransformInfo &TTI = |
| 2342 | P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
| 2343 | |
NAKAMURA Takumi | fb3bd71 | 2015-05-25 01:43:23 +0000 | [diff] [blame] | 2344 | for (size_t i = 0; i < records.size(); i++) { |
Igor Laevsky | e031718 | 2015-05-19 15:59:05 +0000 | [diff] [blame] | 2345 | struct PartiallyConstructedSafepointRecord &info = records[i]; |
| 2346 | CallSite &CS = toUpdate[i]; |
| 2347 | |
| 2348 | rematerializeLiveValues(CS, info, TTI); |
| 2349 | } |
| 2350 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2351 | // Now run through and replace the existing statepoints with new ones with |
| 2352 | // the live variables listed. We do not yet update uses of the values being |
| 2353 | // relocated. We have references to live variables that need to |
| 2354 | // survive to the last iteration of this loop. (By construction, the |
| 2355 | // previous statepoint can not be a live variable, thus we can and remove |
| 2356 | // the old statepoint calls as we go.) |
| 2357 | for (size_t i = 0; i < records.size(); i++) { |
| 2358 | struct PartiallyConstructedSafepointRecord &info = records[i]; |
| 2359 | CallSite &CS = toUpdate[i]; |
| 2360 | makeStatepointExplicit(DT, CS, P, info); |
| 2361 | } |
| 2362 | toUpdate.clear(); // prevent accident use of invalid CallSites |
| 2363 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2364 | // Do all the fixups of the original live variables to their relocated selves |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 2365 | SmallVector<Value *, 128> live; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2366 | for (size_t i = 0; i < records.size(); i++) { |
| 2367 | struct PartiallyConstructedSafepointRecord &info = records[i]; |
| 2368 | // We can't simply save the live set from the original insertion. One of |
| 2369 | // the live values might be the result of a call which needs a safepoint. |
| 2370 | // That Value* no longer exists and we need to use the new gc_result. |
| 2371 | // Thankfully, the liveset is embedded in the statepoint (and updated), so |
| 2372 | // we just grab that. |
Philip Reames | 0a3240f | 2015-02-20 21:34:11 +0000 | [diff] [blame] | 2373 | Statepoint statepoint(info.StatepointToken); |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2374 | live.insert(live.end(), statepoint.gc_args_begin(), |
| 2375 | statepoint.gc_args_end()); |
Philip Reames | 9a2e01d | 2015-04-13 17:35:55 +0000 | [diff] [blame] | 2376 | #ifndef NDEBUG |
| 2377 | // Do some basic sanity checks on our liveness results before performing |
| 2378 | // relocation. Relocation can and will turn mistakes in liveness results |
| 2379 | // into non-sensical code which is must harder to debug. |
| 2380 | // TODO: It would be nice to test consistency as well |
| 2381 | assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) && |
| 2382 | "statepoint must be reachable or liveness is meaningless"); |
| 2383 | for (Value *V : statepoint.gc_args()) { |
| 2384 | if (!isa<Instruction>(V)) |
| 2385 | // Non-instruction values trivial dominate all possible uses |
| 2386 | continue; |
| 2387 | auto LiveInst = cast<Instruction>(V); |
| 2388 | assert(DT.isReachableFromEntry(LiveInst->getParent()) && |
| 2389 | "unreachable values should never be live"); |
| 2390 | assert(DT.dominates(LiveInst, info.StatepointToken) && |
| 2391 | "basic SSA liveness expectation violated by liveness analysis"); |
| 2392 | } |
| 2393 | #endif |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2394 | } |
| 2395 | unique_unsorted(live); |
| 2396 | |
Nick Lewycky | eb3231e | 2015-02-20 07:14:02 +0000 | [diff] [blame] | 2397 | #ifndef NDEBUG |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2398 | // sanity check |
| 2399 | for (auto ptr : live) { |
| 2400 | assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type"); |
| 2401 | } |
Nick Lewycky | eb3231e | 2015-02-20 07:14:02 +0000 | [diff] [blame] | 2402 | #endif |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2403 | |
| 2404 | relocationViaAlloca(F, DT, live, records); |
| 2405 | return !records.empty(); |
| 2406 | } |
| 2407 | |
Sanjoy Das | 353a19e | 2015-06-02 22:33:37 +0000 | [diff] [blame] | 2408 | // Handles both return values and arguments for Functions and CallSites. |
| 2409 | template <typename AttrHolder> |
| 2410 | static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH, |
| 2411 | unsigned Index) { |
| 2412 | AttrBuilder R; |
| 2413 | if (AH.getDereferenceableBytes(Index)) |
| 2414 | R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable, |
| 2415 | AH.getDereferenceableBytes(Index))); |
| 2416 | if (AH.getDereferenceableOrNullBytes(Index)) |
| 2417 | R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull, |
| 2418 | AH.getDereferenceableOrNullBytes(Index))); |
| 2419 | |
| 2420 | if (!R.empty()) |
| 2421 | AH.setAttributes(AH.getAttributes().removeAttributes( |
| 2422 | Ctx, Index, AttributeSet::get(Ctx, Index, R))); |
Vasileios Kalintiris | 9f77f61 | 2015-06-03 08:51:30 +0000 | [diff] [blame] | 2423 | } |
Sanjoy Das | 353a19e | 2015-06-02 22:33:37 +0000 | [diff] [blame] | 2424 | |
| 2425 | void |
| 2426 | RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) { |
| 2427 | LLVMContext &Ctx = F.getContext(); |
| 2428 | |
| 2429 | for (Argument &A : F.args()) |
| 2430 | if (isa<PointerType>(A.getType())) |
| 2431 | RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1); |
| 2432 | |
| 2433 | if (isa<PointerType>(F.getReturnType())) |
| 2434 | RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex); |
| 2435 | } |
| 2436 | |
| 2437 | void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) { |
| 2438 | if (F.empty()) |
| 2439 | return; |
| 2440 | |
| 2441 | LLVMContext &Ctx = F.getContext(); |
| 2442 | MDBuilder Builder(Ctx); |
| 2443 | |
Nico Rieck | 7819951 | 2015-08-06 19:10:45 +0000 | [diff] [blame] | 2444 | for (Instruction &I : instructions(F)) { |
Sanjoy Das | 353a19e | 2015-06-02 22:33:37 +0000 | [diff] [blame] | 2445 | if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) { |
| 2446 | assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!"); |
| 2447 | bool IsImmutableTBAA = |
| 2448 | MD->getNumOperands() == 4 && |
| 2449 | mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1; |
| 2450 | |
| 2451 | if (!IsImmutableTBAA) |
| 2452 | continue; // no work to do, MD_tbaa is already marked mutable |
| 2453 | |
| 2454 | MDNode *Base = cast<MDNode>(MD->getOperand(0)); |
| 2455 | MDNode *Access = cast<MDNode>(MD->getOperand(1)); |
| 2456 | uint64_t Offset = |
| 2457 | mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue(); |
| 2458 | |
| 2459 | MDNode *MutableTBAA = |
| 2460 | Builder.createTBAAStructTagNode(Base, Access, Offset); |
| 2461 | I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA); |
| 2462 | } |
| 2463 | |
| 2464 | if (CallSite CS = CallSite(&I)) { |
| 2465 | for (int i = 0, e = CS.arg_size(); i != e; i++) |
| 2466 | if (isa<PointerType>(CS.getArgument(i)->getType())) |
| 2467 | RemoveDerefAttrAtIndex(Ctx, CS, i + 1); |
| 2468 | if (isa<PointerType>(CS.getType())) |
| 2469 | RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex); |
| 2470 | } |
| 2471 | } |
| 2472 | } |
| 2473 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2474 | /// Returns true if this function should be rewritten by this pass. The main |
| 2475 | /// point of this function is as an extension point for custom logic. |
| 2476 | static bool shouldRewriteStatepointsIn(Function &F) { |
| 2477 | // TODO: This should check the GCStrategy |
Philip Reames | 2ef029c | 2015-02-20 18:56:14 +0000 | [diff] [blame] | 2478 | if (F.hasGC()) { |
NAKAMURA Takumi | fb3bd71 | 2015-05-25 01:43:23 +0000 | [diff] [blame] | 2479 | const char *FunctionGCName = F.getGC(); |
| 2480 | const StringRef StatepointExampleName("statepoint-example"); |
| 2481 | const StringRef CoreCLRName("coreclr"); |
| 2482 | return (StatepointExampleName == FunctionGCName) || |
NAKAMURA Takumi | 5582a6a | 2015-05-25 01:43:34 +0000 | [diff] [blame] | 2483 | (CoreCLRName == FunctionGCName); |
| 2484 | } else |
Philip Reames | 2ef029c | 2015-02-20 18:56:14 +0000 | [diff] [blame] | 2485 | return false; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2486 | } |
| 2487 | |
Sanjoy Das | 353a19e | 2015-06-02 22:33:37 +0000 | [diff] [blame] | 2488 | void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) { |
| 2489 | #ifndef NDEBUG |
| 2490 | assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) && |
| 2491 | "precondition!"); |
| 2492 | #endif |
| 2493 | |
| 2494 | for (Function &F : M) |
| 2495 | stripDereferenceabilityInfoFromPrototype(F); |
| 2496 | |
| 2497 | for (Function &F : M) |
| 2498 | stripDereferenceabilityInfoFromBody(F); |
| 2499 | } |
| 2500 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2501 | bool RewriteStatepointsForGC::runOnFunction(Function &F) { |
| 2502 | // Nothing to do for declarations. |
| 2503 | if (F.isDeclaration() || F.empty()) |
| 2504 | return false; |
| 2505 | |
| 2506 | // Policy choice says not to rewrite - the most common reason is that we're |
| 2507 | // compiling code without a GCStrategy. |
| 2508 | if (!shouldRewriteStatepointsIn(F)) |
| 2509 | return false; |
| 2510 | |
Sanjoy Das | ea45f0e | 2015-06-02 22:33:34 +0000 | [diff] [blame] | 2511 | DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 2512 | |
Philip Reames | 85b36a8 | 2015-04-10 22:07:04 +0000 | [diff] [blame] | 2513 | // Gather all the statepoints which need rewritten. Be careful to only |
| 2514 | // consider those in reachable code since we need to ask dominance queries |
| 2515 | // when rewriting. We'll delete the unreachable ones in a moment. |
Philip Reames | d2b6646 | 2015-02-20 22:39:41 +0000 | [diff] [blame] | 2516 | SmallVector<CallSite, 64> ParsePointNeeded; |
Philip Reames | f66d737 | 2015-04-10 22:16:58 +0000 | [diff] [blame] | 2517 | bool HasUnreachableStatepoint = false; |
Nico Rieck | 7819951 | 2015-08-06 19:10:45 +0000 | [diff] [blame] | 2518 | for (Instruction &I : instructions(F)) { |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2519 | // TODO: only the ones with the flag set! |
Philip Reames | 85b36a8 | 2015-04-10 22:07:04 +0000 | [diff] [blame] | 2520 | if (isStatepoint(I)) { |
| 2521 | if (DT.isReachableFromEntry(I.getParent())) |
| 2522 | ParsePointNeeded.push_back(CallSite(&I)); |
| 2523 | else |
Philip Reames | f66d737 | 2015-04-10 22:16:58 +0000 | [diff] [blame] | 2524 | HasUnreachableStatepoint = true; |
Philip Reames | 85b36a8 | 2015-04-10 22:07:04 +0000 | [diff] [blame] | 2525 | } |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2526 | } |
| 2527 | |
Philip Reames | 85b36a8 | 2015-04-10 22:07:04 +0000 | [diff] [blame] | 2528 | bool MadeChange = false; |
Philip Reames | 704e78b | 2015-04-10 22:34:56 +0000 | [diff] [blame] | 2529 | |
Philip Reames | 85b36a8 | 2015-04-10 22:07:04 +0000 | [diff] [blame] | 2530 | // Delete any unreachable statepoints so that we don't have unrewritten |
| 2531 | // statepoints surviving this pass. This makes testing easier and the |
| 2532 | // resulting IR less confusing to human readers. Rather than be fancy, we |
| 2533 | // just reuse a utility function which removes the unreachable blocks. |
Philip Reames | f66d737 | 2015-04-10 22:16:58 +0000 | [diff] [blame] | 2534 | if (HasUnreachableStatepoint) |
Philip Reames | 85b36a8 | 2015-04-10 22:07:04 +0000 | [diff] [blame] | 2535 | MadeChange |= removeUnreachableBlocks(F); |
| 2536 | |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2537 | // Return early if no work to do. |
| 2538 | if (ParsePointNeeded.empty()) |
Philip Reames | 85b36a8 | 2015-04-10 22:07:04 +0000 | [diff] [blame] | 2539 | return MadeChange; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2540 | |
Philip Reames | 85b36a8 | 2015-04-10 22:07:04 +0000 | [diff] [blame] | 2541 | // As a prepass, go ahead and aggressively destroy single entry phi nodes. |
| 2542 | // These are created by LCSSA. They have the effect of increasing the size |
| 2543 | // of liveness sets for no good reason. It may be harder to do this post |
| 2544 | // insertion since relocations and base phis can confuse things. |
| 2545 | for (BasicBlock &BB : F) |
| 2546 | if (BB.getUniquePredecessor()) { |
| 2547 | MadeChange = true; |
| 2548 | FoldSingleEntryPHINodes(&BB); |
| 2549 | } |
| 2550 | |
Philip Reames | 971dc3a | 2015-08-12 22:11:45 +0000 | [diff] [blame] | 2551 | // Before we start introducing relocations, we want to tweak the IR a bit to |
| 2552 | // avoid unfortunate code generation effects. The main example is that we |
| 2553 | // want to try to make sure the comparison feeding a branch is after any |
| 2554 | // safepoints. Otherwise, we end up with a comparison of pre-relocation |
| 2555 | // values feeding a branch after relocation. This is semantically correct, |
| 2556 | // but results in extra register pressure since both the pre-relocation and |
| 2557 | // post-relocation copies must be available in registers. For code without |
| 2558 | // relocations this is handled elsewhere, but teaching the scheduler to |
| 2559 | // reverse the transform we're about to do would be slightly complex. |
| 2560 | // Note: This may extend the live range of the inputs to the icmp and thus |
| 2561 | // increase the liveset of any statepoint we move over. This is profitable |
| 2562 | // as long as all statepoints are in rare blocks. If we had in-register |
| 2563 | // lowering for live values this would be a much safer transform. |
| 2564 | auto getConditionInst = [](TerminatorInst *TI) -> Instruction* { |
| 2565 | if (auto *BI = dyn_cast<BranchInst>(TI)) |
| 2566 | if (BI->isConditional()) |
| 2567 | return dyn_cast<Instruction>(BI->getCondition()); |
| 2568 | // TODO: Extend this to handle switches |
| 2569 | return nullptr; |
| 2570 | }; |
| 2571 | for (BasicBlock &BB : F) { |
| 2572 | TerminatorInst *TI = BB.getTerminator(); |
| 2573 | if (auto *Cond = getConditionInst(TI)) |
| 2574 | // TODO: Handle more than just ICmps here. We should be able to move |
| 2575 | // most instructions without side effects or memory access. |
| 2576 | if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) { |
| 2577 | MadeChange = true; |
| 2578 | Cond->moveBefore(TI); |
| 2579 | } |
| 2580 | } |
| 2581 | |
Philip Reames | 85b36a8 | 2015-04-10 22:07:04 +0000 | [diff] [blame] | 2582 | MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded); |
| 2583 | return MadeChange; |
Philip Reames | d16a9b1 | 2015-02-20 01:06:44 +0000 | [diff] [blame] | 2584 | } |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2585 | |
| 2586 | // liveness computation via standard dataflow |
| 2587 | // ------------------------------------------------------------------- |
| 2588 | |
| 2589 | // TODO: Consider using bitvectors for liveness, the set of potentially |
| 2590 | // interesting values should be small and easy to pre-compute. |
| 2591 | |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2592 | /// Compute the live-in set for the location rbegin starting from |
| 2593 | /// the live-out set of the basic block |
| 2594 | static void computeLiveInValues(BasicBlock::reverse_iterator rbegin, |
| 2595 | BasicBlock::reverse_iterator rend, |
| 2596 | DenseSet<Value *> &LiveTmp) { |
| 2597 | |
| 2598 | for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) { |
| 2599 | Instruction *I = &*ritr; |
| 2600 | |
| 2601 | // KILL/Def - Remove this definition from LiveIn |
| 2602 | LiveTmp.erase(I); |
| 2603 | |
| 2604 | // Don't consider *uses* in PHI nodes, we handle their contribution to |
| 2605 | // predecessor blocks when we seed the LiveOut sets |
| 2606 | if (isa<PHINode>(I)) |
| 2607 | continue; |
| 2608 | |
| 2609 | // USE - Add to the LiveIn set for this instruction |
| 2610 | for (Value *V : I->operands()) { |
| 2611 | assert(!isUnhandledGCPointerType(V->getType()) && |
| 2612 | "support for FCA unimplemented"); |
Philip Reames | 63294cb | 2015-04-26 19:48:03 +0000 | [diff] [blame] | 2613 | if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) { |
| 2614 | // The choice to exclude all things constant here is slightly subtle. |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 2615 | // There are two independent reasons: |
Philip Reames | 63294cb | 2015-04-26 19:48:03 +0000 | [diff] [blame] | 2616 | // - We assume that things which are constant (from LLVM's definition) |
| 2617 | // do not move at runtime. For example, the address of a global |
| 2618 | // variable is fixed, even though it's contents may not be. |
| 2619 | // - Second, we can't disallow arbitrary inttoptr constants even |
| 2620 | // if the language frontend does. Optimization passes are free to |
| 2621 | // locally exploit facts without respect to global reachability. This |
| 2622 | // can create sections of code which are dynamically unreachable and |
| 2623 | // contain just about anything. (see constants.ll in tests) |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2624 | LiveTmp.insert(V); |
| 2625 | } |
| 2626 | } |
| 2627 | } |
| 2628 | } |
| 2629 | |
| 2630 | static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) { |
| 2631 | |
| 2632 | for (BasicBlock *Succ : successors(BB)) { |
| 2633 | const BasicBlock::iterator E(Succ->getFirstNonPHI()); |
| 2634 | for (BasicBlock::iterator I = Succ->begin(); I != E; I++) { |
| 2635 | PHINode *Phi = cast<PHINode>(&*I); |
| 2636 | Value *V = Phi->getIncomingValueForBlock(BB); |
| 2637 | assert(!isUnhandledGCPointerType(V->getType()) && |
| 2638 | "support for FCA unimplemented"); |
Philip Reames | 63294cb | 2015-04-26 19:48:03 +0000 | [diff] [blame] | 2639 | if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) { |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2640 | LiveTmp.insert(V); |
| 2641 | } |
| 2642 | } |
| 2643 | } |
| 2644 | } |
| 2645 | |
| 2646 | static DenseSet<Value *> computeKillSet(BasicBlock *BB) { |
| 2647 | DenseSet<Value *> KillSet; |
| 2648 | for (Instruction &I : *BB) |
| 2649 | if (isHandledGCPointerType(I.getType())) |
| 2650 | KillSet.insert(&I); |
| 2651 | return KillSet; |
| 2652 | } |
| 2653 | |
Philip Reames | 9638ff9 | 2015-04-11 00:06:47 +0000 | [diff] [blame] | 2654 | #ifndef NDEBUG |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2655 | /// Check that the items in 'Live' dominate 'TI'. This is used as a basic |
| 2656 | /// sanity check for the liveness computation. |
| 2657 | static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live, |
| 2658 | TerminatorInst *TI, bool TermOkay = false) { |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2659 | for (Value *V : Live) { |
| 2660 | if (auto *I = dyn_cast<Instruction>(V)) { |
| 2661 | // The terminator can be a member of the LiveOut set. LLVM's definition |
| 2662 | // of instruction dominance states that V does not dominate itself. As |
| 2663 | // such, we need to special case this to allow it. |
| 2664 | if (TermOkay && TI == I) |
| 2665 | continue; |
| 2666 | assert(DT.dominates(I, TI) && |
| 2667 | "basic SSA liveness expectation violated by liveness analysis"); |
| 2668 | } |
| 2669 | } |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2670 | } |
| 2671 | |
| 2672 | /// Check that all the liveness sets used during the computation of liveness |
| 2673 | /// obey basic SSA properties. This is useful for finding cases where we miss |
| 2674 | /// a def. |
| 2675 | static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data, |
| 2676 | BasicBlock &BB) { |
| 2677 | checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator()); |
| 2678 | checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true); |
| 2679 | checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator()); |
| 2680 | } |
Philip Reames | 9638ff9 | 2015-04-11 00:06:47 +0000 | [diff] [blame] | 2681 | #endif |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2682 | |
| 2683 | static void computeLiveInValues(DominatorTree &DT, Function &F, |
| 2684 | GCPtrLivenessData &Data) { |
| 2685 | |
Philip Reames | 4d80ede | 2015-04-10 23:11:26 +0000 | [diff] [blame] | 2686 | SmallSetVector<BasicBlock *, 200> Worklist; |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2687 | auto AddPredsToWorklist = [&](BasicBlock *BB) { |
Philip Reames | 4d80ede | 2015-04-10 23:11:26 +0000 | [diff] [blame] | 2688 | // We use a SetVector so that we don't have duplicates in the worklist. |
| 2689 | Worklist.insert(pred_begin(BB), pred_end(BB)); |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2690 | }; |
| 2691 | auto NextItem = [&]() { |
| 2692 | BasicBlock *BB = Worklist.back(); |
| 2693 | Worklist.pop_back(); |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2694 | return BB; |
| 2695 | }; |
| 2696 | |
| 2697 | // Seed the liveness for each individual block |
| 2698 | for (BasicBlock &BB : F) { |
| 2699 | Data.KillSet[&BB] = computeKillSet(&BB); |
| 2700 | Data.LiveSet[&BB].clear(); |
| 2701 | computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]); |
| 2702 | |
| 2703 | #ifndef NDEBUG |
| 2704 | for (Value *Kill : Data.KillSet[&BB]) |
| 2705 | assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill"); |
| 2706 | #endif |
| 2707 | |
| 2708 | Data.LiveOut[&BB] = DenseSet<Value *>(); |
| 2709 | computeLiveOutSeed(&BB, Data.LiveOut[&BB]); |
| 2710 | Data.LiveIn[&BB] = Data.LiveSet[&BB]; |
| 2711 | set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]); |
| 2712 | set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]); |
| 2713 | if (!Data.LiveIn[&BB].empty()) |
| 2714 | AddPredsToWorklist(&BB); |
| 2715 | } |
| 2716 | |
| 2717 | // Propagate that liveness until stable |
| 2718 | while (!Worklist.empty()) { |
| 2719 | BasicBlock *BB = NextItem(); |
| 2720 | |
| 2721 | // Compute our new liveout set, then exit early if it hasn't changed |
| 2722 | // despite the contribution of our successor. |
| 2723 | DenseSet<Value *> LiveOut = Data.LiveOut[BB]; |
| 2724 | const auto OldLiveOutSize = LiveOut.size(); |
| 2725 | for (BasicBlock *Succ : successors(BB)) { |
| 2726 | assert(Data.LiveIn.count(Succ)); |
| 2727 | set_union(LiveOut, Data.LiveIn[Succ]); |
| 2728 | } |
| 2729 | // assert OutLiveOut is a subset of LiveOut |
| 2730 | if (OldLiveOutSize == LiveOut.size()) { |
| 2731 | // If the sets are the same size, then we didn't actually add anything |
| 2732 | // when unioning our successors LiveIn Thus, the LiveIn of this block |
| 2733 | // hasn't changed. |
| 2734 | continue; |
| 2735 | } |
| 2736 | Data.LiveOut[BB] = LiveOut; |
| 2737 | |
| 2738 | // Apply the effects of this basic block |
| 2739 | DenseSet<Value *> LiveTmp = LiveOut; |
| 2740 | set_union(LiveTmp, Data.LiveSet[BB]); |
| 2741 | set_subtract(LiveTmp, Data.KillSet[BB]); |
| 2742 | |
| 2743 | assert(Data.LiveIn.count(BB)); |
| 2744 | const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB]; |
| 2745 | // assert: OldLiveIn is a subset of LiveTmp |
| 2746 | if (OldLiveIn.size() != LiveTmp.size()) { |
| 2747 | Data.LiveIn[BB] = LiveTmp; |
| 2748 | AddPredsToWorklist(BB); |
| 2749 | } |
| 2750 | } // while( !worklist.empty() ) |
| 2751 | |
| 2752 | #ifndef NDEBUG |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 2753 | // Sanity check our output against SSA properties. This helps catch any |
Philip Reames | df1ef08 | 2015-04-10 22:53:14 +0000 | [diff] [blame] | 2754 | // missing kills during the above iteration. |
| 2755 | for (BasicBlock &BB : F) { |
| 2756 | checkBasicSSA(DT, Data, BB); |
| 2757 | } |
| 2758 | #endif |
| 2759 | } |
| 2760 | |
| 2761 | static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data, |
| 2762 | StatepointLiveSetTy &Out) { |
| 2763 | |
| 2764 | BasicBlock *BB = Inst->getParent(); |
| 2765 | |
| 2766 | // Note: The copy is intentional and required |
| 2767 | assert(Data.LiveOut.count(BB)); |
| 2768 | DenseSet<Value *> LiveOut = Data.LiveOut[BB]; |
| 2769 | |
| 2770 | // We want to handle the statepoint itself oddly. It's |
| 2771 | // call result is not live (normal), nor are it's arguments |
| 2772 | // (unless they're used again later). This adjustment is |
| 2773 | // specifically what we need to relocate |
| 2774 | BasicBlock::reverse_iterator rend(Inst); |
| 2775 | computeLiveInValues(BB->rbegin(), rend, LiveOut); |
| 2776 | LiveOut.erase(Inst); |
| 2777 | Out.insert(LiveOut.begin(), LiveOut.end()); |
| 2778 | } |
| 2779 | |
| 2780 | static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData, |
| 2781 | const CallSite &CS, |
| 2782 | PartiallyConstructedSafepointRecord &Info) { |
| 2783 | Instruction *Inst = CS.getInstruction(); |
| 2784 | StatepointLiveSetTy Updated; |
| 2785 | findLiveSetAtInst(Inst, RevisedLivenessData, Updated); |
| 2786 | |
| 2787 | #ifndef NDEBUG |
| 2788 | DenseSet<Value *> Bases; |
| 2789 | for (auto KVPair : Info.PointerToBase) { |
| 2790 | Bases.insert(KVPair.second); |
| 2791 | } |
| 2792 | #endif |
| 2793 | // We may have base pointers which are now live that weren't before. We need |
| 2794 | // to update the PointerToBase structure to reflect this. |
| 2795 | for (auto V : Updated) |
| 2796 | if (!Info.PointerToBase.count(V)) { |
| 2797 | assert(Bases.count(V) && "can't find base for unexpected live value"); |
| 2798 | Info.PointerToBase[V] = V; |
| 2799 | continue; |
| 2800 | } |
| 2801 | |
| 2802 | #ifndef NDEBUG |
| 2803 | for (auto V : Updated) { |
| 2804 | assert(Info.PointerToBase.count(V) && |
| 2805 | "must be able to find base for live value"); |
| 2806 | } |
| 2807 | #endif |
| 2808 | |
| 2809 | // Remove any stale base mappings - this can happen since our liveness is |
| 2810 | // more precise then the one inherent in the base pointer analysis |
| 2811 | DenseSet<Value *> ToErase; |
| 2812 | for (auto KVPair : Info.PointerToBase) |
| 2813 | if (!Updated.count(KVPair.first)) |
| 2814 | ToErase.insert(KVPair.first); |
| 2815 | for (auto V : ToErase) |
| 2816 | Info.PointerToBase.erase(V); |
| 2817 | |
| 2818 | #ifndef NDEBUG |
| 2819 | for (auto KVPair : Info.PointerToBase) |
| 2820 | assert(Updated.count(KVPair.first) && "record for non-live value"); |
| 2821 | #endif |
| 2822 | |
| 2823 | Info.liveset = Updated; |
| 2824 | } |