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" 17 #include "llvm/ADT/SetOperations.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/ADT/DenseSet.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/IR/BasicBlock.h" 22 #include "llvm/IR/CallSite.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/IRBuilder.h" 26 #include "llvm/IR/InstIterator.h" 27 #include "llvm/IR/Instructions.h" 28 #include "llvm/IR/Intrinsics.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/IR/Statepoint.h" 32 #include "llvm/IR/Value.h" 33 #include "llvm/IR/Verifier.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Transforms/Scalar.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 #include "llvm/Transforms/Utils/Cloning.h" 39 #include "llvm/Transforms/Utils/Local.h" 40 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 41 42 #define DEBUG_TYPE "rewrite-statepoints-for-gc" 43 44 using namespace llvm; 45 46 // Print tracing output 47 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden, 48 cl::init(false)); 49 50 // Print the liveset found at the insert location 51 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden, 52 cl::init(false)); 53 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden, 54 cl::init(false)); 55 // Print out the base pointers for debugging 56 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden, 57 cl::init(false)); 58 59 #ifdef XDEBUG 60 static bool ClobberNonLive = true; 61 #else 62 static bool ClobberNonLive = false; 63 #endif 64 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live", 65 cl::location(ClobberNonLive), 66 cl::Hidden); 67 68 namespace { 69 struct RewriteStatepointsForGC : public FunctionPass { 70 static char ID; // Pass identification, replacement for typeid 71 72 RewriteStatepointsForGC() : FunctionPass(ID) { 73 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry()); 74 } 75 bool runOnFunction(Function &F) override; 76 77 void getAnalysisUsage(AnalysisUsage &AU) const override { 78 // We add and rewrite a bunch of instructions, but don't really do much 79 // else. We could in theory preserve a lot more analyses here. 80 AU.addRequired<DominatorTreeWrapperPass>(); 81 } 82 }; 83 } // namespace 84 85 char RewriteStatepointsForGC::ID = 0; 86 87 FunctionPass *llvm::createRewriteStatepointsForGCPass() { 88 return new RewriteStatepointsForGC(); 89 } 90 91 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc", 92 "Make relocations explicit at statepoints", false, false) 93 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 94 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc", 95 "Make relocations explicit at statepoints", false, false) 96 97 namespace { 98 struct GCPtrLivenessData { 99 /// Values defined in this block. 100 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet; 101 /// Values used in this block (and thus live); does not included values 102 /// killed within this block. 103 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet; 104 105 /// Values live into this basic block (i.e. used by any 106 /// instruction in this basic block or ones reachable from here) 107 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn; 108 109 /// Values live out of this basic block (i.e. live into 110 /// any successor block) 111 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut; 112 }; 113 114 // The type of the internal cache used inside the findBasePointers family 115 // of functions. From the callers perspective, this is an opaque type and 116 // should not be inspected. 117 // 118 // In the actual implementation this caches two relations: 119 // - The base relation itself (i.e. this pointer is based on that one) 120 // - The base defining value relation (i.e. before base_phi insertion) 121 // Generally, after the execution of a full findBasePointer call, only the 122 // base relation will remain. Internally, we add a mixture of the two 123 // types, then update all the second type to the first type 124 typedef DenseMap<Value *, Value *> DefiningValueMapTy; 125 typedef DenseSet<llvm::Value *> StatepointLiveSetTy; 126 127 struct PartiallyConstructedSafepointRecord { 128 /// The set of values known to be live accross this safepoint 129 StatepointLiveSetTy liveset; 130 131 /// Mapping from live pointers to a base-defining-value 132 DenseMap<llvm::Value *, llvm::Value *> PointerToBase; 133 134 /// Any new values which were added to the IR during base pointer analysis 135 /// for this safepoint 136 DenseSet<llvm::Value *> NewInsertedDefs; 137 138 /// The *new* gc.statepoint instruction itself. This produces the token 139 /// that normal path gc.relocates and the gc.result are tied to. 140 Instruction *StatepointToken; 141 142 /// Instruction to which exceptional gc relocates are attached 143 /// Makes it easier to iterate through them during relocationViaAlloca. 144 Instruction *UnwindToken; 145 }; 146 } 147 148 /// Compute the live-in set for every basic block in the function 149 static void computeLiveInValues(DominatorTree &DT, Function &F, 150 GCPtrLivenessData &Data); 151 152 /// Given results from the dataflow liveness computation, find the set of live 153 /// Values at a particular instruction. 154 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data, 155 StatepointLiveSetTy &out); 156 157 // TODO: Once we can get to the GCStrategy, this becomes 158 // Optional<bool> isGCManagedPointer(const Value *V) const override { 159 160 static bool isGCPointerType(const Type *T) { 161 if (const PointerType *PT = dyn_cast<PointerType>(T)) 162 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our 163 // GC managed heap. We know that a pointer into this heap needs to be 164 // updated and that no other pointer does. 165 return (1 == PT->getAddressSpace()); 166 return false; 167 } 168 169 // Return true if this type is one which a) is a gc pointer or contains a GC 170 // pointer and b) is of a type this code expects to encounter as a live value. 171 // (The insertion code will assert that a type which matches (a) and not (b) 172 // is not encountered.) 173 static bool isHandledGCPointerType(Type *T) { 174 // We fully support gc pointers 175 if (isGCPointerType(T)) 176 return true; 177 // We partially support vectors of gc pointers. The code will assert if it 178 // can't handle something. 179 if (auto VT = dyn_cast<VectorType>(T)) 180 if (isGCPointerType(VT->getElementType())) 181 return true; 182 return false; 183 } 184 185 #ifndef NDEBUG 186 /// Returns true if this type contains a gc pointer whether we know how to 187 /// handle that type or not. 188 static bool containsGCPtrType(Type *Ty) { 189 if (isGCPointerType(Ty)) 190 return true; 191 if (VectorType *VT = dyn_cast<VectorType>(Ty)) 192 return isGCPointerType(VT->getScalarType()); 193 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) 194 return containsGCPtrType(AT->getElementType()); 195 if (StructType *ST = dyn_cast<StructType>(Ty)) 196 return std::any_of( 197 ST->subtypes().begin(), ST->subtypes().end(), 198 [](Type *SubType) { return containsGCPtrType(SubType); }); 199 return false; 200 } 201 202 // Returns true if this is a type which a) is a gc pointer or contains a GC 203 // pointer and b) is of a type which the code doesn't expect (i.e. first class 204 // aggregates). Used to trip assertions. 205 static bool isUnhandledGCPointerType(Type *Ty) { 206 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty); 207 } 208 #endif 209 210 static bool order_by_name(llvm::Value *a, llvm::Value *b) { 211 if (a->hasName() && b->hasName()) { 212 return -1 == a->getName().compare(b->getName()); 213 } else if (a->hasName() && !b->hasName()) { 214 return true; 215 } else if (!a->hasName() && b->hasName()) { 216 return false; 217 } else { 218 // Better than nothing, but not stable 219 return a < b; 220 } 221 } 222 223 // Conservatively identifies any definitions which might be live at the 224 // given instruction. The analysis is performed immediately before the 225 // given instruction. Values defined by that instruction are not considered 226 // live. Values used by that instruction are considered live. 227 static void analyzeParsePointLiveness( 228 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, 229 const CallSite &CS, PartiallyConstructedSafepointRecord &result) { 230 Instruction *inst = CS.getInstruction(); 231 232 StatepointLiveSetTy liveset; 233 findLiveSetAtInst(inst, OriginalLivenessData, liveset); 234 235 if (PrintLiveSet) { 236 // Note: This output is used by several of the test cases 237 // The order of elemtns in a set is not stable, put them in a vec and sort 238 // by name 239 SmallVector<Value *, 64> temp; 240 temp.insert(temp.end(), liveset.begin(), liveset.end()); 241 std::sort(temp.begin(), temp.end(), order_by_name); 242 errs() << "Live Variables:\n"; 243 for (Value *V : temp) { 244 errs() << " " << V->getName(); // no newline 245 V->dump(); 246 } 247 } 248 if (PrintLiveSetSize) { 249 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n"; 250 errs() << "Number live values: " << liveset.size() << "\n"; 251 } 252 result.liveset = liveset; 253 } 254 255 /// If we can trivially determine that this vector contains only base pointers, 256 /// return the base instruction. 257 static Value *findBaseOfVector(Value *I) { 258 assert(I->getType()->isVectorTy() && 259 cast<VectorType>(I->getType())->getElementType()->isPointerTy() && 260 "Illegal to ask for the base pointer of a non-pointer type"); 261 262 // Each case parallels findBaseDefiningValue below, see that code for 263 // detailed motivation. 264 265 if (isa<Argument>(I)) 266 // An incoming argument to the function is a base pointer 267 return I; 268 269 // We shouldn't see the address of a global as a vector value? 270 assert(!isa<GlobalVariable>(I) && 271 "unexpected global variable found in base of vector"); 272 273 // inlining could possibly introduce phi node that contains 274 // undef if callee has multiple returns 275 if (isa<UndefValue>(I)) 276 // utterly meaningless, but useful for dealing with partially optimized 277 // code. 278 return I; 279 280 // Due to inheritance, this must be _after_ the global variable and undef 281 // checks 282 if (Constant *Con = dyn_cast<Constant>(I)) { 283 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) && 284 "order of checks wrong!"); 285 assert(Con->isNullValue() && "null is the only case which makes sense"); 286 return Con; 287 } 288 289 if (isa<LoadInst>(I)) 290 return I; 291 292 // Note: This code is currently rather incomplete. We are essentially only 293 // handling cases where the vector element is trivially a base pointer. We 294 // need to update the entire base pointer construction algorithm to know how 295 // to track vector elements and potentially scalarize, but the case which 296 // would motivate the work hasn't shown up in real workloads yet. 297 llvm_unreachable("no base found for vector element"); 298 } 299 300 /// Helper function for findBasePointer - Will return a value which either a) 301 /// defines the base pointer for the input or b) blocks the simple search 302 /// (i.e. a PHI or Select of two derived pointers) 303 static Value *findBaseDefiningValue(Value *I) { 304 assert(I->getType()->isPointerTy() && 305 "Illegal to ask for the base pointer of a non-pointer type"); 306 307 // This case is a bit of a hack - it only handles extracts from vectors which 308 // trivially contain only base pointers. See note inside the function for 309 // how to improve this. 310 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) { 311 Value *VectorOperand = EEI->getVectorOperand(); 312 Value *VectorBase = findBaseOfVector(VectorOperand); 313 (void)VectorBase; 314 assert(VectorBase && "extract element not known to be a trivial base"); 315 return EEI; 316 } 317 318 if (isa<Argument>(I)) 319 // An incoming argument to the function is a base pointer 320 // We should have never reached here if this argument isn't an gc value 321 return I; 322 323 if (isa<GlobalVariable>(I)) 324 // base case 325 return I; 326 327 // inlining could possibly introduce phi node that contains 328 // undef if callee has multiple returns 329 if (isa<UndefValue>(I)) 330 // utterly meaningless, but useful for dealing with 331 // partially optimized code. 332 return I; 333 334 // Due to inheritance, this must be _after_ the global variable and undef 335 // checks 336 if (Constant *Con = dyn_cast<Constant>(I)) { 337 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) && 338 "order of checks wrong!"); 339 // Note: Finding a constant base for something marked for relocation 340 // doesn't really make sense. The most likely case is either a) some 341 // screwed up the address space usage or b) your validating against 342 // compiled C++ code w/o the proper separation. The only real exception 343 // is a null pointer. You could have generic code written to index of 344 // off a potentially null value and have proven it null. We also use 345 // null pointers in dead paths of relocation phis (which we might later 346 // want to find a base pointer for). 347 assert(isa<ConstantPointerNull>(Con) && 348 "null is the only case which makes sense"); 349 return Con; 350 } 351 352 if (CastInst *CI = dyn_cast<CastInst>(I)) { 353 Value *Def = CI->stripPointerCasts(); 354 // If we find a cast instruction here, it means we've found a cast which is 355 // not simply a pointer cast (i.e. an inttoptr). We don't know how to 356 // handle int->ptr conversion. 357 assert(!isa<CastInst>(Def) && "shouldn't find another cast here"); 358 return findBaseDefiningValue(Def); 359 } 360 361 if (isa<LoadInst>(I)) 362 return I; // The value loaded is an gc base itself 363 364 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) 365 // The base of this GEP is the base 366 return findBaseDefiningValue(GEP->getPointerOperand()); 367 368 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 369 switch (II->getIntrinsicID()) { 370 case Intrinsic::experimental_gc_result_ptr: 371 default: 372 // fall through to general call handling 373 break; 374 case Intrinsic::experimental_gc_statepoint: 375 case Intrinsic::experimental_gc_result_float: 376 case Intrinsic::experimental_gc_result_int: 377 llvm_unreachable("these don't produce pointers"); 378 case Intrinsic::experimental_gc_relocate: { 379 // Rerunning safepoint insertion after safepoints are already 380 // inserted is not supported. It could probably be made to work, 381 // but why are you doing this? There's no good reason. 382 llvm_unreachable("repeat safepoint insertion is not supported"); 383 } 384 case Intrinsic::gcroot: 385 // Currently, this mechanism hasn't been extended to work with gcroot. 386 // There's no reason it couldn't be, but I haven't thought about the 387 // implications much. 388 llvm_unreachable( 389 "interaction with the gcroot mechanism is not supported"); 390 } 391 } 392 // We assume that functions in the source language only return base 393 // pointers. This should probably be generalized via attributes to support 394 // both source language and internal functions. 395 if (isa<CallInst>(I) || isa<InvokeInst>(I)) 396 return I; 397 398 // I have absolutely no idea how to implement this part yet. It's not 399 // neccessarily hard, I just haven't really looked at it yet. 400 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented"); 401 402 if (isa<AtomicCmpXchgInst>(I)) 403 // A CAS is effectively a atomic store and load combined under a 404 // predicate. From the perspective of base pointers, we just treat it 405 // like a load. 406 return I; 407 408 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are " 409 "binary ops which don't apply to pointers"); 410 411 // The aggregate ops. Aggregates can either be in the heap or on the 412 // stack, but in either case, this is simply a field load. As a result, 413 // this is a defining definition of the base just like a load is. 414 if (isa<ExtractValueInst>(I)) 415 return I; 416 417 // We should never see an insert vector since that would require we be 418 // tracing back a struct value not a pointer value. 419 assert(!isa<InsertValueInst>(I) && 420 "Base pointer for a struct is meaningless"); 421 422 // The last two cases here don't return a base pointer. Instead, they 423 // return a value which dynamically selects from amoung several base 424 // derived pointers (each with it's own base potentially). It's the job of 425 // the caller to resolve these. 426 assert((isa<SelectInst>(I) || isa<PHINode>(I)) && 427 "missing instruction case in findBaseDefiningValing"); 428 return I; 429 } 430 431 /// Returns the base defining value for this value. 432 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) { 433 Value *&Cached = Cache[I]; 434 if (!Cached) { 435 Cached = findBaseDefiningValue(I); 436 } 437 assert(Cache[I] != nullptr); 438 439 if (TraceLSP) { 440 dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName() 441 << "\n"; 442 } 443 return Cached; 444 } 445 446 /// Return a base pointer for this value if known. Otherwise, return it's 447 /// base defining value. 448 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) { 449 Value *Def = findBaseDefiningValueCached(I, Cache); 450 auto Found = Cache.find(Def); 451 if (Found != Cache.end()) { 452 // Either a base-of relation, or a self reference. Caller must check. 453 return Found->second; 454 } 455 // Only a BDV available 456 return Def; 457 } 458 459 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV, 460 /// is it known to be a base pointer? Or do we need to continue searching. 461 static bool isKnownBaseResult(Value *V) { 462 if (!isa<PHINode>(V) && !isa<SelectInst>(V)) { 463 // no recursion possible 464 return true; 465 } 466 if (isa<Instruction>(V) && 467 cast<Instruction>(V)->getMetadata("is_base_value")) { 468 // This is a previously inserted base phi or select. We know 469 // that this is a base value. 470 return true; 471 } 472 473 // We need to keep searching 474 return false; 475 } 476 477 // TODO: find a better name for this 478 namespace { 479 class PhiState { 480 public: 481 enum Status { Unknown, Base, Conflict }; 482 483 PhiState(Status s, Value *b = nullptr) : status(s), base(b) { 484 assert(status != Base || b); 485 } 486 PhiState(Value *b) : status(Base), base(b) {} 487 PhiState() : status(Unknown), base(nullptr) {} 488 489 Status getStatus() const { return status; } 490 Value *getBase() const { return base; } 491 492 bool isBase() const { return getStatus() == Base; } 493 bool isUnknown() const { return getStatus() == Unknown; } 494 bool isConflict() const { return getStatus() == Conflict; } 495 496 bool operator==(const PhiState &other) const { 497 return base == other.base && status == other.status; 498 } 499 500 bool operator!=(const PhiState &other) const { return !(*this == other); } 501 502 void dump() { 503 errs() << status << " (" << base << " - " 504 << (base ? base->getName() : "nullptr") << "): "; 505 } 506 507 private: 508 Status status; 509 Value *base; // non null only if status == base 510 }; 511 512 typedef DenseMap<Value *, PhiState> ConflictStateMapTy; 513 // Values of type PhiState form a lattice, and this is a helper 514 // class that implementes the meet operation. The meat of the meet 515 // operation is implemented in MeetPhiStates::pureMeet 516 class MeetPhiStates { 517 public: 518 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates. 519 explicit MeetPhiStates(const ConflictStateMapTy &phiStates) 520 : phiStates(phiStates) {} 521 522 // Destructively meet the current result with the base V. V can 523 // either be a merge instruction (SelectInst / PHINode), in which 524 // case its status is looked up in the phiStates map; or a regular 525 // SSA value, in which case it is assumed to be a base. 526 void meetWith(Value *V) { 527 PhiState otherState = getStateForBDV(V); 528 assert((MeetPhiStates::pureMeet(otherState, currentResult) == 529 MeetPhiStates::pureMeet(currentResult, otherState)) && 530 "math is wrong: meet does not commute!"); 531 currentResult = MeetPhiStates::pureMeet(otherState, currentResult); 532 } 533 534 PhiState getResult() const { return currentResult; } 535 536 private: 537 const ConflictStateMapTy &phiStates; 538 PhiState currentResult; 539 540 /// Return a phi state for a base defining value. We'll generate a new 541 /// base state for known bases and expect to find a cached state otherwise 542 PhiState getStateForBDV(Value *baseValue) { 543 if (isKnownBaseResult(baseValue)) { 544 return PhiState(baseValue); 545 } else { 546 return lookupFromMap(baseValue); 547 } 548 } 549 550 PhiState lookupFromMap(Value *V) { 551 auto I = phiStates.find(V); 552 assert(I != phiStates.end() && "lookup failed!"); 553 return I->second; 554 } 555 556 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) { 557 switch (stateA.getStatus()) { 558 case PhiState::Unknown: 559 return stateB; 560 561 case PhiState::Base: 562 assert(stateA.getBase() && "can't be null"); 563 if (stateB.isUnknown()) 564 return stateA; 565 566 if (stateB.isBase()) { 567 if (stateA.getBase() == stateB.getBase()) { 568 assert(stateA == stateB && "equality broken!"); 569 return stateA; 570 } 571 return PhiState(PhiState::Conflict); 572 } 573 assert(stateB.isConflict() && "only three states!"); 574 return PhiState(PhiState::Conflict); 575 576 case PhiState::Conflict: 577 return stateA; 578 } 579 llvm_unreachable("only three states!"); 580 } 581 }; 582 } 583 /// For a given value or instruction, figure out what base ptr it's derived 584 /// from. For gc objects, this is simply itself. On success, returns a value 585 /// which is the base pointer. (This is reliable and can be used for 586 /// relocation.) On failure, returns nullptr. 587 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache, 588 DenseSet<llvm::Value *> &NewInsertedDefs) { 589 Value *def = findBaseOrBDV(I, cache); 590 591 if (isKnownBaseResult(def)) { 592 return def; 593 } 594 595 // Here's the rough algorithm: 596 // - For every SSA value, construct a mapping to either an actual base 597 // pointer or a PHI which obscures the base pointer. 598 // - Construct a mapping from PHI to unknown TOP state. Use an 599 // optimistic algorithm to propagate base pointer information. Lattice 600 // looks like: 601 // UNKNOWN 602 // b1 b2 b3 b4 603 // CONFLICT 604 // When algorithm terminates, all PHIs will either have a single concrete 605 // base or be in a conflict state. 606 // - For every conflict, insert a dummy PHI node without arguments. Add 607 // these to the base[Instruction] = BasePtr mapping. For every 608 // non-conflict, add the actual base. 609 // - For every conflict, add arguments for the base[a] of each input 610 // arguments. 611 // 612 // Note: A simpler form of this would be to add the conflict form of all 613 // PHIs without running the optimistic algorithm. This would be 614 // analougous to pessimistic data flow and would likely lead to an 615 // overall worse solution. 616 617 ConflictStateMapTy states; 618 states[def] = PhiState(); 619 // Recursively fill in all phis & selects reachable from the initial one 620 // for which we don't already know a definite base value for 621 // TODO: This should be rewritten with a worklist 622 bool done = false; 623 while (!done) { 624 done = true; 625 // Since we're adding elements to 'states' as we run, we can't keep 626 // iterators into the set. 627 SmallVector<Value *, 16> Keys; 628 Keys.reserve(states.size()); 629 for (auto Pair : states) { 630 Value *V = Pair.first; 631 Keys.push_back(V); 632 } 633 for (Value *v : Keys) { 634 assert(!isKnownBaseResult(v) && "why did it get added?"); 635 if (PHINode *phi = dyn_cast<PHINode>(v)) { 636 assert(phi->getNumIncomingValues() > 0 && 637 "zero input phis are illegal"); 638 for (Value *InVal : phi->incoming_values()) { 639 Value *local = findBaseOrBDV(InVal, cache); 640 if (!isKnownBaseResult(local) && states.find(local) == states.end()) { 641 states[local] = PhiState(); 642 done = false; 643 } 644 } 645 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) { 646 Value *local = findBaseOrBDV(sel->getTrueValue(), cache); 647 if (!isKnownBaseResult(local) && states.find(local) == states.end()) { 648 states[local] = PhiState(); 649 done = false; 650 } 651 local = findBaseOrBDV(sel->getFalseValue(), cache); 652 if (!isKnownBaseResult(local) && states.find(local) == states.end()) { 653 states[local] = PhiState(); 654 done = false; 655 } 656 } 657 } 658 } 659 660 if (TraceLSP) { 661 errs() << "States after initialization:\n"; 662 for (auto Pair : states) { 663 Instruction *v = cast<Instruction>(Pair.first); 664 PhiState state = Pair.second; 665 state.dump(); 666 v->dump(); 667 } 668 } 669 670 // TODO: come back and revisit the state transitions around inputs which 671 // have reached conflict state. The current version seems too conservative. 672 673 bool progress = true; 674 while (progress) { 675 #ifndef NDEBUG 676 size_t oldSize = states.size(); 677 #endif 678 progress = false; 679 // We're only changing keys in this loop, thus safe to keep iterators 680 for (auto Pair : states) { 681 MeetPhiStates calculateMeet(states); 682 Value *v = Pair.first; 683 assert(!isKnownBaseResult(v) && "why did it get added?"); 684 if (SelectInst *select = dyn_cast<SelectInst>(v)) { 685 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache)); 686 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache)); 687 } else 688 for (Value *Val : cast<PHINode>(v)->incoming_values()) 689 calculateMeet.meetWith(findBaseOrBDV(Val, cache)); 690 691 PhiState oldState = states[v]; 692 PhiState newState = calculateMeet.getResult(); 693 if (oldState != newState) { 694 progress = true; 695 states[v] = newState; 696 } 697 } 698 699 assert(oldSize <= states.size()); 700 assert(oldSize == states.size() || progress); 701 } 702 703 if (TraceLSP) { 704 errs() << "States after meet iteration:\n"; 705 for (auto Pair : states) { 706 Instruction *v = cast<Instruction>(Pair.first); 707 PhiState state = Pair.second; 708 state.dump(); 709 v->dump(); 710 } 711 } 712 713 // Insert Phis for all conflicts 714 // We want to keep naming deterministic in the loop that follows, so 715 // sort the keys before iteration. This is useful in allowing us to 716 // write stable tests. Note that there is no invalidation issue here. 717 SmallVector<Value *, 16> Keys; 718 Keys.reserve(states.size()); 719 for (auto Pair : states) { 720 Value *V = Pair.first; 721 Keys.push_back(V); 722 } 723 std::sort(Keys.begin(), Keys.end(), order_by_name); 724 // TODO: adjust naming patterns to avoid this order of iteration dependency 725 for (Value *V : Keys) { 726 Instruction *v = cast<Instruction>(V); 727 PhiState state = states[V]; 728 assert(!isKnownBaseResult(v) && "why did it get added?"); 729 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!"); 730 if (!state.isConflict()) 731 continue; 732 733 if (isa<PHINode>(v)) { 734 int num_preds = 735 std::distance(pred_begin(v->getParent()), pred_end(v->getParent())); 736 assert(num_preds > 0 && "how did we reach here"); 737 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v); 738 NewInsertedDefs.insert(phi); 739 // Add metadata marking this as a base value 740 auto *const_1 = ConstantInt::get( 741 Type::getInt32Ty( 742 v->getParent()->getParent()->getParent()->getContext()), 743 1); 744 auto MDConst = ConstantAsMetadata::get(const_1); 745 MDNode *md = MDNode::get( 746 v->getParent()->getParent()->getParent()->getContext(), MDConst); 747 phi->setMetadata("is_base_value", md); 748 states[v] = PhiState(PhiState::Conflict, phi); 749 } else { 750 SelectInst *sel = cast<SelectInst>(v); 751 // The undef will be replaced later 752 UndefValue *undef = UndefValue::get(sel->getType()); 753 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef, 754 undef, "base_select", sel); 755 NewInsertedDefs.insert(basesel); 756 // Add metadata marking this as a base value 757 auto *const_1 = ConstantInt::get( 758 Type::getInt32Ty( 759 v->getParent()->getParent()->getParent()->getContext()), 760 1); 761 auto MDConst = ConstantAsMetadata::get(const_1); 762 MDNode *md = MDNode::get( 763 v->getParent()->getParent()->getParent()->getContext(), MDConst); 764 basesel->setMetadata("is_base_value", md); 765 states[v] = PhiState(PhiState::Conflict, basesel); 766 } 767 } 768 769 // Fixup all the inputs of the new PHIs 770 for (auto Pair : states) { 771 Instruction *v = cast<Instruction>(Pair.first); 772 PhiState state = Pair.second; 773 774 assert(!isKnownBaseResult(v) && "why did it get added?"); 775 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!"); 776 if (!state.isConflict()) 777 continue; 778 779 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) { 780 PHINode *phi = cast<PHINode>(v); 781 unsigned NumPHIValues = phi->getNumIncomingValues(); 782 for (unsigned i = 0; i < NumPHIValues; i++) { 783 Value *InVal = phi->getIncomingValue(i); 784 BasicBlock *InBB = phi->getIncomingBlock(i); 785 786 // If we've already seen InBB, add the same incoming value 787 // we added for it earlier. The IR verifier requires phi 788 // nodes with multiple entries from the same basic block 789 // to have the same incoming value for each of those 790 // entries. If we don't do this check here and basephi 791 // has a different type than base, we'll end up adding two 792 // bitcasts (and hence two distinct values) as incoming 793 // values for the same basic block. 794 795 int blockIndex = basephi->getBasicBlockIndex(InBB); 796 if (blockIndex != -1) { 797 Value *oldBase = basephi->getIncomingValue(blockIndex); 798 basephi->addIncoming(oldBase, InBB); 799 #ifndef NDEBUG 800 Value *base = findBaseOrBDV(InVal, cache); 801 if (!isKnownBaseResult(base)) { 802 // Either conflict or base. 803 assert(states.count(base)); 804 base = states[base].getBase(); 805 assert(base != nullptr && "unknown PhiState!"); 806 assert(NewInsertedDefs.count(base) && 807 "should have already added this in a prev. iteration!"); 808 } 809 810 // In essense this assert states: the only way two 811 // values incoming from the same basic block may be 812 // different is by being different bitcasts of the same 813 // value. A cleanup that remains TODO is changing 814 // findBaseOrBDV to return an llvm::Value of the correct 815 // type (and still remain pure). This will remove the 816 // need to add bitcasts. 817 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() && 818 "sanity -- findBaseOrBDV should be pure!"); 819 #endif 820 continue; 821 } 822 823 // Find either the defining value for the PHI or the normal base for 824 // a non-phi node 825 Value *base = findBaseOrBDV(InVal, cache); 826 if (!isKnownBaseResult(base)) { 827 // Either conflict or base. 828 assert(states.count(base)); 829 base = states[base].getBase(); 830 assert(base != nullptr && "unknown PhiState!"); 831 } 832 assert(base && "can't be null"); 833 // Must use original input BB since base may not be Instruction 834 // The cast is needed since base traversal may strip away bitcasts 835 if (base->getType() != basephi->getType()) { 836 base = new BitCastInst(base, basephi->getType(), "cast", 837 InBB->getTerminator()); 838 NewInsertedDefs.insert(base); 839 } 840 basephi->addIncoming(base, InBB); 841 } 842 assert(basephi->getNumIncomingValues() == NumPHIValues); 843 } else { 844 SelectInst *basesel = cast<SelectInst>(state.getBase()); 845 SelectInst *sel = cast<SelectInst>(v); 846 // Operand 1 & 2 are true, false path respectively. TODO: refactor to 847 // something more safe and less hacky. 848 for (int i = 1; i <= 2; i++) { 849 Value *InVal = sel->getOperand(i); 850 // Find either the defining value for the PHI or the normal base for 851 // a non-phi node 852 Value *base = findBaseOrBDV(InVal, cache); 853 if (!isKnownBaseResult(base)) { 854 // Either conflict or base. 855 assert(states.count(base)); 856 base = states[base].getBase(); 857 assert(base != nullptr && "unknown PhiState!"); 858 } 859 assert(base && "can't be null"); 860 // Must use original input BB since base may not be Instruction 861 // The cast is needed since base traversal may strip away bitcasts 862 if (base->getType() != basesel->getType()) { 863 base = new BitCastInst(base, basesel->getType(), "cast", basesel); 864 NewInsertedDefs.insert(base); 865 } 866 basesel->setOperand(i, base); 867 } 868 } 869 } 870 871 // Cache all of our results so we can cheaply reuse them 872 // NOTE: This is actually two caches: one of the base defining value 873 // relation and one of the base pointer relation! FIXME 874 for (auto item : states) { 875 Value *v = item.first; 876 Value *base = item.second.getBase(); 877 assert(v && base); 878 assert(!isKnownBaseResult(v) && "why did it get added?"); 879 880 if (TraceLSP) { 881 std::string fromstr = 882 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "") 883 : "none"; 884 errs() << "Updating base value cache" 885 << " for: " << (v->hasName() ? v->getName() : "") 886 << " from: " << fromstr 887 << " to: " << (base->hasName() ? base->getName() : "") << "\n"; 888 } 889 890 assert(isKnownBaseResult(base) && 891 "must be something we 'know' is a base pointer"); 892 if (cache.count(v)) { 893 // Once we transition from the BDV relation being store in the cache to 894 // the base relation being stored, it must be stable 895 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) && 896 "base relation should be stable"); 897 } 898 cache[v] = base; 899 } 900 assert(cache.find(def) != cache.end()); 901 return cache[def]; 902 } 903 904 // For a set of live pointers (base and/or derived), identify the base 905 // pointer of the object which they are derived from. This routine will 906 // mutate the IR graph as needed to make the 'base' pointer live at the 907 // definition site of 'derived'. This ensures that any use of 'derived' can 908 // also use 'base'. This may involve the insertion of a number of 909 // additional PHI nodes. 910 // 911 // preconditions: live is a set of pointer type Values 912 // 913 // side effects: may insert PHI nodes into the existing CFG, will preserve 914 // CFG, will not remove or mutate any existing nodes 915 // 916 // post condition: PointerToBase contains one (derived, base) pair for every 917 // pointer in live. Note that derived can be equal to base if the original 918 // pointer was a base pointer. 919 static void 920 findBasePointers(const StatepointLiveSetTy &live, 921 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase, 922 DominatorTree *DT, DefiningValueMapTy &DVCache, 923 DenseSet<llvm::Value *> &NewInsertedDefs) { 924 // For the naming of values inserted to be deterministic - which makes for 925 // much cleaner and more stable tests - we need to assign an order to the 926 // live values. DenseSets do not provide a deterministic order across runs. 927 SmallVector<Value *, 64> Temp; 928 Temp.insert(Temp.end(), live.begin(), live.end()); 929 std::sort(Temp.begin(), Temp.end(), order_by_name); 930 for (Value *ptr : Temp) { 931 Value *base = findBasePointer(ptr, DVCache, NewInsertedDefs); 932 assert(base && "failed to find base pointer"); 933 PointerToBase[ptr] = base; 934 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) || 935 DT->dominates(cast<Instruction>(base)->getParent(), 936 cast<Instruction>(ptr)->getParent())) && 937 "The base we found better dominate the derived pointer"); 938 939 // If you see this trip and like to live really dangerously, the code should 940 // be correct, just with idioms the verifier can't handle. You can try 941 // disabling the verifier at your own substaintial risk. 942 assert(!isa<ConstantPointerNull>(base) && 943 "the relocation code needs adjustment to handle the relocation of " 944 "a null pointer constant without causing false positives in the " 945 "safepoint ir verifier."); 946 } 947 } 948 949 /// Find the required based pointers (and adjust the live set) for the given 950 /// parse point. 951 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache, 952 const CallSite &CS, 953 PartiallyConstructedSafepointRecord &result) { 954 DenseMap<llvm::Value *, llvm::Value *> PointerToBase; 955 DenseSet<llvm::Value *> NewInsertedDefs; 956 findBasePointers(result.liveset, PointerToBase, &DT, DVCache, 957 NewInsertedDefs); 958 959 if (PrintBasePointers) { 960 // Note: Need to print these in a stable order since this is checked in 961 // some tests. 962 errs() << "Base Pairs (w/o Relocation):\n"; 963 SmallVector<Value *, 64> Temp; 964 Temp.reserve(PointerToBase.size()); 965 for (auto Pair : PointerToBase) { 966 Temp.push_back(Pair.first); 967 } 968 std::sort(Temp.begin(), Temp.end(), order_by_name); 969 for (Value *Ptr : Temp) { 970 Value *Base = PointerToBase[Ptr]; 971 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName() 972 << "\n"; 973 } 974 } 975 976 result.PointerToBase = PointerToBase; 977 result.NewInsertedDefs = NewInsertedDefs; 978 } 979 980 /// Given an updated version of the dataflow liveness results, update the 981 /// liveset and base pointer maps for the call site CS. 982 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData, 983 const CallSite &CS, 984 PartiallyConstructedSafepointRecord &result); 985 986 static void recomputeLiveInValues( 987 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate, 988 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) { 989 // TODO-PERF: reuse the original liveness, then simply run the dataflow 990 // again. The old values are still live and will help it stablize quickly. 991 GCPtrLivenessData RevisedLivenessData; 992 computeLiveInValues(DT, F, RevisedLivenessData); 993 for (size_t i = 0; i < records.size(); i++) { 994 struct PartiallyConstructedSafepointRecord &info = records[i]; 995 const CallSite &CS = toUpdate[i]; 996 recomputeLiveInValues(RevisedLivenessData, CS, info); 997 } 998 } 999 1000 // When inserting gc.relocate calls, we need to ensure there are no uses 1001 // of the original value between the gc.statepoint and the gc.relocate call. 1002 // One case which can arise is a phi node starting one of the successor blocks. 1003 // We also need to be able to insert the gc.relocates only on the path which 1004 // goes through the statepoint. We might need to split an edge to make this 1005 // possible. 1006 static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB, 1007 BasicBlock *InvokeParent, 1008 Pass *P) { 1009 DominatorTree *DT = nullptr; 1010 if (auto *DTP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) 1011 DT = &DTP->getDomTree(); 1012 1013 BasicBlock *Ret = BB; 1014 if (!BB->getUniquePredecessor()) { 1015 Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, DT); 1016 } 1017 1018 // Now that 'ret' has unique predecessor we can safely remove all phi nodes 1019 // from it 1020 FoldSingleEntryPHINodes(Ret); 1021 assert(!isa<PHINode>(Ret->begin())); 1022 1023 // At this point, we can safely insert a gc.relocate as the first instruction 1024 // in Ret if needed. 1025 return Ret; 1026 } 1027 1028 static int find_index(ArrayRef<Value *> livevec, Value *val) { 1029 auto itr = std::find(livevec.begin(), livevec.end(), val); 1030 assert(livevec.end() != itr); 1031 size_t index = std::distance(livevec.begin(), itr); 1032 assert(index < livevec.size()); 1033 return index; 1034 } 1035 1036 // Create new attribute set containing only attributes which can be transfered 1037 // from original call to the safepoint. 1038 static AttributeSet legalizeCallAttributes(AttributeSet AS) { 1039 AttributeSet ret; 1040 1041 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) { 1042 unsigned index = AS.getSlotIndex(Slot); 1043 1044 if (index == AttributeSet::ReturnIndex || 1045 index == AttributeSet::FunctionIndex) { 1046 1047 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end; 1048 ++it) { 1049 Attribute attr = *it; 1050 1051 // Do not allow certain attributes - just skip them 1052 // Safepoint can not be read only or read none. 1053 if (attr.hasAttribute(Attribute::ReadNone) || 1054 attr.hasAttribute(Attribute::ReadOnly)) 1055 continue; 1056 1057 ret = ret.addAttributes( 1058 AS.getContext(), index, 1059 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr))); 1060 } 1061 } 1062 1063 // Just skip parameter attributes for now 1064 } 1065 1066 return ret; 1067 } 1068 1069 /// Helper function to place all gc relocates necessary for the given 1070 /// statepoint. 1071 /// Inputs: 1072 /// liveVariables - list of variables to be relocated. 1073 /// liveStart - index of the first live variable. 1074 /// basePtrs - base pointers. 1075 /// statepointToken - statepoint instruction to which relocates should be 1076 /// bound. 1077 /// Builder - Llvm IR builder to be used to construct new calls. 1078 static void CreateGCRelocates(ArrayRef<llvm::Value *> liveVariables, 1079 const int liveStart, 1080 ArrayRef<llvm::Value *> basePtrs, 1081 Instruction *statepointToken, 1082 IRBuilder<> Builder) { 1083 SmallVector<Instruction *, 64> NewDefs; 1084 NewDefs.reserve(liveVariables.size()); 1085 1086 Module *M = statepointToken->getParent()->getParent()->getParent(); 1087 1088 for (unsigned i = 0; i < liveVariables.size(); i++) { 1089 // We generate a (potentially) unique declaration for every pointer type 1090 // combination. This results is some blow up the function declarations in 1091 // the IR, but removes the need for argument bitcasts which shrinks the IR 1092 // greatly and makes it much more readable. 1093 SmallVector<Type *, 1> types; // one per 'any' type 1094 types.push_back(liveVariables[i]->getType()); // result type 1095 Value *gc_relocate_decl = Intrinsic::getDeclaration( 1096 M, Intrinsic::experimental_gc_relocate, types); 1097 1098 // Generate the gc.relocate call and save the result 1099 Value *baseIdx = 1100 ConstantInt::get(Type::getInt32Ty(M->getContext()), 1101 liveStart + find_index(liveVariables, basePtrs[i])); 1102 Value *liveIdx = ConstantInt::get( 1103 Type::getInt32Ty(M->getContext()), 1104 liveStart + find_index(liveVariables, liveVariables[i])); 1105 1106 // only specify a debug name if we can give a useful one 1107 Value *reloc = Builder.CreateCall3( 1108 gc_relocate_decl, statepointToken, baseIdx, liveIdx, 1109 liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated" 1110 : ""); 1111 // Trick CodeGen into thinking there are lots of free registers at this 1112 // fake call. 1113 cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold); 1114 1115 NewDefs.push_back(cast<Instruction>(reloc)); 1116 } 1117 assert(NewDefs.size() == liveVariables.size() && 1118 "missing or extra redefinition at safepoint"); 1119 } 1120 1121 static void 1122 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */ 1123 const SmallVectorImpl<llvm::Value *> &basePtrs, 1124 const SmallVectorImpl<llvm::Value *> &liveVariables, 1125 Pass *P, 1126 PartiallyConstructedSafepointRecord &result) { 1127 assert(basePtrs.size() == liveVariables.size()); 1128 assert(isStatepoint(CS) && 1129 "This method expects to be rewriting a statepoint"); 1130 1131 BasicBlock *BB = CS.getInstruction()->getParent(); 1132 assert(BB); 1133 Function *F = BB->getParent(); 1134 assert(F && "must be set"); 1135 Module *M = F->getParent(); 1136 (void)M; 1137 assert(M && "must be set"); 1138 1139 // We're not changing the function signature of the statepoint since the gc 1140 // arguments go into the var args section. 1141 Function *gc_statepoint_decl = CS.getCalledFunction(); 1142 1143 // Then go ahead and use the builder do actually do the inserts. We insert 1144 // immediately before the previous instruction under the assumption that all 1145 // arguments will be available here. We can't insert afterwards since we may 1146 // be replacing a terminator. 1147 Instruction *insertBefore = CS.getInstruction(); 1148 IRBuilder<> Builder(insertBefore); 1149 // Copy all of the arguments from the original statepoint - this includes the 1150 // target, call args, and deopt args 1151 SmallVector<llvm::Value *, 64> args; 1152 args.insert(args.end(), CS.arg_begin(), CS.arg_end()); 1153 // TODO: Clear the 'needs rewrite' flag 1154 1155 // add all the pointers to be relocated (gc arguments) 1156 // Capture the start of the live variable list for use in the gc_relocates 1157 const int live_start = args.size(); 1158 args.insert(args.end(), liveVariables.begin(), liveVariables.end()); 1159 1160 // Create the statepoint given all the arguments 1161 Instruction *token = nullptr; 1162 AttributeSet return_attributes; 1163 if (CS.isCall()) { 1164 CallInst *toReplace = cast<CallInst>(CS.getInstruction()); 1165 CallInst *call = 1166 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token"); 1167 call->setTailCall(toReplace->isTailCall()); 1168 call->setCallingConv(toReplace->getCallingConv()); 1169 1170 // Currently we will fail on parameter attributes and on certain 1171 // function attributes. 1172 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes()); 1173 // In case if we can handle this set of sttributes - set up function attrs 1174 // directly on statepoint and return attrs later for gc_result intrinsic. 1175 call->setAttributes(new_attrs.getFnAttributes()); 1176 return_attributes = new_attrs.getRetAttributes(); 1177 1178 token = call; 1179 1180 // Put the following gc_result and gc_relocate calls immediately after the 1181 // the old call (which we're about to delete) 1182 BasicBlock::iterator next(toReplace); 1183 assert(BB->end() != next && "not a terminator, must have next"); 1184 next++; 1185 Instruction *IP = &*(next); 1186 Builder.SetInsertPoint(IP); 1187 Builder.SetCurrentDebugLocation(IP->getDebugLoc()); 1188 1189 } else { 1190 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction()); 1191 1192 // Insert the new invoke into the old block. We'll remove the old one in a 1193 // moment at which point this will become the new terminator for the 1194 // original block. 1195 InvokeInst *invoke = InvokeInst::Create( 1196 gc_statepoint_decl, toReplace->getNormalDest(), 1197 toReplace->getUnwindDest(), args, "", toReplace->getParent()); 1198 invoke->setCallingConv(toReplace->getCallingConv()); 1199 1200 // Currently we will fail on parameter attributes and on certain 1201 // function attributes. 1202 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes()); 1203 // In case if we can handle this set of sttributes - set up function attrs 1204 // directly on statepoint and return attrs later for gc_result intrinsic. 1205 invoke->setAttributes(new_attrs.getFnAttributes()); 1206 return_attributes = new_attrs.getRetAttributes(); 1207 1208 token = invoke; 1209 1210 // Generate gc relocates in exceptional path 1211 BasicBlock *unwindBlock = toReplace->getUnwindDest(); 1212 assert(!isa<PHINode>(unwindBlock->begin()) && 1213 unwindBlock->getUniquePredecessor() && 1214 "can't safely insert in this block!"); 1215 1216 Instruction *IP = &*(unwindBlock->getFirstInsertionPt()); 1217 Builder.SetInsertPoint(IP); 1218 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc()); 1219 1220 // Extract second element from landingpad return value. We will attach 1221 // exceptional gc relocates to it. 1222 const unsigned idx = 1; 1223 Instruction *exceptional_token = 1224 cast<Instruction>(Builder.CreateExtractValue( 1225 unwindBlock->getLandingPadInst(), idx, "relocate_token")); 1226 result.UnwindToken = exceptional_token; 1227 1228 // Just throw away return value. We will use the one we got for normal 1229 // block. 1230 (void)CreateGCRelocates(liveVariables, live_start, basePtrs, 1231 exceptional_token, Builder); 1232 1233 // Generate gc relocates and returns for normal block 1234 BasicBlock *normalDest = toReplace->getNormalDest(); 1235 assert(!isa<PHINode>(normalDest->begin()) && 1236 normalDest->getUniquePredecessor() && 1237 "can't safely insert in this block!"); 1238 1239 IP = &*(normalDest->getFirstInsertionPt()); 1240 Builder.SetInsertPoint(IP); 1241 1242 // gc relocates will be generated later as if it were regular call 1243 // statepoint 1244 } 1245 assert(token); 1246 1247 // Take the name of the original value call if it had one. 1248 token->takeName(CS.getInstruction()); 1249 1250 // The GCResult is already inserted, we just need to find it 1251 #ifndef NDEBUG 1252 Instruction *toReplace = CS.getInstruction(); 1253 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) && 1254 "only valid use before rewrite is gc.result"); 1255 assert(!toReplace->hasOneUse() || 1256 isGCResult(cast<Instruction>(*toReplace->user_begin()))); 1257 #endif 1258 1259 // Update the gc.result of the original statepoint (if any) to use the newly 1260 // inserted statepoint. This is safe to do here since the token can't be 1261 // considered a live reference. 1262 CS.getInstruction()->replaceAllUsesWith(token); 1263 1264 result.StatepointToken = token; 1265 1266 // Second, create a gc.relocate for every live variable 1267 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder); 1268 } 1269 1270 namespace { 1271 struct name_ordering { 1272 Value *base; 1273 Value *derived; 1274 bool operator()(name_ordering const &a, name_ordering const &b) { 1275 return -1 == a.derived->getName().compare(b.derived->getName()); 1276 } 1277 }; 1278 } 1279 static void stablize_order(SmallVectorImpl<Value *> &basevec, 1280 SmallVectorImpl<Value *> &livevec) { 1281 assert(basevec.size() == livevec.size()); 1282 1283 SmallVector<name_ordering, 64> temp; 1284 for (size_t i = 0; i < basevec.size(); i++) { 1285 name_ordering v; 1286 v.base = basevec[i]; 1287 v.derived = livevec[i]; 1288 temp.push_back(v); 1289 } 1290 std::sort(temp.begin(), temp.end(), name_ordering()); 1291 for (size_t i = 0; i < basevec.size(); i++) { 1292 basevec[i] = temp[i].base; 1293 livevec[i] = temp[i].derived; 1294 } 1295 } 1296 1297 // Replace an existing gc.statepoint with a new one and a set of gc.relocates 1298 // which make the relocations happening at this safepoint explicit. 1299 // 1300 // WARNING: Does not do any fixup to adjust users of the original live 1301 // values. That's the callers responsibility. 1302 static void 1303 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P, 1304 PartiallyConstructedSafepointRecord &result) { 1305 auto liveset = result.liveset; 1306 auto PointerToBase = result.PointerToBase; 1307 1308 // Convert to vector for efficient cross referencing. 1309 SmallVector<Value *, 64> basevec, livevec; 1310 livevec.reserve(liveset.size()); 1311 basevec.reserve(liveset.size()); 1312 for (Value *L : liveset) { 1313 livevec.push_back(L); 1314 1315 assert(PointerToBase.find(L) != PointerToBase.end()); 1316 Value *base = PointerToBase[L]; 1317 basevec.push_back(base); 1318 } 1319 assert(livevec.size() == basevec.size()); 1320 1321 // To make the output IR slightly more stable (for use in diffs), ensure a 1322 // fixed order of the values in the safepoint (by sorting the value name). 1323 // The order is otherwise meaningless. 1324 stablize_order(basevec, livevec); 1325 1326 // Do the actual rewriting and delete the old statepoint 1327 makeStatepointExplicitImpl(CS, basevec, livevec, P, result); 1328 CS.getInstruction()->eraseFromParent(); 1329 } 1330 1331 // Helper function for the relocationViaAlloca. 1332 // It receives iterator to the statepoint gc relocates and emits store to the 1333 // assigned 1334 // location (via allocaMap) for the each one of them. 1335 // Add visited values into the visitedLiveValues set we will later use them 1336 // for sanity check. 1337 static void 1338 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs, 1339 DenseMap<Value *, Value *> &allocaMap, 1340 DenseSet<Value *> &visitedLiveValues) { 1341 1342 for (User *U : gcRelocs) { 1343 if (!isa<IntrinsicInst>(U)) 1344 continue; 1345 1346 IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U); 1347 1348 // We only care about relocates 1349 if (relocatedValue->getIntrinsicID() != 1350 Intrinsic::experimental_gc_relocate) { 1351 continue; 1352 } 1353 1354 GCRelocateOperands relocateOperands(relocatedValue); 1355 Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr()); 1356 assert(allocaMap.count(originalValue)); 1357 Value *alloca = allocaMap[originalValue]; 1358 1359 // Emit store into the related alloca 1360 StoreInst *store = new StoreInst(relocatedValue, alloca); 1361 store->insertAfter(relocatedValue); 1362 1363 #ifndef NDEBUG 1364 visitedLiveValues.insert(originalValue); 1365 #endif 1366 } 1367 } 1368 1369 /// do all the relocation update via allocas and mem2reg 1370 static void relocationViaAlloca( 1371 Function &F, DominatorTree &DT, ArrayRef<Value *> live, 1372 ArrayRef<struct PartiallyConstructedSafepointRecord> records) { 1373 #ifndef NDEBUG 1374 // record initial number of (static) allocas; we'll check we have the same 1375 // number when we get done. 1376 int InitialAllocaNum = 0; 1377 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E; 1378 I++) 1379 if (isa<AllocaInst>(*I)) 1380 InitialAllocaNum++; 1381 #endif 1382 1383 // TODO-PERF: change data structures, reserve 1384 DenseMap<Value *, Value *> allocaMap; 1385 SmallVector<AllocaInst *, 200> PromotableAllocas; 1386 PromotableAllocas.reserve(live.size()); 1387 1388 // emit alloca for each live gc pointer 1389 for (unsigned i = 0; i < live.size(); i++) { 1390 Value *liveValue = live[i]; 1391 AllocaInst *alloca = new AllocaInst(liveValue->getType(), "", 1392 F.getEntryBlock().getFirstNonPHI()); 1393 allocaMap[liveValue] = alloca; 1394 PromotableAllocas.push_back(alloca); 1395 } 1396 1397 // The next two loops are part of the same conceptual operation. We need to 1398 // insert a store to the alloca after the original def and at each 1399 // redefinition. We need to insert a load before each use. These are split 1400 // into distinct loops for performance reasons. 1401 1402 // update gc pointer after each statepoint 1403 // either store a relocated value or null (if no relocated value found for 1404 // this gc pointer and it is not a gc_result) 1405 // this must happen before we update the statepoint with load of alloca 1406 // otherwise we lose the link between statepoint and old def 1407 for (size_t i = 0; i < records.size(); i++) { 1408 const struct PartiallyConstructedSafepointRecord &info = records[i]; 1409 Value *Statepoint = info.StatepointToken; 1410 1411 // This will be used for consistency check 1412 DenseSet<Value *> visitedLiveValues; 1413 1414 // Insert stores for normal statepoint gc relocates 1415 insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues); 1416 1417 // In case if it was invoke statepoint 1418 // we will insert stores for exceptional path gc relocates. 1419 if (isa<InvokeInst>(Statepoint)) { 1420 insertRelocationStores(info.UnwindToken->users(), allocaMap, 1421 visitedLiveValues); 1422 } 1423 1424 if (ClobberNonLive) { 1425 // As a debuging aid, pretend that an unrelocated pointer becomes null at 1426 // the gc.statepoint. This will turn some subtle GC problems into 1427 // slightly easier to debug SEGVs. Note that on large IR files with 1428 // lots of gc.statepoints this is extremely costly both memory and time 1429 // wise. 1430 SmallVector<AllocaInst *, 64> ToClobber; 1431 for (auto Pair : allocaMap) { 1432 Value *Def = Pair.first; 1433 AllocaInst *Alloca = cast<AllocaInst>(Pair.second); 1434 1435 // This value was relocated 1436 if (visitedLiveValues.count(Def)) { 1437 continue; 1438 } 1439 ToClobber.push_back(Alloca); 1440 } 1441 1442 auto InsertClobbersAt = [&](Instruction *IP) { 1443 for (auto *AI : ToClobber) { 1444 auto AIType = cast<PointerType>(AI->getType()); 1445 auto PT = cast<PointerType>(AIType->getElementType()); 1446 Constant *CPN = ConstantPointerNull::get(PT); 1447 StoreInst *store = new StoreInst(CPN, AI); 1448 store->insertBefore(IP); 1449 } 1450 }; 1451 1452 // Insert the clobbering stores. These may get intermixed with the 1453 // gc.results and gc.relocates, but that's fine. 1454 if (auto II = dyn_cast<InvokeInst>(Statepoint)) { 1455 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt()); 1456 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt()); 1457 } else { 1458 BasicBlock::iterator Next(cast<CallInst>(Statepoint)); 1459 Next++; 1460 InsertClobbersAt(Next); 1461 } 1462 } 1463 } 1464 // update use with load allocas and add store for gc_relocated 1465 for (auto Pair : allocaMap) { 1466 Value *def = Pair.first; 1467 Value *alloca = Pair.second; 1468 1469 // we pre-record the uses of allocas so that we dont have to worry about 1470 // later update 1471 // that change the user information. 1472 SmallVector<Instruction *, 20> uses; 1473 // PERF: trade a linear scan for repeated reallocation 1474 uses.reserve(std::distance(def->user_begin(), def->user_end())); 1475 for (User *U : def->users()) { 1476 if (!isa<ConstantExpr>(U)) { 1477 // If the def has a ConstantExpr use, then the def is either a 1478 // ConstantExpr use itself or null. In either case 1479 // (recursively in the first, directly in the second), the oop 1480 // it is ultimately dependent on is null and this particular 1481 // use does not need to be fixed up. 1482 uses.push_back(cast<Instruction>(U)); 1483 } 1484 } 1485 1486 std::sort(uses.begin(), uses.end()); 1487 auto last = std::unique(uses.begin(), uses.end()); 1488 uses.erase(last, uses.end()); 1489 1490 for (Instruction *use : uses) { 1491 if (isa<PHINode>(use)) { 1492 PHINode *phi = cast<PHINode>(use); 1493 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) { 1494 if (def == phi->getIncomingValue(i)) { 1495 LoadInst *load = new LoadInst( 1496 alloca, "", phi->getIncomingBlock(i)->getTerminator()); 1497 phi->setIncomingValue(i, load); 1498 } 1499 } 1500 } else { 1501 LoadInst *load = new LoadInst(alloca, "", use); 1502 use->replaceUsesOfWith(def, load); 1503 } 1504 } 1505 1506 // emit store for the initial gc value 1507 // store must be inserted after load, otherwise store will be in alloca's 1508 // use list and an extra load will be inserted before it 1509 StoreInst *store = new StoreInst(def, alloca); 1510 if (Instruction *inst = dyn_cast<Instruction>(def)) { 1511 if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) { 1512 // InvokeInst is a TerminatorInst so the store need to be inserted 1513 // into its normal destination block. 1514 BasicBlock *normalDest = invoke->getNormalDest(); 1515 store->insertBefore(normalDest->getFirstNonPHI()); 1516 } else { 1517 assert(!inst->isTerminator() && 1518 "The only TerminatorInst that can produce a value is " 1519 "InvokeInst which is handled above."); 1520 store->insertAfter(inst); 1521 } 1522 } else { 1523 assert((isa<Argument>(def) || isa<GlobalVariable>(def) || 1524 isa<ConstantPointerNull>(def)) && 1525 "Must be argument or global"); 1526 store->insertAfter(cast<Instruction>(alloca)); 1527 } 1528 } 1529 1530 assert(PromotableAllocas.size() == live.size() && 1531 "we must have the same allocas with lives"); 1532 if (!PromotableAllocas.empty()) { 1533 // apply mem2reg to promote alloca to SSA 1534 PromoteMemToReg(PromotableAllocas, DT); 1535 } 1536 1537 #ifndef NDEBUG 1538 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E; 1539 I++) 1540 if (isa<AllocaInst>(*I)) 1541 InitialAllocaNum--; 1542 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas"); 1543 #endif 1544 } 1545 1546 /// Implement a unique function which doesn't require we sort the input 1547 /// vector. Doing so has the effect of changing the output of a couple of 1548 /// tests in ways which make them less useful in testing fused safepoints. 1549 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) { 1550 DenseSet<T> Seen; 1551 SmallVector<T, 128> TempVec; 1552 TempVec.reserve(Vec.size()); 1553 for (auto Element : Vec) 1554 TempVec.push_back(Element); 1555 Vec.clear(); 1556 for (auto V : TempVec) { 1557 if (Seen.insert(V).second) { 1558 Vec.push_back(V); 1559 } 1560 } 1561 } 1562 1563 static Function *getUseHolder(Module &M) { 1564 FunctionType *ftype = 1565 FunctionType::get(Type::getVoidTy(M.getContext()), true); 1566 Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype)); 1567 return Func; 1568 } 1569 1570 /// Insert holders so that each Value is obviously live through the entire 1571 /// liftetime of the call. 1572 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values, 1573 SmallVectorImpl<CallInst *> &holders) { 1574 Module *M = CS.getInstruction()->getParent()->getParent()->getParent(); 1575 Function *Func = getUseHolder(*M); 1576 if (CS.isCall()) { 1577 // For call safepoints insert dummy calls right after safepoint 1578 BasicBlock::iterator next(CS.getInstruction()); 1579 next++; 1580 CallInst *base_holder = CallInst::Create(Func, Values, "", next); 1581 holders.push_back(base_holder); 1582 } else if (CS.isInvoke()) { 1583 // For invoke safepooints insert dummy calls both in normal and 1584 // exceptional destination blocks 1585 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction()); 1586 CallInst *normal_holder = CallInst::Create( 1587 Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt()); 1588 CallInst *unwind_holder = CallInst::Create( 1589 Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt()); 1590 holders.push_back(normal_holder); 1591 holders.push_back(unwind_holder); 1592 } else 1593 llvm_unreachable("unsupported call type"); 1594 } 1595 1596 static void findLiveReferences( 1597 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate, 1598 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) { 1599 GCPtrLivenessData OriginalLivenessData; 1600 computeLiveInValues(DT, F, OriginalLivenessData); 1601 for (size_t i = 0; i < records.size(); i++) { 1602 struct PartiallyConstructedSafepointRecord &info = records[i]; 1603 const CallSite &CS = toUpdate[i]; 1604 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info); 1605 } 1606 } 1607 1608 /// Remove any vector of pointers from the liveset by scalarizing them over the 1609 /// statepoint instruction. Adds the scalarized pieces to the liveset. It 1610 /// would be preferrable to include the vector in the statepoint itself, but 1611 /// the lowering code currently does not handle that. Extending it would be 1612 /// slightly non-trivial since it requires a format change. Given how rare 1613 /// such cases are (for the moment?) scalarizing is an acceptable comprimise. 1614 static void splitVectorValues(Instruction *StatepointInst, 1615 StatepointLiveSetTy &LiveSet, DominatorTree &DT) { 1616 SmallVector<Value *, 16> ToSplit; 1617 for (Value *V : LiveSet) 1618 if (isa<VectorType>(V->getType())) 1619 ToSplit.push_back(V); 1620 1621 if (ToSplit.empty()) 1622 return; 1623 1624 Function &F = *(StatepointInst->getParent()->getParent()); 1625 1626 DenseMap<Value *, AllocaInst *> AllocaMap; 1627 // First is normal return, second is exceptional return (invoke only) 1628 DenseMap<Value *, std::pair<Value *, Value *>> Replacements; 1629 for (Value *V : ToSplit) { 1630 LiveSet.erase(V); 1631 1632 AllocaInst *Alloca = 1633 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI()); 1634 AllocaMap[V] = Alloca; 1635 1636 VectorType *VT = cast<VectorType>(V->getType()); 1637 IRBuilder<> Builder(StatepointInst); 1638 SmallVector<Value *, 16> Elements; 1639 for (unsigned i = 0; i < VT->getNumElements(); i++) 1640 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i))); 1641 LiveSet.insert(Elements.begin(), Elements.end()); 1642 1643 auto InsertVectorReform = [&](Instruction *IP) { 1644 Builder.SetInsertPoint(IP); 1645 Builder.SetCurrentDebugLocation(IP->getDebugLoc()); 1646 Value *ResultVec = UndefValue::get(VT); 1647 for (unsigned i = 0; i < VT->getNumElements(); i++) 1648 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i], 1649 Builder.getInt32(i)); 1650 return ResultVec; 1651 }; 1652 1653 if (isa<CallInst>(StatepointInst)) { 1654 BasicBlock::iterator Next(StatepointInst); 1655 Next++; 1656 Instruction *IP = &*(Next); 1657 Replacements[V].first = InsertVectorReform(IP); 1658 Replacements[V].second = nullptr; 1659 } else { 1660 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst); 1661 // We've already normalized - check that we don't have shared destination 1662 // blocks 1663 BasicBlock *NormalDest = Invoke->getNormalDest(); 1664 assert(!isa<PHINode>(NormalDest->begin())); 1665 BasicBlock *UnwindDest = Invoke->getUnwindDest(); 1666 assert(!isa<PHINode>(UnwindDest->begin())); 1667 // Insert insert element sequences in both successors 1668 Instruction *IP = &*(NormalDest->getFirstInsertionPt()); 1669 Replacements[V].first = InsertVectorReform(IP); 1670 IP = &*(UnwindDest->getFirstInsertionPt()); 1671 Replacements[V].second = InsertVectorReform(IP); 1672 } 1673 } 1674 for (Value *V : ToSplit) { 1675 AllocaInst *Alloca = AllocaMap[V]; 1676 1677 // Capture all users before we start mutating use lists 1678 SmallVector<Instruction *, 16> Users; 1679 for (User *U : V->users()) 1680 Users.push_back(cast<Instruction>(U)); 1681 1682 for (Instruction *I : Users) { 1683 if (auto Phi = dyn_cast<PHINode>(I)) { 1684 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) 1685 if (V == Phi->getIncomingValue(i)) { 1686 LoadInst *Load = new LoadInst( 1687 Alloca, "", Phi->getIncomingBlock(i)->getTerminator()); 1688 Phi->setIncomingValue(i, Load); 1689 } 1690 } else { 1691 LoadInst *Load = new LoadInst(Alloca, "", I); 1692 I->replaceUsesOfWith(V, Load); 1693 } 1694 } 1695 1696 // Store the original value and the replacement value into the alloca 1697 StoreInst *Store = new StoreInst(V, Alloca); 1698 if (auto I = dyn_cast<Instruction>(V)) 1699 Store->insertAfter(I); 1700 else 1701 Store->insertAfter(Alloca); 1702 1703 // Normal return for invoke, or call return 1704 Instruction *Replacement = cast<Instruction>(Replacements[V].first); 1705 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement); 1706 // Unwind return for invoke only 1707 Replacement = cast_or_null<Instruction>(Replacements[V].second); 1708 if (Replacement) 1709 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement); 1710 } 1711 1712 // apply mem2reg to promote alloca to SSA 1713 SmallVector<AllocaInst *, 16> Allocas; 1714 for (Value *V : ToSplit) 1715 Allocas.push_back(AllocaMap[V]); 1716 PromoteMemToReg(Allocas, DT); 1717 } 1718 1719 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P, 1720 SmallVectorImpl<CallSite> &toUpdate) { 1721 #ifndef NDEBUG 1722 // sanity check the input 1723 std::set<CallSite> uniqued; 1724 uniqued.insert(toUpdate.begin(), toUpdate.end()); 1725 assert(uniqued.size() == toUpdate.size() && "no duplicates please!"); 1726 1727 for (size_t i = 0; i < toUpdate.size(); i++) { 1728 CallSite &CS = toUpdate[i]; 1729 assert(CS.getInstruction()->getParent()->getParent() == &F); 1730 assert(isStatepoint(CS) && "expected to already be a deopt statepoint"); 1731 } 1732 #endif 1733 1734 // When inserting gc.relocates for invokes, we need to be able to insert at 1735 // the top of the successor blocks. See the comment on 1736 // normalForInvokeSafepoint on exactly what is needed. Note that this step 1737 // may restructure the CFG. 1738 for (CallSite CS : toUpdate) 1739 if (CS.isInvoke()) { 1740 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction()); 1741 normalizeForInvokeSafepoint(invoke->getNormalDest(), 1742 invoke->getParent(), P); 1743 normalizeForInvokeSafepoint(invoke->getUnwindDest(), 1744 invoke->getParent(), P); 1745 } 1746 1747 // A list of dummy calls added to the IR to keep various values obviously 1748 // live in the IR. We'll remove all of these when done. 1749 SmallVector<CallInst *, 64> holders; 1750 1751 // Insert a dummy call with all of the arguments to the vm_state we'll need 1752 // for the actual safepoint insertion. This ensures reference arguments in 1753 // the deopt argument list are considered live through the safepoint (and 1754 // thus makes sure they get relocated.) 1755 for (size_t i = 0; i < toUpdate.size(); i++) { 1756 CallSite &CS = toUpdate[i]; 1757 Statepoint StatepointCS(CS); 1758 1759 SmallVector<Value *, 64> DeoptValues; 1760 for (Use &U : StatepointCS.vm_state_args()) { 1761 Value *Arg = cast<Value>(&U); 1762 assert(!isUnhandledGCPointerType(Arg->getType()) && 1763 "support for FCA unimplemented"); 1764 if (isHandledGCPointerType(Arg->getType())) 1765 DeoptValues.push_back(Arg); 1766 } 1767 insertUseHolderAfter(CS, DeoptValues, holders); 1768 } 1769 1770 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records; 1771 records.reserve(toUpdate.size()); 1772 for (size_t i = 0; i < toUpdate.size(); i++) { 1773 struct PartiallyConstructedSafepointRecord info; 1774 records.push_back(info); 1775 } 1776 assert(records.size() == toUpdate.size()); 1777 1778 // A) Identify all gc pointers which are staticly live at the given call 1779 // site. 1780 findLiveReferences(F, DT, P, toUpdate, records); 1781 1782 // Do a limited scalarization of any live at safepoint vector values which 1783 // contain pointers. This enables this pass to run after vectorization at 1784 // the cost of some possible performance loss. TODO: it would be nice to 1785 // natively support vectors all the way through the backend so we don't need 1786 // to scalarize here. 1787 for (size_t i = 0; i < records.size(); i++) { 1788 struct PartiallyConstructedSafepointRecord &info = records[i]; 1789 Instruction *statepoint = toUpdate[i].getInstruction(); 1790 splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT); 1791 } 1792 1793 // B) Find the base pointers for each live pointer 1794 /* scope for caching */ { 1795 // Cache the 'defining value' relation used in the computation and 1796 // insertion of base phis and selects. This ensures that we don't insert 1797 // large numbers of duplicate base_phis. 1798 DefiningValueMapTy DVCache; 1799 1800 for (size_t i = 0; i < records.size(); i++) { 1801 struct PartiallyConstructedSafepointRecord &info = records[i]; 1802 CallSite &CS = toUpdate[i]; 1803 findBasePointers(DT, DVCache, CS, info); 1804 } 1805 } // end of cache scope 1806 1807 // The base phi insertion logic (for any safepoint) may have inserted new 1808 // instructions which are now live at some safepoint. The simplest such 1809 // example is: 1810 // loop: 1811 // phi a <-- will be a new base_phi here 1812 // safepoint 1 <-- that needs to be live here 1813 // gep a + 1 1814 // safepoint 2 1815 // br loop 1816 DenseSet<llvm::Value *> allInsertedDefs; 1817 for (size_t i = 0; i < records.size(); i++) { 1818 struct PartiallyConstructedSafepointRecord &info = records[i]; 1819 allInsertedDefs.insert(info.NewInsertedDefs.begin(), 1820 info.NewInsertedDefs.end()); 1821 } 1822 1823 // We insert some dummy calls after each safepoint to definitely hold live 1824 // the base pointers which were identified for that safepoint. We'll then 1825 // ask liveness for _every_ base inserted to see what is now live. Then we 1826 // remove the dummy calls. 1827 holders.reserve(holders.size() + records.size()); 1828 for (size_t i = 0; i < records.size(); i++) { 1829 struct PartiallyConstructedSafepointRecord &info = records[i]; 1830 CallSite &CS = toUpdate[i]; 1831 1832 SmallVector<Value *, 128> Bases; 1833 for (auto Pair : info.PointerToBase) { 1834 Bases.push_back(Pair.second); 1835 } 1836 insertUseHolderAfter(CS, Bases, holders); 1837 } 1838 1839 // By selecting base pointers, we've effectively inserted new uses. Thus, we 1840 // need to rerun liveness. We may *also* have inserted new defs, but that's 1841 // not the key issue. 1842 recomputeLiveInValues(F, DT, P, toUpdate, records); 1843 1844 if (PrintBasePointers) { 1845 for (size_t i = 0; i < records.size(); i++) { 1846 struct PartiallyConstructedSafepointRecord &info = records[i]; 1847 errs() << "Base Pairs: (w/Relocation)\n"; 1848 for (auto Pair : info.PointerToBase) { 1849 errs() << " derived %" << Pair.first->getName() << " base %" 1850 << Pair.second->getName() << "\n"; 1851 } 1852 } 1853 } 1854 for (size_t i = 0; i < holders.size(); i++) { 1855 holders[i]->eraseFromParent(); 1856 holders[i] = nullptr; 1857 } 1858 holders.clear(); 1859 1860 // Now run through and replace the existing statepoints with new ones with 1861 // the live variables listed. We do not yet update uses of the values being 1862 // relocated. We have references to live variables that need to 1863 // survive to the last iteration of this loop. (By construction, the 1864 // previous statepoint can not be a live variable, thus we can and remove 1865 // the old statepoint calls as we go.) 1866 for (size_t i = 0; i < records.size(); i++) { 1867 struct PartiallyConstructedSafepointRecord &info = records[i]; 1868 CallSite &CS = toUpdate[i]; 1869 makeStatepointExplicit(DT, CS, P, info); 1870 } 1871 toUpdate.clear(); // prevent accident use of invalid CallSites 1872 1873 // Do all the fixups of the original live variables to their relocated selves 1874 SmallVector<Value *, 128> live; 1875 for (size_t i = 0; i < records.size(); i++) { 1876 struct PartiallyConstructedSafepointRecord &info = records[i]; 1877 // We can't simply save the live set from the original insertion. One of 1878 // the live values might be the result of a call which needs a safepoint. 1879 // That Value* no longer exists and we need to use the new gc_result. 1880 // Thankfully, the liveset is embedded in the statepoint (and updated), so 1881 // we just grab that. 1882 Statepoint statepoint(info.StatepointToken); 1883 live.insert(live.end(), statepoint.gc_args_begin(), 1884 statepoint.gc_args_end()); 1885 #ifndef NDEBUG 1886 // Do some basic sanity checks on our liveness results before performing 1887 // relocation. Relocation can and will turn mistakes in liveness results 1888 // into non-sensical code which is must harder to debug. 1889 // TODO: It would be nice to test consistency as well 1890 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) && 1891 "statepoint must be reachable or liveness is meaningless"); 1892 for (Value *V : statepoint.gc_args()) { 1893 if (!isa<Instruction>(V)) 1894 // Non-instruction values trivial dominate all possible uses 1895 continue; 1896 auto LiveInst = cast<Instruction>(V); 1897 assert(DT.isReachableFromEntry(LiveInst->getParent()) && 1898 "unreachable values should never be live"); 1899 assert(DT.dominates(LiveInst, info.StatepointToken) && 1900 "basic SSA liveness expectation violated by liveness analysis"); 1901 } 1902 #endif 1903 } 1904 unique_unsorted(live); 1905 1906 #ifndef NDEBUG 1907 // sanity check 1908 for (auto ptr : live) { 1909 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type"); 1910 } 1911 #endif 1912 1913 relocationViaAlloca(F, DT, live, records); 1914 return !records.empty(); 1915 } 1916 1917 /// Returns true if this function should be rewritten by this pass. The main 1918 /// point of this function is as an extension point for custom logic. 1919 static bool shouldRewriteStatepointsIn(Function &F) { 1920 // TODO: This should check the GCStrategy 1921 if (F.hasGC()) { 1922 const std::string StatepointExampleName("statepoint-example"); 1923 return StatepointExampleName == F.getGC(); 1924 } else 1925 return false; 1926 } 1927 1928 bool RewriteStatepointsForGC::runOnFunction(Function &F) { 1929 // Nothing to do for declarations. 1930 if (F.isDeclaration() || F.empty()) 1931 return false; 1932 1933 // Policy choice says not to rewrite - the most common reason is that we're 1934 // compiling code without a GCStrategy. 1935 if (!shouldRewriteStatepointsIn(F)) 1936 return false; 1937 1938 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1939 1940 // Gather all the statepoints which need rewritten. Be careful to only 1941 // consider those in reachable code since we need to ask dominance queries 1942 // when rewriting. We'll delete the unreachable ones in a moment. 1943 SmallVector<CallSite, 64> ParsePointNeeded; 1944 bool HasUnreachableStatepoint = false; 1945 for (Instruction &I : inst_range(F)) { 1946 // TODO: only the ones with the flag set! 1947 if (isStatepoint(I)) { 1948 if (DT.isReachableFromEntry(I.getParent())) 1949 ParsePointNeeded.push_back(CallSite(&I)); 1950 else 1951 HasUnreachableStatepoint = true; 1952 } 1953 } 1954 1955 bool MadeChange = false; 1956 1957 // Delete any unreachable statepoints so that we don't have unrewritten 1958 // statepoints surviving this pass. This makes testing easier and the 1959 // resulting IR less confusing to human readers. Rather than be fancy, we 1960 // just reuse a utility function which removes the unreachable blocks. 1961 if (HasUnreachableStatepoint) 1962 MadeChange |= removeUnreachableBlocks(F); 1963 1964 // Return early if no work to do. 1965 if (ParsePointNeeded.empty()) 1966 return MadeChange; 1967 1968 // As a prepass, go ahead and aggressively destroy single entry phi nodes. 1969 // These are created by LCSSA. They have the effect of increasing the size 1970 // of liveness sets for no good reason. It may be harder to do this post 1971 // insertion since relocations and base phis can confuse things. 1972 for (BasicBlock &BB : F) 1973 if (BB.getUniquePredecessor()) { 1974 MadeChange = true; 1975 FoldSingleEntryPHINodes(&BB); 1976 } 1977 1978 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded); 1979 return MadeChange; 1980 } 1981 1982 // liveness computation via standard dataflow 1983 // ------------------------------------------------------------------- 1984 1985 // TODO: Consider using bitvectors for liveness, the set of potentially 1986 // interesting values should be small and easy to pre-compute. 1987 1988 /// Is this value a constant consisting of entirely null values? 1989 static bool isConstantNull(Value *V) { 1990 return isa<Constant>(V) && cast<Constant>(V)->isNullValue(); 1991 } 1992 1993 /// Compute the live-in set for the location rbegin starting from 1994 /// the live-out set of the basic block 1995 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin, 1996 BasicBlock::reverse_iterator rend, 1997 DenseSet<Value *> &LiveTmp) { 1998 1999 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) { 2000 Instruction *I = &*ritr; 2001 2002 // KILL/Def - Remove this definition from LiveIn 2003 LiveTmp.erase(I); 2004 2005 // Don't consider *uses* in PHI nodes, we handle their contribution to 2006 // predecessor blocks when we seed the LiveOut sets 2007 if (isa<PHINode>(I)) 2008 continue; 2009 2010 // USE - Add to the LiveIn set for this instruction 2011 for (Value *V : I->operands()) { 2012 assert(!isUnhandledGCPointerType(V->getType()) && 2013 "support for FCA unimplemented"); 2014 if (isHandledGCPointerType(V->getType()) && !isConstantNull(V) && 2015 !isa<UndefValue>(V)) { 2016 // The choice to exclude null and undef is arbitrary here. Reconsider? 2017 LiveTmp.insert(V); 2018 } 2019 } 2020 } 2021 } 2022 2023 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) { 2024 2025 for (BasicBlock *Succ : successors(BB)) { 2026 const BasicBlock::iterator E(Succ->getFirstNonPHI()); 2027 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) { 2028 PHINode *Phi = cast<PHINode>(&*I); 2029 Value *V = Phi->getIncomingValueForBlock(BB); 2030 assert(!isUnhandledGCPointerType(V->getType()) && 2031 "support for FCA unimplemented"); 2032 if (isHandledGCPointerType(V->getType()) && !isConstantNull(V) && 2033 !isa<UndefValue>(V)) { 2034 // The choice to exclude null and undef is arbitrary here. Reconsider? 2035 LiveTmp.insert(V); 2036 } 2037 } 2038 } 2039 } 2040 2041 static DenseSet<Value *> computeKillSet(BasicBlock *BB) { 2042 DenseSet<Value *> KillSet; 2043 for (Instruction &I : *BB) 2044 if (isHandledGCPointerType(I.getType())) 2045 KillSet.insert(&I); 2046 return KillSet; 2047 } 2048 2049 #ifndef NDEBUG 2050 /// Check that the items in 'Live' dominate 'TI'. This is used as a basic 2051 /// sanity check for the liveness computation. 2052 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live, 2053 TerminatorInst *TI, bool TermOkay = false) { 2054 for (Value *V : Live) { 2055 if (auto *I = dyn_cast<Instruction>(V)) { 2056 // The terminator can be a member of the LiveOut set. LLVM's definition 2057 // of instruction dominance states that V does not dominate itself. As 2058 // such, we need to special case this to allow it. 2059 if (TermOkay && TI == I) 2060 continue; 2061 assert(DT.dominates(I, TI) && 2062 "basic SSA liveness expectation violated by liveness analysis"); 2063 } 2064 } 2065 } 2066 2067 /// Check that all the liveness sets used during the computation of liveness 2068 /// obey basic SSA properties. This is useful for finding cases where we miss 2069 /// a def. 2070 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data, 2071 BasicBlock &BB) { 2072 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator()); 2073 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true); 2074 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator()); 2075 } 2076 #endif 2077 2078 static void computeLiveInValues(DominatorTree &DT, Function &F, 2079 GCPtrLivenessData &Data) { 2080 2081 SmallSetVector<BasicBlock *, 200> Worklist; 2082 auto AddPredsToWorklist = [&](BasicBlock *BB) { 2083 // We use a SetVector so that we don't have duplicates in the worklist. 2084 Worklist.insert(pred_begin(BB), pred_end(BB)); 2085 }; 2086 auto NextItem = [&]() { 2087 BasicBlock *BB = Worklist.back(); 2088 Worklist.pop_back(); 2089 return BB; 2090 }; 2091 2092 // Seed the liveness for each individual block 2093 for (BasicBlock &BB : F) { 2094 Data.KillSet[&BB] = computeKillSet(&BB); 2095 Data.LiveSet[&BB].clear(); 2096 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]); 2097 2098 #ifndef NDEBUG 2099 for (Value *Kill : Data.KillSet[&BB]) 2100 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill"); 2101 #endif 2102 2103 Data.LiveOut[&BB] = DenseSet<Value *>(); 2104 computeLiveOutSeed(&BB, Data.LiveOut[&BB]); 2105 Data.LiveIn[&BB] = Data.LiveSet[&BB]; 2106 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]); 2107 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]); 2108 if (!Data.LiveIn[&BB].empty()) 2109 AddPredsToWorklist(&BB); 2110 } 2111 2112 // Propagate that liveness until stable 2113 while (!Worklist.empty()) { 2114 BasicBlock *BB = NextItem(); 2115 2116 // Compute our new liveout set, then exit early if it hasn't changed 2117 // despite the contribution of our successor. 2118 DenseSet<Value *> LiveOut = Data.LiveOut[BB]; 2119 const auto OldLiveOutSize = LiveOut.size(); 2120 for (BasicBlock *Succ : successors(BB)) { 2121 assert(Data.LiveIn.count(Succ)); 2122 set_union(LiveOut, Data.LiveIn[Succ]); 2123 } 2124 // assert OutLiveOut is a subset of LiveOut 2125 if (OldLiveOutSize == LiveOut.size()) { 2126 // If the sets are the same size, then we didn't actually add anything 2127 // when unioning our successors LiveIn Thus, the LiveIn of this block 2128 // hasn't changed. 2129 continue; 2130 } 2131 Data.LiveOut[BB] = LiveOut; 2132 2133 // Apply the effects of this basic block 2134 DenseSet<Value *> LiveTmp = LiveOut; 2135 set_union(LiveTmp, Data.LiveSet[BB]); 2136 set_subtract(LiveTmp, Data.KillSet[BB]); 2137 2138 assert(Data.LiveIn.count(BB)); 2139 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB]; 2140 // assert: OldLiveIn is a subset of LiveTmp 2141 if (OldLiveIn.size() != LiveTmp.size()) { 2142 Data.LiveIn[BB] = LiveTmp; 2143 AddPredsToWorklist(BB); 2144 } 2145 } // while( !worklist.empty() ) 2146 2147 #ifndef NDEBUG 2148 // Sanity check our ouput against SSA properties. This helps catch any 2149 // missing kills during the above iteration. 2150 for (BasicBlock &BB : F) { 2151 checkBasicSSA(DT, Data, BB); 2152 } 2153 #endif 2154 } 2155 2156 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data, 2157 StatepointLiveSetTy &Out) { 2158 2159 BasicBlock *BB = Inst->getParent(); 2160 2161 // Note: The copy is intentional and required 2162 assert(Data.LiveOut.count(BB)); 2163 DenseSet<Value *> LiveOut = Data.LiveOut[BB]; 2164 2165 // We want to handle the statepoint itself oddly. It's 2166 // call result is not live (normal), nor are it's arguments 2167 // (unless they're used again later). This adjustment is 2168 // specifically what we need to relocate 2169 BasicBlock::reverse_iterator rend(Inst); 2170 computeLiveInValues(BB->rbegin(), rend, LiveOut); 2171 LiveOut.erase(Inst); 2172 Out.insert(LiveOut.begin(), LiveOut.end()); 2173 } 2174 2175 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData, 2176 const CallSite &CS, 2177 PartiallyConstructedSafepointRecord &Info) { 2178 Instruction *Inst = CS.getInstruction(); 2179 StatepointLiveSetTy Updated; 2180 findLiveSetAtInst(Inst, RevisedLivenessData, Updated); 2181 2182 #ifndef NDEBUG 2183 DenseSet<Value *> Bases; 2184 for (auto KVPair : Info.PointerToBase) { 2185 Bases.insert(KVPair.second); 2186 } 2187 #endif 2188 // We may have base pointers which are now live that weren't before. We need 2189 // to update the PointerToBase structure to reflect this. 2190 for (auto V : Updated) 2191 if (!Info.PointerToBase.count(V)) { 2192 assert(Bases.count(V) && "can't find base for unexpected live value"); 2193 Info.PointerToBase[V] = V; 2194 continue; 2195 } 2196 2197 #ifndef NDEBUG 2198 for (auto V : Updated) { 2199 assert(Info.PointerToBase.count(V) && 2200 "must be able to find base for live value"); 2201 } 2202 #endif 2203 2204 // Remove any stale base mappings - this can happen since our liveness is 2205 // more precise then the one inherent in the base pointer analysis 2206 DenseSet<Value *> ToErase; 2207 for (auto KVPair : Info.PointerToBase) 2208 if (!Updated.count(KVPair.first)) 2209 ToErase.insert(KVPair.first); 2210 for (auto V : ToErase) 2211 Info.PointerToBase.erase(V); 2212 2213 #ifndef NDEBUG 2214 for (auto KVPair : Info.PointerToBase) 2215 assert(Updated.count(KVPair.first) && "record for non-live value"); 2216 #endif 2217 2218 Info.liveset = Updated; 2219 } 2220