1//===- SpeculateAroundPHIs.cpp --------------------------------------------===// 2// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6// 7//===----------------------------------------------------------------------===// 8 9#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h" 10#include "llvm/ADT/PostOrderIterator.h" 11#include "llvm/ADT/Sequence.h" 12#include "llvm/ADT/SetVector.h" 13#include "llvm/ADT/Statistic.h" 14#include "llvm/Analysis/TargetTransformInfo.h" 15#include "llvm/Analysis/ValueTracking.h" 16#include "llvm/IR/BasicBlock.h" 17#include "llvm/IR/IRBuilder.h" 18#include "llvm/IR/Instructions.h" 19#include "llvm/IR/IntrinsicInst.h" 20#include "llvm/Support/Debug.h" 21#include "llvm/Transforms/Utils/BasicBlockUtils.h" 22 23using namespace llvm; 24 25#define DEBUG_TYPE "spec-phis" 26 27STATISTIC(NumPHIsSpeculated, "Number of PHI nodes we speculated around"); 28STATISTIC(NumEdgesSplit, 29 "Number of critical edges which were split for speculation"); 30STATISTIC(NumSpeculatedInstructions, 31 "Number of instructions we speculated around the PHI nodes"); 32STATISTIC(NumNewRedundantInstructions, 33 "Number of new, redundant instructions inserted"); 34 35/// Check whether speculating the users of a PHI node around the PHI 36/// will be safe. 37/// 38/// This checks both that all of the users are safe and also that all of their 39/// operands are either recursively safe or already available along an incoming 40/// edge to the PHI. 41/// 42/// This routine caches both all the safe nodes explored in `PotentialSpecSet` 43/// and the chain of nodes that definitively reach any unsafe node in 44/// `UnsafeSet`. By preserving these between repeated calls to this routine for 45/// PHIs in the same basic block, the exploration here can be reused. However, 46/// these caches must no be reused for PHIs in a different basic block as they 47/// reflect what is available along incoming edges. 48static bool 49isSafeToSpeculatePHIUsers(PHINode &PN, DominatorTree &DT, 50 SmallPtrSetImpl<Instruction *> &PotentialSpecSet, 51 SmallPtrSetImpl<Instruction *> &UnsafeSet) { 52 auto *PhiBB = PN.getParent(); 53 SmallPtrSet<Instruction *, 4> Visited; 54 SmallVector<std::pair<Instruction *, User::value_op_iterator>, 16> DFSStack; 55 56 // Walk each user of the PHI node. 57 for (Use &U : PN.uses()) { 58 auto *UI = cast<Instruction>(U.getUser()); 59 60 // Ensure the use post-dominates the PHI node. This ensures that, in the 61 // absence of unwinding, the use will actually be reached. 62 // FIXME: We use a blunt hammer of requiring them to be in the same basic 63 // block. We should consider using actual post-dominance here in the 64 // future. 65 if (UI->getParent() != PhiBB) { 66 LLVM_DEBUG(dbgs() << " Unsafe: use in a different BB: " << *UI << "\n"); 67 return false; 68 } 69 70 if (const auto *CS = dyn_cast<CallBase>(UI)) { 71 if (CS->isConvergent() || CS->cannotDuplicate()) { 72 LLVM_DEBUG(dbgs() << " Unsafe: convergent " 73 "callsite cannot de duplicated: " << *UI << '\n'); 74 return false; 75 } 76 } 77 78 // FIXME: This check is much too conservative. We're not going to move these 79 // instructions onto new dynamic paths through the program unless there is 80 // a call instruction between the use and the PHI node. And memory isn't 81 // changing unless there is a store in that same sequence. We should 82 // probably change this to do at least a limited scan of the intervening 83 // instructions and allow handling stores in easily proven safe cases. 84 if (mayBeMemoryDependent(*UI)) { 85 LLVM_DEBUG(dbgs() << " Unsafe: can't speculate use: " << *UI << "\n"); 86 return false; 87 } 88 89 // Now do a depth-first search of everything these users depend on to make 90 // sure they are transitively safe. This is a depth-first search, but we 91 // check nodes in preorder to minimize the amount of checking. 92 Visited.insert(UI); 93 DFSStack.push_back({UI, UI->value_op_begin()}); 94 do { 95 User::value_op_iterator OpIt; 96 std::tie(UI, OpIt) = DFSStack.pop_back_val(); 97 98 while (OpIt != UI->value_op_end()) { 99 auto *OpI = dyn_cast<Instruction>(*OpIt); 100 // Increment to the next operand for whenever we continue. 101 ++OpIt; 102 // No need to visit non-instructions, which can't form dependencies. 103 if (!OpI) 104 continue; 105 106 // Now do the main pre-order checks that this operand is a viable 107 // dependency of something we want to speculate. 108 109 // First do a few checks for instructions that won't require 110 // speculation at all because they are trivially available on the 111 // incoming edge (either through dominance or through an incoming value 112 // to a PHI). 113 // 114 // The cases in the current block will be trivially dominated by the 115 // edge. 116 auto *ParentBB = OpI->getParent(); 117 if (ParentBB == PhiBB) { 118 if (isa<PHINode>(OpI)) { 119 // We can trivially map through phi nodes in the same block. 120 continue; 121 } 122 } else if (DT.dominates(ParentBB, PhiBB)) { 123 // Instructions from dominating blocks are already available. 124 continue; 125 } 126 127 // Once we know that we're considering speculating the operand, check 128 // if we've already explored this subgraph and found it to be safe. 129 if (PotentialSpecSet.count(OpI)) 130 continue; 131 132 // If we've already explored this subgraph and found it unsafe, bail. 133 // If when we directly test whether this is safe it fails, bail. 134 if (UnsafeSet.count(OpI) || ParentBB != PhiBB || 135 mayBeMemoryDependent(*OpI)) { 136 LLVM_DEBUG(dbgs() << " Unsafe: can't speculate transitive use: " 137 << *OpI << "\n"); 138 // Record the stack of instructions which reach this node as unsafe 139 // so we prune subsequent searches. 140 UnsafeSet.insert(OpI); 141 for (auto &StackPair : DFSStack) { 142 Instruction *I = StackPair.first; 143 UnsafeSet.insert(I); 144 } 145 return false; 146 } 147 148 // Skip any operands we're already recursively checking. 149 if (!Visited.insert(OpI).second) 150 continue; 151 152 // Push onto the stack and descend. We can directly continue this 153 // loop when ascending. 154 DFSStack.push_back({UI, OpIt}); 155 UI = OpI; 156 OpIt = OpI->value_op_begin(); 157 } 158 159 // This node and all its operands are safe. Go ahead and cache that for 160 // reuse later. 161 PotentialSpecSet.insert(UI); 162 163 // Continue with the next node on the stack. 164 } while (!DFSStack.empty()); 165 } 166 167#ifndef NDEBUG 168 // Every visited operand should have been marked as safe for speculation at 169 // this point. Verify this and return success. 170 for (auto *I : Visited) 171 assert(PotentialSpecSet.count(I) && 172 "Failed to mark a visited instruction as safe!"); 173#endif 174 return true; 175} 176 177/// Check whether, in isolation, a given PHI node is both safe and profitable 178/// to speculate users around. 179/// 180/// This handles checking whether there are any constant operands to a PHI 181/// which could represent a useful speculation candidate, whether the users of 182/// the PHI are safe to speculate including all their transitive dependencies, 183/// and whether after speculation there will be some cost savings (profit) to 184/// folding the operands into the users of the PHI node. Returns true if both 185/// safe and profitable with relevant cost savings updated in the map and with 186/// an update to the `PotentialSpecSet`. Returns false if either safety or 187/// profitability are absent. Some new entries may be made to the 188/// `PotentialSpecSet` even when this routine returns false, but they remain 189/// conservatively correct. 190/// 191/// The profitability check here is a local one, but it checks this in an 192/// interesting way. Beyond checking that the total cost of materializing the 193/// constants will be less than the cost of folding them into their users, it 194/// also checks that no one incoming constant will have a higher cost when 195/// folded into its users rather than materialized. This higher cost could 196/// result in a dynamic *path* that is more expensive even when the total cost 197/// is lower. Currently, all of the interesting cases where this optimization 198/// should fire are ones where it is a no-loss operation in this sense. If we 199/// ever want to be more aggressive here, we would need to balance the 200/// different incoming edges' cost by looking at their respective 201/// probabilities. 202static bool isSafeAndProfitableToSpeculateAroundPHI( 203 PHINode &PN, SmallDenseMap<PHINode *, int, 16> &CostSavingsMap, 204 SmallPtrSetImpl<Instruction *> &PotentialSpecSet, 205 SmallPtrSetImpl<Instruction *> &UnsafeSet, DominatorTree &DT, 206 TargetTransformInfo &TTI) { 207 // First see whether there is any cost savings to speculating around this 208 // PHI, and build up a map of the constant inputs to how many times they 209 // occur. 210 bool NonFreeMat = false; 211 struct CostsAndCount { 212 int MatCost = TargetTransformInfo::TCC_Free; 213 int FoldedCost = TargetTransformInfo::TCC_Free; 214 int Count = 0; 215 }; 216 SmallDenseMap<ConstantInt *, CostsAndCount, 16> CostsAndCounts; 217 SmallPtrSet<BasicBlock *, 16> IncomingConstantBlocks; 218 for (int i : llvm::seq<int>(0, PN.getNumIncomingValues())) { 219 auto *IncomingC = dyn_cast<ConstantInt>(PN.getIncomingValue(i)); 220 if (!IncomingC) 221 continue; 222 223 // Only visit each incoming edge with a constant input once. 224 if (!IncomingConstantBlocks.insert(PN.getIncomingBlock(i)).second) 225 continue; 226 227 auto InsertResult = CostsAndCounts.insert({IncomingC, {}}); 228 // Count how many edges share a given incoming costant. 229 ++InsertResult.first->second.Count; 230 // Only compute the cost the first time we see a particular constant. 231 if (!InsertResult.second) 232 continue; 233 234 int &MatCost = InsertResult.first->second.MatCost; 235 MatCost = TTI.getIntImmCost(IncomingC->getValue(), IncomingC->getType(), 236 TargetTransformInfo::TCK_SizeAndLatency); 237 NonFreeMat |= MatCost != TTI.TCC_Free; 238 } 239 if (!NonFreeMat) { 240 LLVM_DEBUG(dbgs() << " Free: " << PN << "\n"); 241 // No profit in free materialization. 242 return false; 243 } 244 245 // Now check that the uses of this PHI can actually be speculated, 246 // otherwise we'll still have to materialize the PHI value. 247 if (!isSafeToSpeculatePHIUsers(PN, DT, PotentialSpecSet, UnsafeSet)) { 248 LLVM_DEBUG(dbgs() << " Unsafe PHI: " << PN << "\n"); 249 return false; 250 } 251 252 // Compute how much (if any) savings are available by speculating around this 253 // PHI. 254 for (Use &U : PN.uses()) { 255 auto *UserI = cast<Instruction>(U.getUser()); 256 // Now check whether there is any savings to folding the incoming constants 257 // into this use. 258 unsigned Idx = U.getOperandNo(); 259 260 // If we have a binary operator that is commutative, an actual constant 261 // operand would end up on the RHS, so pretend the use of the PHI is on the 262 // RHS. 263 // 264 // Technically, this is a bit weird if *both* operands are PHIs we're 265 // speculating. But if that is the case, giving an "optimistic" cost isn't 266 // a bad thing because after speculation it will constant fold. And 267 // moreover, such cases should likely have been constant folded already by 268 // some other pass, so we shouldn't worry about "modeling" them terribly 269 // accurately here. Similarly, if the other operand is a constant, it still 270 // seems fine to be "optimistic" in our cost modeling, because when the 271 // incoming operand from the PHI node is also a constant, we will end up 272 // constant folding. 273 if (UserI->isBinaryOp() && UserI->isCommutative() && Idx != 1) 274 // Assume we will commute the constant to the RHS to be canonical. 275 Idx = 1; 276 277 // Get the intrinsic ID if this user is an intrinsic. 278 Intrinsic::ID IID = Intrinsic::not_intrinsic; 279 if (auto *UserII = dyn_cast<IntrinsicInst>(UserI)) 280 IID = UserII->getIntrinsicID(); 281 282 for (auto &IncomingConstantAndCostsAndCount : CostsAndCounts) { 283 ConstantInt *IncomingC = IncomingConstantAndCostsAndCount.first; 284 int MatCost = IncomingConstantAndCostsAndCount.second.MatCost; 285 int &FoldedCost = IncomingConstantAndCostsAndCount.second.FoldedCost; 286 if (IID) 287 FoldedCost += 288 TTI.getIntImmCostIntrin(IID, Idx, IncomingC->getValue(), 289 IncomingC->getType(), 290 TargetTransformInfo::TCK_SizeAndLatency); 291 else 292 FoldedCost += 293 TTI.getIntImmCostInst(UserI->getOpcode(), Idx, 294 IncomingC->getValue(), IncomingC->getType(), 295 TargetTransformInfo::TCK_SizeAndLatency); 296 297 // If we accumulate more folded cost for this incoming constant than 298 // materialized cost, then we'll regress any edge with this constant so 299 // just bail. We're only interested in cases where folding the incoming 300 // constants is at least break-even on all paths. 301 if (FoldedCost > MatCost) { 302 LLVM_DEBUG(dbgs() << " Not profitable to fold imm: " << *IncomingC 303 << "\n" 304 " Materializing cost: " 305 << MatCost 306 << "\n" 307 " Accumulated folded cost: " 308 << FoldedCost << "\n"); 309 return false; 310 } 311 } 312 } 313 314 // Compute the total cost savings afforded by this PHI node. 315 int TotalMatCost = TTI.TCC_Free, TotalFoldedCost = TTI.TCC_Free; 316 for (auto IncomingConstantAndCostsAndCount : CostsAndCounts) { 317 int MatCost = IncomingConstantAndCostsAndCount.second.MatCost; 318 int FoldedCost = IncomingConstantAndCostsAndCount.second.FoldedCost; 319 int Count = IncomingConstantAndCostsAndCount.second.Count; 320 321 TotalMatCost += MatCost * Count; 322 TotalFoldedCost += FoldedCost * Count; 323 } 324 assert(TotalFoldedCost <= TotalMatCost && "If each constant's folded cost is " 325 "less that its materialized cost, " 326 "the sum must be as well."); 327 328 LLVM_DEBUG(dbgs() << " Cost savings " << (TotalMatCost - TotalFoldedCost) 329 << ": " << PN << "\n"); 330 CostSavingsMap[&PN] = TotalMatCost - TotalFoldedCost; 331 return true; 332} 333 334/// Simple helper to walk all the users of a list of phis depth first, and call 335/// a visit function on each one in post-order. 336/// 337/// All of the PHIs should be in the same basic block, and this is primarily 338/// used to make a single depth-first walk across their collective users 339/// without revisiting any subgraphs. Callers should provide a fast, idempotent 340/// callable to test whether a node has been visited and the more important 341/// callable to actually visit a particular node. 342/// 343/// Depth-first and postorder here refer to the *operand* graph -- we start 344/// from a collection of users of PHI nodes and walk "up" the operands 345/// depth-first. 346template <typename IsVisitedT, typename VisitT> 347static void visitPHIUsersAndDepsInPostOrder(ArrayRef<PHINode *> PNs, 348 IsVisitedT IsVisited, 349 VisitT Visit) { 350 SmallVector<std::pair<Instruction *, User::value_op_iterator>, 16> DFSStack; 351 for (auto *PN : PNs) 352 for (Use &U : PN->uses()) { 353 auto *UI = cast<Instruction>(U.getUser()); 354 if (IsVisited(UI)) 355 // Already visited this user, continue across the roots. 356 continue; 357 358 // Otherwise, walk the operand graph depth-first and visit each 359 // dependency in postorder. 360 DFSStack.push_back({UI, UI->value_op_begin()}); 361 do { 362 User::value_op_iterator OpIt; 363 std::tie(UI, OpIt) = DFSStack.pop_back_val(); 364 while (OpIt != UI->value_op_end()) { 365 auto *OpI = dyn_cast<Instruction>(*OpIt); 366 // Increment to the next operand for whenever we continue. 367 ++OpIt; 368 // No need to visit non-instructions, which can't form dependencies, 369 // or instructions outside of our potential dependency set that we 370 // were given. Finally, if we've already visited the node, continue 371 // to the next. 372 if (!OpI || IsVisited(OpI)) 373 continue; 374 375 // Push onto the stack and descend. We can directly continue this 376 // loop when ascending. 377 DFSStack.push_back({UI, OpIt}); 378 UI = OpI; 379 OpIt = OpI->value_op_begin(); 380 } 381 382 // Finished visiting children, visit this node. 383 assert(!IsVisited(UI) && "Should not have already visited a node!"); 384 Visit(UI); 385 } while (!DFSStack.empty()); 386 } 387} 388 389/// Find profitable PHIs to speculate. 390/// 391/// For a PHI node to be profitable, we need the cost of speculating its users 392/// (and their dependencies) to not exceed the savings of folding the PHI's 393/// constant operands into the speculated users. 394/// 395/// Computing this is surprisingly challenging. Because users of two different 396/// PHI nodes can depend on each other or on common other instructions, it may 397/// be profitable to speculate two PHI nodes together even though neither one 398/// in isolation is profitable. The straightforward way to find all the 399/// profitable PHIs would be to check each combination of PHIs' cost, but this 400/// is exponential in complexity. 401/// 402/// Even if we assume that we only care about cases where we can consider each 403/// PHI node in isolation (rather than considering cases where none are 404/// profitable in isolation but some subset are profitable as a set), we still 405/// have a challenge. The obvious way to find all individually profitable PHIs 406/// is to iterate until reaching a fixed point, but this will be quadratic in 407/// complexity. =/ 408/// 409/// This code currently uses a linear-to-compute order for a greedy approach. 410/// It won't find cases where a set of PHIs must be considered together, but it 411/// handles most cases of order dependence without quadratic iteration. The 412/// specific order used is the post-order across the operand DAG. When the last 413/// user of a PHI is visited in this postorder walk, we check it for 414/// profitability. 415/// 416/// There is an orthogonal extra complexity to all of this: computing the cost 417/// itself can easily become a linear computation making everything again (at 418/// best) quadratic. Using a postorder over the operand graph makes it 419/// particularly easy to avoid this through dynamic programming. As we do the 420/// postorder walk, we build the transitive cost of that subgraph. It is also 421/// straightforward to then update these costs when we mark a PHI for 422/// speculation so that subsequent PHIs don't re-pay the cost of already 423/// speculated instructions. 424static SmallVector<PHINode *, 16> 425findProfitablePHIs(ArrayRef<PHINode *> PNs, 426 const SmallDenseMap<PHINode *, int, 16> &CostSavingsMap, 427 const SmallPtrSetImpl<Instruction *> &PotentialSpecSet, 428 int NumPreds, DominatorTree &DT, TargetTransformInfo &TTI) { 429 SmallVector<PHINode *, 16> SpecPNs; 430 431 // First, establish a reverse mapping from immediate users of the PHI nodes 432 // to the nodes themselves, and count how many users each PHI node has in 433 // a way we can update while processing them. 434 SmallDenseMap<Instruction *, TinyPtrVector<PHINode *>, 16> UserToPNMap; 435 SmallDenseMap<PHINode *, int, 16> PNUserCountMap; 436 SmallPtrSet<Instruction *, 16> UserSet; 437 for (auto *PN : PNs) { 438 assert(UserSet.empty() && "Must start with an empty user set!"); 439 for (Use &U : PN->uses()) 440 UserSet.insert(cast<Instruction>(U.getUser())); 441 PNUserCountMap[PN] = UserSet.size(); 442 for (auto *UI : UserSet) 443 UserToPNMap.insert({UI, {}}).first->second.push_back(PN); 444 UserSet.clear(); 445 } 446 447 // Now do a DFS across the operand graph of the users, computing cost as we 448 // go and when all costs for a given PHI are known, checking that PHI for 449 // profitability. 450 SmallDenseMap<Instruction *, int, 16> SpecCostMap; 451 visitPHIUsersAndDepsInPostOrder( 452 PNs, 453 /*IsVisited*/ 454 [&](Instruction *I) { 455 // We consider anything that isn't potentially speculated to be 456 // "visited" as it is already handled. Similarly, anything that *is* 457 // potentially speculated but for which we have an entry in our cost 458 // map, we're done. 459 return !PotentialSpecSet.count(I) || SpecCostMap.count(I); 460 }, 461 /*Visit*/ 462 [&](Instruction *I) { 463 // We've fully visited the operands, so sum their cost with this node 464 // and update the cost map. 465 int Cost = TTI.TCC_Free; 466 for (Value *OpV : I->operand_values()) 467 if (auto *OpI = dyn_cast<Instruction>(OpV)) { 468 auto CostMapIt = SpecCostMap.find(OpI); 469 if (CostMapIt != SpecCostMap.end()) 470 Cost += CostMapIt->second; 471 } 472 Cost += TTI.getUserCost(I, TargetTransformInfo::TCK_SizeAndLatency); 473 bool Inserted = SpecCostMap.insert({I, Cost}).second; 474 (void)Inserted; 475 assert(Inserted && "Must not re-insert a cost during the DFS!"); 476 477 // Now check if this node had a corresponding PHI node using it. If so, 478 // we need to decrement the outstanding user count for it. 479 auto UserPNsIt = UserToPNMap.find(I); 480 if (UserPNsIt == UserToPNMap.end()) 481 return; 482 auto &UserPNs = UserPNsIt->second; 483 auto UserPNsSplitIt = std::stable_partition( 484 UserPNs.begin(), UserPNs.end(), [&](PHINode *UserPN) { 485 int &PNUserCount = PNUserCountMap.find(UserPN)->second; 486 assert( 487 PNUserCount > 0 && 488 "Should never re-visit a PN after its user count hits zero!"); 489 --PNUserCount; 490 return PNUserCount != 0; 491 }); 492 493 // FIXME: Rather than one at a time, we should sum the savings as the 494 // cost will be completely shared. 495 SmallVector<Instruction *, 16> SpecWorklist; 496 for (auto *PN : llvm::make_range(UserPNsSplitIt, UserPNs.end())) { 497 int SpecCost = TTI.TCC_Free; 498 for (Use &U : PN->uses()) 499 SpecCost += 500 SpecCostMap.find(cast<Instruction>(U.getUser()))->second; 501 SpecCost *= (NumPreds - 1); 502 // When the user count of a PHI node hits zero, we should check its 503 // profitability. If profitable, we should mark it for speculation 504 // and zero out the cost of everything it depends on. 505 int CostSavings = CostSavingsMap.find(PN)->second; 506 if (SpecCost > CostSavings) { 507 LLVM_DEBUG(dbgs() << " Not profitable, speculation cost: " << *PN 508 << "\n" 509 " Cost savings: " 510 << CostSavings 511 << "\n" 512 " Speculation cost: " 513 << SpecCost << "\n"); 514 continue; 515 } 516 517 // We're going to speculate this user-associated PHI. Copy it out and 518 // add its users to the worklist to update their cost. 519 SpecPNs.push_back(PN); 520 for (Use &U : PN->uses()) { 521 auto *UI = cast<Instruction>(U.getUser()); 522 auto CostMapIt = SpecCostMap.find(UI); 523 if (CostMapIt->second == 0) 524 continue; 525 // Zero out this cost entry to avoid duplicates. 526 CostMapIt->second = 0; 527 SpecWorklist.push_back(UI); 528 } 529 } 530 531 // Now walk all the operands of the users in the worklist transitively 532 // to zero out all the memoized costs. 533 while (!SpecWorklist.empty()) { 534 Instruction *SpecI = SpecWorklist.pop_back_val(); 535 assert(SpecCostMap.find(SpecI)->second == 0 && 536 "Didn't zero out a cost!"); 537 538 // Walk the operands recursively to zero out their cost as well. 539 for (auto *OpV : SpecI->operand_values()) { 540 auto *OpI = dyn_cast<Instruction>(OpV); 541 if (!OpI) 542 continue; 543 auto CostMapIt = SpecCostMap.find(OpI); 544 if (CostMapIt == SpecCostMap.end() || CostMapIt->second == 0) 545 continue; 546 CostMapIt->second = 0; 547 SpecWorklist.push_back(OpI); 548 } 549 } 550 }); 551 552 return SpecPNs; 553} 554 555/// Speculate users around a set of PHI nodes. 556/// 557/// This routine does the actual speculation around a set of PHI nodes where we 558/// have determined this to be both safe and profitable. 559/// 560/// This routine handles any spliting of critical edges necessary to create 561/// a safe block to speculate into as well as cloning the instructions and 562/// rewriting all uses. 563static void speculatePHIs(ArrayRef<PHINode *> SpecPNs, 564 SmallPtrSetImpl<Instruction *> &PotentialSpecSet, 565 SmallSetVector<BasicBlock *, 16> &PredSet, 566 DominatorTree &DT) { 567 LLVM_DEBUG(dbgs() << " Speculating around " << SpecPNs.size() << " PHIs!\n"); 568 NumPHIsSpeculated += SpecPNs.size(); 569 570 // Split any critical edges so that we have a block to hoist into. 571 auto *ParentBB = SpecPNs[0]->getParent(); 572 SmallVector<BasicBlock *, 16> SpecPreds; 573 SpecPreds.reserve(PredSet.size()); 574 for (auto *PredBB : PredSet) { 575 auto *NewPredBB = SplitCriticalEdge( 576 PredBB, ParentBB, 577 CriticalEdgeSplittingOptions(&DT).setMergeIdenticalEdges()); 578 if (NewPredBB) { 579 ++NumEdgesSplit; 580 LLVM_DEBUG(dbgs() << " Split critical edge from: " << PredBB->getName() 581 << "\n"); 582 SpecPreds.push_back(NewPredBB); 583 } else { 584 assert(PredBB->getSingleSuccessor() == ParentBB && 585 "We need a non-critical predecessor to speculate into."); 586 assert(!isa<InvokeInst>(PredBB->getTerminator()) && 587 "Cannot have a non-critical invoke!"); 588 589 // Already non-critical, use existing pred. 590 SpecPreds.push_back(PredBB); 591 } 592 } 593 594 SmallPtrSet<Instruction *, 16> SpecSet; 595 SmallVector<Instruction *, 16> SpecList; 596 visitPHIUsersAndDepsInPostOrder(SpecPNs, 597 /*IsVisited*/ 598 [&](Instruction *I) { 599 // This is visited if we don't need to 600 // speculate it or we already have 601 // speculated it. 602 return !PotentialSpecSet.count(I) || 603 SpecSet.count(I); 604 }, 605 /*Visit*/ 606 [&](Instruction *I) { 607 // All operands scheduled, schedule this 608 // node. 609 SpecSet.insert(I); 610 SpecList.push_back(I); 611 }); 612 613 int NumSpecInsts = SpecList.size() * SpecPreds.size(); 614 int NumRedundantInsts = NumSpecInsts - SpecList.size(); 615 LLVM_DEBUG(dbgs() << " Inserting " << NumSpecInsts 616 << " speculated instructions, " << NumRedundantInsts 617 << " redundancies\n"); 618 NumSpeculatedInstructions += NumSpecInsts; 619 NumNewRedundantInstructions += NumRedundantInsts; 620 621 // Each predecessor is numbered by its index in `SpecPreds`, so for each 622 // instruction we speculate, the speculated instruction is stored in that 623 // index of the vector associated with the original instruction. We also 624 // store the incoming values for each predecessor from any PHIs used. 625 SmallDenseMap<Instruction *, SmallVector<Value *, 2>, 16> SpeculatedValueMap; 626 627 // Inject the synthetic mappings to rewrite PHIs to the appropriate incoming 628 // value. This handles both the PHIs we are speculating around and any other 629 // PHIs that happen to be used. 630 for (auto *OrigI : SpecList) 631 for (auto *OpV : OrigI->operand_values()) { 632 auto *OpPN = dyn_cast<PHINode>(OpV); 633 if (!OpPN || OpPN->getParent() != ParentBB) 634 continue; 635 636 auto InsertResult = SpeculatedValueMap.insert({OpPN, {}}); 637 if (!InsertResult.second) 638 continue; 639 640 auto &SpeculatedVals = InsertResult.first->second; 641 642 // Populating our structure for mapping is particularly annoying because 643 // finding an incoming value for a particular predecessor block in a PHI 644 // node is a linear time operation! To avoid quadratic behavior, we build 645 // a map for this PHI node's incoming values and then translate it into 646 // the more compact representation used below. 647 SmallDenseMap<BasicBlock *, Value *, 16> IncomingValueMap; 648 for (int i : llvm::seq<int>(0, OpPN->getNumIncomingValues())) 649 IncomingValueMap[OpPN->getIncomingBlock(i)] = OpPN->getIncomingValue(i); 650 651 for (auto *PredBB : SpecPreds) 652 SpeculatedVals.push_back(IncomingValueMap.find(PredBB)->second); 653 } 654 655 // Speculate into each predecessor. 656 for (int PredIdx : llvm::seq<int>(0, SpecPreds.size())) { 657 auto *PredBB = SpecPreds[PredIdx]; 658 assert(PredBB->getSingleSuccessor() == ParentBB && 659 "We need a non-critical predecessor to speculate into."); 660 661 for (auto *OrigI : SpecList) { 662 auto *NewI = OrigI->clone(); 663 NewI->setName(Twine(OrigI->getName()) + "." + Twine(PredIdx)); 664 NewI->insertBefore(PredBB->getTerminator()); 665 666 // Rewrite all the operands to the previously speculated instructions. 667 // Because we're walking in-order, the defs must precede the uses and we 668 // should already have these mappings. 669 for (Use &U : NewI->operands()) { 670 auto *OpI = dyn_cast<Instruction>(U.get()); 671 if (!OpI) 672 continue; 673 auto MapIt = SpeculatedValueMap.find(OpI); 674 if (MapIt == SpeculatedValueMap.end()) 675 continue; 676 const auto &SpeculatedVals = MapIt->second; 677 assert(SpeculatedVals[PredIdx] && 678 "Must have a speculated value for this predecessor!"); 679 assert(SpeculatedVals[PredIdx]->getType() == OpI->getType() && 680 "Speculated value has the wrong type!"); 681 682 // Rewrite the use to this predecessor's speculated instruction. 683 U.set(SpeculatedVals[PredIdx]); 684 } 685 686 // Commute instructions which now have a constant in the LHS but not the 687 // RHS. 688 if (NewI->isBinaryOp() && NewI->isCommutative() && 689 isa<Constant>(NewI->getOperand(0)) && 690 !isa<Constant>(NewI->getOperand(1))) 691 NewI->getOperandUse(0).swap(NewI->getOperandUse(1)); 692 693 SpeculatedValueMap[OrigI].push_back(NewI); 694 assert(SpeculatedValueMap[OrigI][PredIdx] == NewI && 695 "Mismatched speculated instruction index!"); 696 } 697 } 698 699 // Walk the speculated instruction list and if they have uses, insert a PHI 700 // for them from the speculated versions, and replace the uses with the PHI. 701 // Then erase the instructions as they have been fully speculated. The walk 702 // needs to be in reverse so that we don't think there are users when we'll 703 // actually eventually remove them later. 704 IRBuilder<> IRB(SpecPNs[0]); 705 for (auto *OrigI : llvm::reverse(SpecList)) { 706 // Check if we need a PHI for any remaining users and if so, insert it. 707 if (!OrigI->use_empty()) { 708 auto *SpecIPN = IRB.CreatePHI(OrigI->getType(), SpecPreds.size(), 709 Twine(OrigI->getName()) + ".phi"); 710 // Add the incoming values we speculated. 711 auto &SpeculatedVals = SpeculatedValueMap.find(OrigI)->second; 712 for (int PredIdx : llvm::seq<int>(0, SpecPreds.size())) 713 SpecIPN->addIncoming(SpeculatedVals[PredIdx], SpecPreds[PredIdx]); 714 715 // And replace the uses with the PHI node. 716 OrigI->replaceAllUsesWith(SpecIPN); 717 } 718 719 // It is important to immediately erase this so that it stops using other 720 // instructions. This avoids inserting needless PHIs of them. 721 OrigI->eraseFromParent(); 722 } 723 724 // All of the uses of the speculated phi nodes should be removed at this 725 // point, so erase them. 726 for (auto *SpecPN : SpecPNs) { 727 assert(SpecPN->use_empty() && "All users should have been speculated!"); 728 SpecPN->eraseFromParent(); 729 } 730} 731 732/// Try to speculate around a series of PHIs from a single basic block. 733/// 734/// This routine checks whether any of these PHIs are profitable to speculate 735/// users around. If safe and profitable, it does the speculation. It returns 736/// true when at least some speculation occurs. 737static bool tryToSpeculatePHIs(SmallVectorImpl<PHINode *> &PNs, 738 DominatorTree &DT, TargetTransformInfo &TTI) { 739 LLVM_DEBUG(dbgs() << "Evaluating phi nodes for speculation:\n"); 740 741 // Savings in cost from speculating around a PHI node. 742 SmallDenseMap<PHINode *, int, 16> CostSavingsMap; 743 744 // Remember the set of instructions that are candidates for speculation so 745 // that we can quickly walk things within that space. This prunes out 746 // instructions already available along edges, etc. 747 SmallPtrSet<Instruction *, 16> PotentialSpecSet; 748 749 // Remember the set of instructions that are (transitively) unsafe to 750 // speculate into the incoming edges of this basic block. This avoids 751 // recomputing them for each PHI node we check. This set is specific to this 752 // block though as things are pruned out of it based on what is available 753 // along incoming edges. 754 SmallPtrSet<Instruction *, 16> UnsafeSet; 755 756 // For each PHI node in this block, check whether there are immediate folding 757 // opportunities from speculation, and whether that speculation will be 758 // valid. This determise the set of safe PHIs to speculate. 759 PNs.erase(llvm::remove_if(PNs, 760 [&](PHINode *PN) { 761 return !isSafeAndProfitableToSpeculateAroundPHI( 762 *PN, CostSavingsMap, PotentialSpecSet, 763 UnsafeSet, DT, TTI); 764 }), 765 PNs.end()); 766 // If no PHIs were profitable, skip. 767 if (PNs.empty()) { 768 LLVM_DEBUG(dbgs() << " No safe and profitable PHIs found!\n"); 769 return false; 770 } 771 772 // We need to know how much speculation will cost which is determined by how 773 // many incoming edges will need a copy of each speculated instruction. 774 SmallSetVector<BasicBlock *, 16> PredSet; 775 for (auto *PredBB : PNs[0]->blocks()) { 776 if (!PredSet.insert(PredBB)) 777 continue; 778 779 // We cannot speculate when a predecessor is an indirect branch. 780 // FIXME: We also can't reliably create a non-critical edge block for 781 // speculation if the predecessor is an invoke. This doesn't seem 782 // fundamental and we should probably be splitting critical edges 783 // differently. 784 const auto *TermInst = PredBB->getTerminator(); 785 if (isa<IndirectBrInst>(TermInst) || 786 isa<InvokeInst>(TermInst) || 787 isa<CallBrInst>(TermInst)) { 788 LLVM_DEBUG(dbgs() << " Invalid: predecessor terminator: " 789 << PredBB->getName() << "\n"); 790 return false; 791 } 792 } 793 if (PredSet.size() < 2) { 794 LLVM_DEBUG(dbgs() << " Unimportant: phi with only one predecessor\n"); 795 return false; 796 } 797 798 SmallVector<PHINode *, 16> SpecPNs = findProfitablePHIs( 799 PNs, CostSavingsMap, PotentialSpecSet, PredSet.size(), DT, TTI); 800 if (SpecPNs.empty()) 801 // Nothing to do. 802 return false; 803 804 speculatePHIs(SpecPNs, PotentialSpecSet, PredSet, DT); 805 return true; 806} 807 808PreservedAnalyses SpeculateAroundPHIsPass::run(Function &F, 809 FunctionAnalysisManager &AM) { 810 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 811 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 812 813 bool Changed = false; 814 for (auto *BB : ReversePostOrderTraversal<Function *>(&F)) { 815 SmallVector<PHINode *, 16> PNs; 816 auto BBI = BB->begin(); 817 while (auto *PN = dyn_cast<PHINode>(&*BBI)) { 818 PNs.push_back(PN); 819 ++BBI; 820 } 821 822 if (PNs.empty()) 823 continue; 824 825 Changed |= tryToSpeculatePHIs(PNs, DT, TTI); 826 } 827 828 if (!Changed) 829 return PreservedAnalyses::all(); 830 831 PreservedAnalyses PA; 832 return PA; 833} 834