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