1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// 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 // This transformation analyzes and transforms the induction variables (and 11 // computations derived from them) into simpler forms suitable for subsequent 12 // analysis and transformation. 13 // 14 // If the trip count of a loop is computable, this pass also makes the following 15 // changes: 16 // 1. The exit condition for the loop is canonicalized to compare the 17 // induction value against the exit value. This turns loops like: 18 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)' 19 // 2. Any use outside of the loop of an expression derived from the indvar 20 // is changed to compute the derived value outside of the loop, eliminating 21 // the dependence on the exit value of the induction variable. If the only 22 // purpose of the loop is to compute the exit value of some derived 23 // expression, this transformation will make the loop dead. 24 // 25 //===----------------------------------------------------------------------===// 26 27 #include "llvm/Transforms/Scalar.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/Analysis/LoopInfo.h" 32 #include "llvm/Analysis/LoopPass.h" 33 #include "llvm/Analysis/ScalarEvolutionExpander.h" 34 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/TargetTransformInfo.h" 37 #include "llvm/IR/BasicBlock.h" 38 #include "llvm/IR/CFG.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/Dominators.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/IntrinsicInst.h" 44 #include "llvm/IR/LLVMContext.h" 45 #include "llvm/IR/PatternMatch.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/Support/CommandLine.h" 48 #include "llvm/Support/Debug.h" 49 #include "llvm/Support/raw_ostream.h" 50 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 51 #include "llvm/Transforms/Utils/Local.h" 52 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 53 using namespace llvm; 54 55 #define DEBUG_TYPE "indvars" 56 57 STATISTIC(NumWidened , "Number of indvars widened"); 58 STATISTIC(NumReplaced , "Number of exit values replaced"); 59 STATISTIC(NumLFTR , "Number of loop exit tests replaced"); 60 STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated"); 61 STATISTIC(NumElimIV , "Number of congruent IVs eliminated"); 62 63 // Trip count verification can be enabled by default under NDEBUG if we 64 // implement a strong expression equivalence checker in SCEV. Until then, we 65 // use the verify-indvars flag, which may assert in some cases. 66 static cl::opt<bool> VerifyIndvars( 67 "verify-indvars", cl::Hidden, 68 cl::desc("Verify the ScalarEvolution result after running indvars")); 69 70 static cl::opt<bool> ReduceLiveIVs("liv-reduce", cl::Hidden, 71 cl::desc("Reduce live induction variables.")); 72 73 enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl }; 74 75 static cl::opt<ReplaceExitVal> ReplaceExitValue( 76 "replexitval", cl::Hidden, cl::init(OnlyCheapRepl), 77 cl::desc("Choose the strategy to replace exit value in IndVarSimplify"), 78 cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"), 79 clEnumValN(OnlyCheapRepl, "cheap", 80 "only replace exit value when the cost is cheap"), 81 clEnumValN(AlwaysRepl, "always", 82 "always replace exit value whenever possible"), 83 clEnumValEnd)); 84 85 namespace { 86 struct RewritePhi; 87 } 88 89 namespace { 90 class IndVarSimplify : public LoopPass { 91 LoopInfo *LI; 92 ScalarEvolution *SE; 93 DominatorTree *DT; 94 TargetLibraryInfo *TLI; 95 const TargetTransformInfo *TTI; 96 97 SmallVector<WeakVH, 16> DeadInsts; 98 bool Changed; 99 public: 100 101 static char ID; // Pass identification, replacement for typeid 102 IndVarSimplify() 103 : LoopPass(ID), LI(nullptr), SE(nullptr), DT(nullptr), Changed(false) { 104 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry()); 105 } 106 107 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 108 109 void getAnalysisUsage(AnalysisUsage &AU) const override { 110 AU.addRequired<DominatorTreeWrapperPass>(); 111 AU.addRequired<LoopInfoWrapperPass>(); 112 AU.addRequired<ScalarEvolutionWrapperPass>(); 113 AU.addRequiredID(LoopSimplifyID); 114 AU.addRequiredID(LCSSAID); 115 AU.addPreserved<ScalarEvolutionWrapperPass>(); 116 AU.addPreservedID(LoopSimplifyID); 117 AU.addPreservedID(LCSSAID); 118 AU.setPreservesCFG(); 119 } 120 121 private: 122 void releaseMemory() override { 123 DeadInsts.clear(); 124 } 125 126 bool isValidRewrite(Value *FromVal, Value *ToVal); 127 128 void HandleFloatingPointIV(Loop *L, PHINode *PH); 129 void RewriteNonIntegerIVs(Loop *L); 130 131 void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM); 132 133 bool CanLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet); 134 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter); 135 136 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount, 137 PHINode *IndVar, SCEVExpander &Rewriter); 138 139 void SinkUnusedInvariants(Loop *L); 140 141 Value *ExpandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S, Loop *L, 142 Instruction *InsertPt, Type *Ty); 143 }; 144 } 145 146 char IndVarSimplify::ID = 0; 147 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars", 148 "Induction Variable Simplification", false, false) 149 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 150 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 151 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 152 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 153 INITIALIZE_PASS_DEPENDENCY(LCSSA) 154 INITIALIZE_PASS_END(IndVarSimplify, "indvars", 155 "Induction Variable Simplification", false, false) 156 157 Pass *llvm::createIndVarSimplifyPass() { 158 return new IndVarSimplify(); 159 } 160 161 /// isValidRewrite - Return true if the SCEV expansion generated by the 162 /// rewriter can replace the original value. SCEV guarantees that it 163 /// produces the same value, but the way it is produced may be illegal IR. 164 /// Ideally, this function will only be called for verification. 165 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) { 166 // If an SCEV expression subsumed multiple pointers, its expansion could 167 // reassociate the GEP changing the base pointer. This is illegal because the 168 // final address produced by a GEP chain must be inbounds relative to its 169 // underlying object. Otherwise basic alias analysis, among other things, 170 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid 171 // producing an expression involving multiple pointers. Until then, we must 172 // bail out here. 173 // 174 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject 175 // because it understands lcssa phis while SCEV does not. 176 Value *FromPtr = FromVal; 177 Value *ToPtr = ToVal; 178 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) { 179 FromPtr = GEP->getPointerOperand(); 180 } 181 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) { 182 ToPtr = GEP->getPointerOperand(); 183 } 184 if (FromPtr != FromVal || ToPtr != ToVal) { 185 // Quickly check the common case 186 if (FromPtr == ToPtr) 187 return true; 188 189 // SCEV may have rewritten an expression that produces the GEP's pointer 190 // operand. That's ok as long as the pointer operand has the same base 191 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the 192 // base of a recurrence. This handles the case in which SCEV expansion 193 // converts a pointer type recurrence into a nonrecurrent pointer base 194 // indexed by an integer recurrence. 195 196 // If the GEP base pointer is a vector of pointers, abort. 197 if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy()) 198 return false; 199 200 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr)); 201 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr)); 202 if (FromBase == ToBase) 203 return true; 204 205 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out " 206 << *FromBase << " != " << *ToBase << "\n"); 207 208 return false; 209 } 210 return true; 211 } 212 213 /// Determine the insertion point for this user. By default, insert immediately 214 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the 215 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest 216 /// common dominator for the incoming blocks. 217 static Instruction *getInsertPointForUses(Instruction *User, Value *Def, 218 DominatorTree *DT) { 219 PHINode *PHI = dyn_cast<PHINode>(User); 220 if (!PHI) 221 return User; 222 223 Instruction *InsertPt = nullptr; 224 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) { 225 if (PHI->getIncomingValue(i) != Def) 226 continue; 227 228 BasicBlock *InsertBB = PHI->getIncomingBlock(i); 229 if (!InsertPt) { 230 InsertPt = InsertBB->getTerminator(); 231 continue; 232 } 233 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB); 234 InsertPt = InsertBB->getTerminator(); 235 } 236 assert(InsertPt && "Missing phi operand"); 237 assert((!isa<Instruction>(Def) || 238 DT->dominates(cast<Instruction>(Def), InsertPt)) && 239 "def does not dominate all uses"); 240 return InsertPt; 241 } 242 243 //===----------------------------------------------------------------------===// 244 // RewriteNonIntegerIVs and helpers. Prefer integer IVs. 245 //===----------------------------------------------------------------------===// 246 247 /// ConvertToSInt - Convert APF to an integer, if possible. 248 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) { 249 bool isExact = false; 250 // See if we can convert this to an int64_t 251 uint64_t UIntVal; 252 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero, 253 &isExact) != APFloat::opOK || !isExact) 254 return false; 255 IntVal = UIntVal; 256 return true; 257 } 258 259 /// HandleFloatingPointIV - If the loop has floating induction variable 260 /// then insert corresponding integer induction variable if possible. 261 /// For example, 262 /// for(double i = 0; i < 10000; ++i) 263 /// bar(i) 264 /// is converted into 265 /// for(int i = 0; i < 10000; ++i) 266 /// bar((double)i); 267 /// 268 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) { 269 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 270 unsigned BackEdge = IncomingEdge^1; 271 272 // Check incoming value. 273 ConstantFP *InitValueVal = 274 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge)); 275 276 int64_t InitValue; 277 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue)) 278 return; 279 280 // Check IV increment. Reject this PN if increment operation is not 281 // an add or increment value can not be represented by an integer. 282 BinaryOperator *Incr = 283 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge)); 284 if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return; 285 286 // If this is not an add of the PHI with a constantfp, or if the constant fp 287 // is not an integer, bail out. 288 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1)); 289 int64_t IncValue; 290 if (IncValueVal == nullptr || Incr->getOperand(0) != PN || 291 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue)) 292 return; 293 294 // Check Incr uses. One user is PN and the other user is an exit condition 295 // used by the conditional terminator. 296 Value::user_iterator IncrUse = Incr->user_begin(); 297 Instruction *U1 = cast<Instruction>(*IncrUse++); 298 if (IncrUse == Incr->user_end()) return; 299 Instruction *U2 = cast<Instruction>(*IncrUse++); 300 if (IncrUse != Incr->user_end()) return; 301 302 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't 303 // only used by a branch, we can't transform it. 304 FCmpInst *Compare = dyn_cast<FCmpInst>(U1); 305 if (!Compare) 306 Compare = dyn_cast<FCmpInst>(U2); 307 if (!Compare || !Compare->hasOneUse() || 308 !isa<BranchInst>(Compare->user_back())) 309 return; 310 311 BranchInst *TheBr = cast<BranchInst>(Compare->user_back()); 312 313 // We need to verify that the branch actually controls the iteration count 314 // of the loop. If not, the new IV can overflow and no one will notice. 315 // The branch block must be in the loop and one of the successors must be out 316 // of the loop. 317 assert(TheBr->isConditional() && "Can't use fcmp if not conditional"); 318 if (!L->contains(TheBr->getParent()) || 319 (L->contains(TheBr->getSuccessor(0)) && 320 L->contains(TheBr->getSuccessor(1)))) 321 return; 322 323 324 // If it isn't a comparison with an integer-as-fp (the exit value), we can't 325 // transform it. 326 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1)); 327 int64_t ExitValue; 328 if (ExitValueVal == nullptr || 329 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue)) 330 return; 331 332 // Find new predicate for integer comparison. 333 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE; 334 switch (Compare->getPredicate()) { 335 default: return; // Unknown comparison. 336 case CmpInst::FCMP_OEQ: 337 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break; 338 case CmpInst::FCMP_ONE: 339 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break; 340 case CmpInst::FCMP_OGT: 341 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break; 342 case CmpInst::FCMP_OGE: 343 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break; 344 case CmpInst::FCMP_OLT: 345 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break; 346 case CmpInst::FCMP_OLE: 347 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break; 348 } 349 350 // We convert the floating point induction variable to a signed i32 value if 351 // we can. This is only safe if the comparison will not overflow in a way 352 // that won't be trapped by the integer equivalent operations. Check for this 353 // now. 354 // TODO: We could use i64 if it is native and the range requires it. 355 356 // The start/stride/exit values must all fit in signed i32. 357 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue)) 358 return; 359 360 // If not actually striding (add x, 0.0), avoid touching the code. 361 if (IncValue == 0) 362 return; 363 364 // Positive and negative strides have different safety conditions. 365 if (IncValue > 0) { 366 // If we have a positive stride, we require the init to be less than the 367 // exit value. 368 if (InitValue >= ExitValue) 369 return; 370 371 uint32_t Range = uint32_t(ExitValue-InitValue); 372 // Check for infinite loop, either: 373 // while (i <= Exit) or until (i > Exit) 374 if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) { 375 if (++Range == 0) return; // Range overflows. 376 } 377 378 unsigned Leftover = Range % uint32_t(IncValue); 379 380 // If this is an equality comparison, we require that the strided value 381 // exactly land on the exit value, otherwise the IV condition will wrap 382 // around and do things the fp IV wouldn't. 383 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 384 Leftover != 0) 385 return; 386 387 // If the stride would wrap around the i32 before exiting, we can't 388 // transform the IV. 389 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue) 390 return; 391 392 } else { 393 // If we have a negative stride, we require the init to be greater than the 394 // exit value. 395 if (InitValue <= ExitValue) 396 return; 397 398 uint32_t Range = uint32_t(InitValue-ExitValue); 399 // Check for infinite loop, either: 400 // while (i >= Exit) or until (i < Exit) 401 if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) { 402 if (++Range == 0) return; // Range overflows. 403 } 404 405 unsigned Leftover = Range % uint32_t(-IncValue); 406 407 // If this is an equality comparison, we require that the strided value 408 // exactly land on the exit value, otherwise the IV condition will wrap 409 // around and do things the fp IV wouldn't. 410 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 411 Leftover != 0) 412 return; 413 414 // If the stride would wrap around the i32 before exiting, we can't 415 // transform the IV. 416 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue) 417 return; 418 } 419 420 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext()); 421 422 // Insert new integer induction variable. 423 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN); 424 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue), 425 PN->getIncomingBlock(IncomingEdge)); 426 427 Value *NewAdd = 428 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue), 429 Incr->getName()+".int", Incr); 430 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge)); 431 432 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd, 433 ConstantInt::get(Int32Ty, ExitValue), 434 Compare->getName()); 435 436 // In the following deletions, PN may become dead and may be deleted. 437 // Use a WeakVH to observe whether this happens. 438 WeakVH WeakPH = PN; 439 440 // Delete the old floating point exit comparison. The branch starts using the 441 // new comparison. 442 NewCompare->takeName(Compare); 443 Compare->replaceAllUsesWith(NewCompare); 444 RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI); 445 446 // Delete the old floating point increment. 447 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType())); 448 RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI); 449 450 // If the FP induction variable still has uses, this is because something else 451 // in the loop uses its value. In order to canonicalize the induction 452 // variable, we chose to eliminate the IV and rewrite it in terms of an 453 // int->fp cast. 454 // 455 // We give preference to sitofp over uitofp because it is faster on most 456 // platforms. 457 if (WeakPH) { 458 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv", 459 PN->getParent()->getFirstInsertionPt()); 460 PN->replaceAllUsesWith(Conv); 461 RecursivelyDeleteTriviallyDeadInstructions(PN, TLI); 462 } 463 Changed = true; 464 } 465 466 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) { 467 // First step. Check to see if there are any floating-point recurrences. 468 // If there are, change them into integer recurrences, permitting analysis by 469 // the SCEV routines. 470 // 471 BasicBlock *Header = L->getHeader(); 472 473 SmallVector<WeakVH, 8> PHIs; 474 for (BasicBlock::iterator I = Header->begin(); 475 PHINode *PN = dyn_cast<PHINode>(I); ++I) 476 PHIs.push_back(PN); 477 478 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 479 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i])) 480 HandleFloatingPointIV(L, PN); 481 482 // If the loop previously had floating-point IV, ScalarEvolution 483 // may not have been able to compute a trip count. Now that we've done some 484 // re-writing, the trip count may be computable. 485 if (Changed) 486 SE->forgetLoop(L); 487 } 488 489 namespace { 490 // Collect information about PHI nodes which can be transformed in 491 // RewriteLoopExitValues. 492 struct RewritePhi { 493 PHINode *PN; 494 unsigned Ith; // Ith incoming value. 495 Value *Val; // Exit value after expansion. 496 bool HighCost; // High Cost when expansion. 497 bool SafePhi; // LCSSASafePhiForRAUW. 498 499 RewritePhi(PHINode *P, unsigned I, Value *V, bool H, bool S) 500 : PN(P), Ith(I), Val(V), HighCost(H), SafePhi(S) {} 501 }; 502 } 503 504 Value *IndVarSimplify::ExpandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S, 505 Loop *L, Instruction *InsertPt, 506 Type *ResultTy) { 507 // Before expanding S into an expensive LLVM expression, see if we can use an 508 // already existing value as the expansion for S. 509 if (Value *RetValue = Rewriter.findExistingExpansion(S, InsertPt, L)) 510 return RetValue; 511 512 // We didn't find anything, fall back to using SCEVExpander. 513 return Rewriter.expandCodeFor(S, ResultTy, InsertPt); 514 } 515 516 //===----------------------------------------------------------------------===// 517 // RewriteLoopExitValues - Optimize IV users outside the loop. 518 // As a side effect, reduces the amount of IV processing within the loop. 519 //===----------------------------------------------------------------------===// 520 521 /// RewriteLoopExitValues - Check to see if this loop has a computable 522 /// loop-invariant execution count. If so, this means that we can compute the 523 /// final value of any expressions that are recurrent in the loop, and 524 /// substitute the exit values from the loop into any instructions outside of 525 /// the loop that use the final values of the current expressions. 526 /// 527 /// This is mostly redundant with the regular IndVarSimplify activities that 528 /// happen later, except that it's more powerful in some cases, because it's 529 /// able to brute-force evaluate arbitrary instructions as long as they have 530 /// constant operands at the beginning of the loop. 531 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) { 532 // Verify the input to the pass in already in LCSSA form. 533 assert(L->isLCSSAForm(*DT)); 534 535 SmallVector<BasicBlock*, 8> ExitBlocks; 536 L->getUniqueExitBlocks(ExitBlocks); 537 538 SmallVector<RewritePhi, 8> RewritePhiSet; 539 // Find all values that are computed inside the loop, but used outside of it. 540 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 541 // the exit blocks of the loop to find them. 542 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 543 BasicBlock *ExitBB = ExitBlocks[i]; 544 545 // If there are no PHI nodes in this exit block, then no values defined 546 // inside the loop are used on this path, skip it. 547 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 548 if (!PN) continue; 549 550 unsigned NumPreds = PN->getNumIncomingValues(); 551 552 // We would like to be able to RAUW single-incoming value PHI nodes. We 553 // have to be certain this is safe even when this is an LCSSA PHI node. 554 // While the computed exit value is no longer varying in *this* loop, the 555 // exit block may be an exit block for an outer containing loop as well, 556 // the exit value may be varying in the outer loop, and thus it may still 557 // require an LCSSA PHI node. The safe case is when this is 558 // single-predecessor PHI node (LCSSA) and the exit block containing it is 559 // part of the enclosing loop, or this is the outer most loop of the nest. 560 // In either case the exit value could (at most) be varying in the same 561 // loop body as the phi node itself. Thus if it is in turn used outside of 562 // an enclosing loop it will only be via a separate LCSSA node. 563 bool LCSSASafePhiForRAUW = 564 NumPreds == 1 && 565 (!L->getParentLoop() || L->getParentLoop() == LI->getLoopFor(ExitBB)); 566 567 // Iterate over all of the PHI nodes. 568 BasicBlock::iterator BBI = ExitBB->begin(); 569 while ((PN = dyn_cast<PHINode>(BBI++))) { 570 if (PN->use_empty()) 571 continue; // dead use, don't replace it 572 573 // SCEV only supports integer expressions for now. 574 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy()) 575 continue; 576 577 // It's necessary to tell ScalarEvolution about this explicitly so that 578 // it can walk the def-use list and forget all SCEVs, as it may not be 579 // watching the PHI itself. Once the new exit value is in place, there 580 // may not be a def-use connection between the loop and every instruction 581 // which got a SCEVAddRecExpr for that loop. 582 SE->forgetValue(PN); 583 584 // Iterate over all of the values in all the PHI nodes. 585 for (unsigned i = 0; i != NumPreds; ++i) { 586 // If the value being merged in is not integer or is not defined 587 // in the loop, skip it. 588 Value *InVal = PN->getIncomingValue(i); 589 if (!isa<Instruction>(InVal)) 590 continue; 591 592 // If this pred is for a subloop, not L itself, skip it. 593 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 594 continue; // The Block is in a subloop, skip it. 595 596 // Check that InVal is defined in the loop. 597 Instruction *Inst = cast<Instruction>(InVal); 598 if (!L->contains(Inst)) 599 continue; 600 601 // Okay, this instruction has a user outside of the current loop 602 // and varies predictably *inside* the loop. Evaluate the value it 603 // contains when the loop exits, if possible. 604 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 605 if (!SE->isLoopInvariant(ExitValue, L) || 606 !isSafeToExpand(ExitValue, *SE)) 607 continue; 608 609 // Computing the value outside of the loop brings no benefit if : 610 // - it is definitely used inside the loop in a way which can not be 611 // optimized away. 612 // - no use outside of the loop can take advantage of hoisting the 613 // computation out of the loop 614 if (ExitValue->getSCEVType()>=scMulExpr) { 615 unsigned NumHardInternalUses = 0; 616 unsigned NumSoftExternalUses = 0; 617 unsigned NumUses = 0; 618 for (auto IB = Inst->user_begin(), IE = Inst->user_end(); 619 IB != IE && NumUses <= 6; ++IB) { 620 Instruction *UseInstr = cast<Instruction>(*IB); 621 unsigned Opc = UseInstr->getOpcode(); 622 NumUses++; 623 if (L->contains(UseInstr)) { 624 if (Opc == Instruction::Call || Opc == Instruction::Ret) 625 NumHardInternalUses++; 626 } else { 627 if (Opc == Instruction::PHI) { 628 // Do not count the Phi as a use. LCSSA may have inserted 629 // plenty of trivial ones. 630 NumUses--; 631 for (auto PB = UseInstr->user_begin(), 632 PE = UseInstr->user_end(); 633 PB != PE && NumUses <= 6; ++PB, ++NumUses) { 634 unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode(); 635 if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret) 636 NumSoftExternalUses++; 637 } 638 continue; 639 } 640 if (Opc != Instruction::Call && Opc != Instruction::Ret) 641 NumSoftExternalUses++; 642 } 643 } 644 if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses) 645 continue; 646 } 647 648 bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst); 649 Value *ExitVal = 650 ExpandSCEVIfNeeded(Rewriter, ExitValue, L, Inst, PN->getType()); 651 652 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n' 653 << " LoopVal = " << *Inst << "\n"); 654 655 if (!isValidRewrite(Inst, ExitVal)) { 656 DeadInsts.push_back(ExitVal); 657 continue; 658 } 659 660 // Collect all the candidate PHINodes to be rewritten. 661 RewritePhiSet.push_back( 662 RewritePhi(PN, i, ExitVal, HighCost, LCSSASafePhiForRAUW)); 663 } 664 } 665 } 666 667 bool LoopCanBeDel = CanLoopBeDeleted(L, RewritePhiSet); 668 669 // Transformation. 670 for (const RewritePhi &Phi : RewritePhiSet) { 671 PHINode *PN = Phi.PN; 672 Value *ExitVal = Phi.Val; 673 674 // Only do the rewrite when the ExitValue can be expanded cheaply. 675 // If LoopCanBeDel is true, rewrite exit value aggressively. 676 if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) { 677 DeadInsts.push_back(ExitVal); 678 continue; 679 } 680 681 Changed = true; 682 ++NumReplaced; 683 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith)); 684 PN->setIncomingValue(Phi.Ith, ExitVal); 685 686 // If this instruction is dead now, delete it. Don't do it now to avoid 687 // invalidating iterators. 688 if (isInstructionTriviallyDead(Inst, TLI)) 689 DeadInsts.push_back(Inst); 690 691 // If we determined that this PHI is safe to replace even if an LCSSA 692 // PHI, do so. 693 if (Phi.SafePhi) { 694 PN->replaceAllUsesWith(ExitVal); 695 PN->eraseFromParent(); 696 } 697 } 698 699 // The insertion point instruction may have been deleted; clear it out 700 // so that the rewriter doesn't trip over it later. 701 Rewriter.clearInsertPoint(); 702 } 703 704 /// CanLoopBeDeleted - Check whether it is possible to delete the loop after 705 /// rewriting exit value. If it is possible, ignore ReplaceExitValue and 706 /// do rewriting aggressively. 707 bool IndVarSimplify::CanLoopBeDeleted( 708 Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) { 709 710 BasicBlock *Preheader = L->getLoopPreheader(); 711 // If there is no preheader, the loop will not be deleted. 712 if (!Preheader) 713 return false; 714 715 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1. 716 // We obviate multiple ExitingBlocks case for simplicity. 717 // TODO: If we see testcase with multiple ExitingBlocks can be deleted 718 // after exit value rewriting, we can enhance the logic here. 719 SmallVector<BasicBlock *, 4> ExitingBlocks; 720 L->getExitingBlocks(ExitingBlocks); 721 SmallVector<BasicBlock *, 8> ExitBlocks; 722 L->getUniqueExitBlocks(ExitBlocks); 723 if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1) 724 return false; 725 726 BasicBlock *ExitBlock = ExitBlocks[0]; 727 BasicBlock::iterator BI = ExitBlock->begin(); 728 while (PHINode *P = dyn_cast<PHINode>(BI)) { 729 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 730 731 // If the Incoming value of P is found in RewritePhiSet, we know it 732 // could be rewritten to use a loop invariant value in transformation 733 // phase later. Skip it in the loop invariant check below. 734 bool found = false; 735 for (const RewritePhi &Phi : RewritePhiSet) { 736 unsigned i = Phi.Ith; 737 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) { 738 found = true; 739 break; 740 } 741 } 742 743 Instruction *I; 744 if (!found && (I = dyn_cast<Instruction>(Incoming))) 745 if (!L->hasLoopInvariantOperands(I)) 746 return false; 747 748 ++BI; 749 } 750 751 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); 752 LI != LE; ++LI) { 753 for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); BI != BE; 754 ++BI) { 755 if (BI->mayHaveSideEffects()) 756 return false; 757 } 758 } 759 760 return true; 761 } 762 763 //===----------------------------------------------------------------------===// 764 // IV Widening - Extend the width of an IV to cover its widest uses. 765 //===----------------------------------------------------------------------===// 766 767 namespace { 768 // Collect information about induction variables that are used by sign/zero 769 // extend operations. This information is recorded by CollectExtend and 770 // provides the input to WidenIV. 771 struct WideIVInfo { 772 PHINode *NarrowIV; 773 Type *WidestNativeType; // Widest integer type created [sz]ext 774 bool IsSigned; // Was a sext user seen before a zext? 775 776 WideIVInfo() : NarrowIV(nullptr), WidestNativeType(nullptr), 777 IsSigned(false) {} 778 }; 779 } 780 781 /// visitCast - Update information about the induction variable that is 782 /// extended by this sign or zero extend operation. This is used to determine 783 /// the final width of the IV before actually widening it. 784 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE, 785 const TargetTransformInfo *TTI) { 786 bool IsSigned = Cast->getOpcode() == Instruction::SExt; 787 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt) 788 return; 789 790 Type *Ty = Cast->getType(); 791 uint64_t Width = SE->getTypeSizeInBits(Ty); 792 if (!Cast->getModule()->getDataLayout().isLegalInteger(Width)) 793 return; 794 795 // Cast is either an sext or zext up to this point. 796 // We should not widen an indvar if arithmetics on the wider indvar are more 797 // expensive than those on the narrower indvar. We check only the cost of ADD 798 // because at least an ADD is required to increment the induction variable. We 799 // could compute more comprehensively the cost of all instructions on the 800 // induction variable when necessary. 801 if (TTI && 802 TTI->getArithmeticInstrCost(Instruction::Add, Ty) > 803 TTI->getArithmeticInstrCost(Instruction::Add, 804 Cast->getOperand(0)->getType())) { 805 return; 806 } 807 808 if (!WI.WidestNativeType) { 809 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); 810 WI.IsSigned = IsSigned; 811 return; 812 } 813 814 // We extend the IV to satisfy the sign of its first user, arbitrarily. 815 if (WI.IsSigned != IsSigned) 816 return; 817 818 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType)) 819 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); 820 } 821 822 namespace { 823 824 /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the 825 /// WideIV that computes the same value as the Narrow IV def. This avoids 826 /// caching Use* pointers. 827 struct NarrowIVDefUse { 828 Instruction *NarrowDef; 829 Instruction *NarrowUse; 830 Instruction *WideDef; 831 832 NarrowIVDefUse(): NarrowDef(nullptr), NarrowUse(nullptr), WideDef(nullptr) {} 833 834 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD): 835 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {} 836 }; 837 838 /// WidenIV - The goal of this transform is to remove sign and zero extends 839 /// without creating any new induction variables. To do this, it creates a new 840 /// phi of the wider type and redirects all users, either removing extends or 841 /// inserting truncs whenever we stop propagating the type. 842 /// 843 class WidenIV { 844 // Parameters 845 PHINode *OrigPhi; 846 Type *WideType; 847 bool IsSigned; 848 849 // Context 850 LoopInfo *LI; 851 Loop *L; 852 ScalarEvolution *SE; 853 DominatorTree *DT; 854 855 // Result 856 PHINode *WidePhi; 857 Instruction *WideInc; 858 const SCEV *WideIncExpr; 859 SmallVectorImpl<WeakVH> &DeadInsts; 860 861 SmallPtrSet<Instruction*,16> Widened; 862 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers; 863 864 public: 865 WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, 866 ScalarEvolution *SEv, DominatorTree *DTree, 867 SmallVectorImpl<WeakVH> &DI) : 868 OrigPhi(WI.NarrowIV), 869 WideType(WI.WidestNativeType), 870 IsSigned(WI.IsSigned), 871 LI(LInfo), 872 L(LI->getLoopFor(OrigPhi->getParent())), 873 SE(SEv), 874 DT(DTree), 875 WidePhi(nullptr), 876 WideInc(nullptr), 877 WideIncExpr(nullptr), 878 DeadInsts(DI) { 879 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV"); 880 } 881 882 PHINode *CreateWideIV(SCEVExpander &Rewriter); 883 884 protected: 885 Value *getExtend(Value *NarrowOper, Type *WideType, bool IsSigned, 886 Instruction *Use); 887 888 Instruction *CloneIVUser(NarrowIVDefUse DU); 889 890 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse); 891 892 const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU); 893 894 const SCEV *GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 895 unsigned OpCode) const; 896 897 Instruction *WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter); 898 899 bool WidenLoopCompare(NarrowIVDefUse DU); 900 901 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef); 902 }; 903 } // anonymous namespace 904 905 /// isLoopInvariant - Perform a quick domtree based check for loop invariance 906 /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems 907 /// gratuitous for this purpose. 908 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) { 909 Instruction *Inst = dyn_cast<Instruction>(V); 910 if (!Inst) 911 return true; 912 913 return DT->properlyDominates(Inst->getParent(), L->getHeader()); 914 } 915 916 Value *WidenIV::getExtend(Value *NarrowOper, Type *WideType, bool IsSigned, 917 Instruction *Use) { 918 // Set the debug location and conservative insertion point. 919 IRBuilder<> Builder(Use); 920 // Hoist the insertion point into loop preheaders as far as possible. 921 for (const Loop *L = LI->getLoopFor(Use->getParent()); 922 L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT); 923 L = L->getParentLoop()) 924 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator()); 925 926 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) : 927 Builder.CreateZExt(NarrowOper, WideType); 928 } 929 930 /// CloneIVUser - Instantiate a wide operation to replace a narrow 931 /// operation. This only needs to handle operations that can evaluation to 932 /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone. 933 Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) { 934 unsigned Opcode = DU.NarrowUse->getOpcode(); 935 switch (Opcode) { 936 default: 937 return nullptr; 938 case Instruction::Add: 939 case Instruction::Mul: 940 case Instruction::UDiv: 941 case Instruction::Sub: 942 case Instruction::And: 943 case Instruction::Or: 944 case Instruction::Xor: 945 case Instruction::Shl: 946 case Instruction::LShr: 947 case Instruction::AShr: 948 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n"); 949 950 // Replace NarrowDef operands with WideDef. Otherwise, we don't know 951 // anything about the narrow operand yet so must insert a [sz]ext. It is 952 // probably loop invariant and will be folded or hoisted. If it actually 953 // comes from a widened IV, it should be removed during a future call to 954 // WidenIVUse. 955 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef : 956 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, DU.NarrowUse); 957 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef : 958 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, DU.NarrowUse); 959 960 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse); 961 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), 962 LHS, RHS, 963 NarrowBO->getName()); 964 IRBuilder<> Builder(DU.NarrowUse); 965 Builder.Insert(WideBO); 966 if (const OverflowingBinaryOperator *OBO = 967 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) { 968 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap(); 969 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap(); 970 } 971 return WideBO; 972 } 973 } 974 975 const SCEV *WidenIV::GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 976 unsigned OpCode) const { 977 if (OpCode == Instruction::Add) 978 return SE->getAddExpr(LHS, RHS); 979 if (OpCode == Instruction::Sub) 980 return SE->getMinusSCEV(LHS, RHS); 981 if (OpCode == Instruction::Mul) 982 return SE->getMulExpr(LHS, RHS); 983 984 llvm_unreachable("Unsupported opcode."); 985 } 986 987 /// No-wrap operations can transfer sign extension of their result to their 988 /// operands. Generate the SCEV value for the widened operation without 989 /// actually modifying the IR yet. If the expression after extending the 990 /// operands is an AddRec for this loop, return it. 991 const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) { 992 993 // Handle the common case of add<nsw/nuw> 994 const unsigned OpCode = DU.NarrowUse->getOpcode(); 995 // Only Add/Sub/Mul instructions supported yet. 996 if (OpCode != Instruction::Add && OpCode != Instruction::Sub && 997 OpCode != Instruction::Mul) 998 return nullptr; 999 1000 // One operand (NarrowDef) has already been extended to WideDef. Now determine 1001 // if extending the other will lead to a recurrence. 1002 const unsigned ExtendOperIdx = 1003 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0; 1004 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU"); 1005 1006 const SCEV *ExtendOperExpr = nullptr; 1007 const OverflowingBinaryOperator *OBO = 1008 cast<OverflowingBinaryOperator>(DU.NarrowUse); 1009 if (IsSigned && OBO->hasNoSignedWrap()) 1010 ExtendOperExpr = SE->getSignExtendExpr( 1011 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 1012 else if(!IsSigned && OBO->hasNoUnsignedWrap()) 1013 ExtendOperExpr = SE->getZeroExtendExpr( 1014 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 1015 else 1016 return nullptr; 1017 1018 // When creating this SCEV expr, don't apply the current operations NSW or NUW 1019 // flags. This instruction may be guarded by control flow that the no-wrap 1020 // behavior depends on. Non-control-equivalent instructions can be mapped to 1021 // the same SCEV expression, and it would be incorrect to transfer NSW/NUW 1022 // semantics to those operations. 1023 const SCEV *lhs = SE->getSCEV(DU.WideDef); 1024 const SCEV *rhs = ExtendOperExpr; 1025 1026 // Let's swap operands to the initial order for the case of non-commutative 1027 // operations, like SUB. See PR21014. 1028 if (ExtendOperIdx == 0) 1029 std::swap(lhs, rhs); 1030 const SCEVAddRecExpr *AddRec = 1031 dyn_cast<SCEVAddRecExpr>(GetSCEVByOpCode(lhs, rhs, OpCode)); 1032 1033 if (!AddRec || AddRec->getLoop() != L) 1034 return nullptr; 1035 return AddRec; 1036 } 1037 1038 /// GetWideRecurrence - Is this instruction potentially interesting for further 1039 /// simplification after widening it's type? In other words, can the 1040 /// extend be safely hoisted out of the loop with SCEV reducing the value to a 1041 /// recurrence on the same loop. If so, return the sign or zero extended 1042 /// recurrence. Otherwise return NULL. 1043 const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) { 1044 if (!SE->isSCEVable(NarrowUse->getType())) 1045 return nullptr; 1046 1047 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse); 1048 if (SE->getTypeSizeInBits(NarrowExpr->getType()) 1049 >= SE->getTypeSizeInBits(WideType)) { 1050 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow 1051 // index. So don't follow this use. 1052 return nullptr; 1053 } 1054 1055 const SCEV *WideExpr = IsSigned ? 1056 SE->getSignExtendExpr(NarrowExpr, WideType) : 1057 SE->getZeroExtendExpr(NarrowExpr, WideType); 1058 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr); 1059 if (!AddRec || AddRec->getLoop() != L) 1060 return nullptr; 1061 return AddRec; 1062 } 1063 1064 /// This IV user cannot be widen. Replace this use of the original narrow IV 1065 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV. 1066 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT) { 1067 DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef 1068 << " for user " << *DU.NarrowUse << "\n"); 1069 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT)); 1070 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType()); 1071 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc); 1072 } 1073 1074 /// If the narrow use is a compare instruction, then widen the compare 1075 // (and possibly the other operand). The extend operation is hoisted into the 1076 // loop preheader as far as possible. 1077 bool WidenIV::WidenLoopCompare(NarrowIVDefUse DU) { 1078 ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse); 1079 if (!Cmp) 1080 return false; 1081 1082 // Sign of IV user and compare must match. 1083 if (IsSigned != CmpInst::isSigned(Cmp->getPredicate())) 1084 return false; 1085 1086 Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0); 1087 unsigned CastWidth = SE->getTypeSizeInBits(Op->getType()); 1088 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1089 assert (CastWidth <= IVWidth && "Unexpected width while widening compare."); 1090 1091 // Widen the compare instruction. 1092 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT)); 1093 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1094 1095 // Widen the other operand of the compare, if necessary. 1096 if (CastWidth < IVWidth) { 1097 Value *ExtOp = getExtend(Op, WideType, IsSigned, Cmp); 1098 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp); 1099 } 1100 return true; 1101 } 1102 1103 /// WidenIVUse - Determine whether an individual user of the narrow IV can be 1104 /// widened. If so, return the wide clone of the user. 1105 Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) { 1106 1107 // Stop traversing the def-use chain at inner-loop phis or post-loop phis. 1108 if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) { 1109 if (LI->getLoopFor(UsePhi->getParent()) != L) { 1110 // For LCSSA phis, sink the truncate outside the loop. 1111 // After SimplifyCFG most loop exit targets have a single predecessor. 1112 // Otherwise fall back to a truncate within the loop. 1113 if (UsePhi->getNumOperands() != 1) 1114 truncateIVUse(DU, DT); 1115 else { 1116 PHINode *WidePhi = 1117 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide", 1118 UsePhi); 1119 WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0)); 1120 IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt()); 1121 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType()); 1122 UsePhi->replaceAllUsesWith(Trunc); 1123 DeadInsts.emplace_back(UsePhi); 1124 DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi 1125 << " to " << *WidePhi << "\n"); 1126 } 1127 return nullptr; 1128 } 1129 } 1130 // Our raison d'etre! Eliminate sign and zero extension. 1131 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) { 1132 Value *NewDef = DU.WideDef; 1133 if (DU.NarrowUse->getType() != WideType) { 1134 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType()); 1135 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1136 if (CastWidth < IVWidth) { 1137 // The cast isn't as wide as the IV, so insert a Trunc. 1138 IRBuilder<> Builder(DU.NarrowUse); 1139 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType()); 1140 } 1141 else { 1142 // A wider extend was hidden behind a narrower one. This may induce 1143 // another round of IV widening in which the intermediate IV becomes 1144 // dead. It should be very rare. 1145 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi 1146 << " not wide enough to subsume " << *DU.NarrowUse << "\n"); 1147 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1148 NewDef = DU.NarrowUse; 1149 } 1150 } 1151 if (NewDef != DU.NarrowUse) { 1152 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse 1153 << " replaced by " << *DU.WideDef << "\n"); 1154 ++NumElimExt; 1155 DU.NarrowUse->replaceAllUsesWith(NewDef); 1156 DeadInsts.emplace_back(DU.NarrowUse); 1157 } 1158 // Now that the extend is gone, we want to expose it's uses for potential 1159 // further simplification. We don't need to directly inform SimplifyIVUsers 1160 // of the new users, because their parent IV will be processed later as a 1161 // new loop phi. If we preserved IVUsers analysis, we would also want to 1162 // push the uses of WideDef here. 1163 1164 // No further widening is needed. The deceased [sz]ext had done it for us. 1165 return nullptr; 1166 } 1167 1168 // Does this user itself evaluate to a recurrence after widening? 1169 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse); 1170 if (!WideAddRec) 1171 WideAddRec = GetExtendedOperandRecurrence(DU); 1172 1173 if (!WideAddRec) { 1174 // If use is a loop condition, try to promote the condition instead of 1175 // truncating the IV first. 1176 if (WidenLoopCompare(DU)) 1177 return nullptr; 1178 1179 // This user does not evaluate to a recurence after widening, so don't 1180 // follow it. Instead insert a Trunc to kill off the original use, 1181 // eventually isolating the original narrow IV so it can be removed. 1182 truncateIVUse(DU, DT); 1183 return nullptr; 1184 } 1185 // Assume block terminators cannot evaluate to a recurrence. We can't to 1186 // insert a Trunc after a terminator if there happens to be a critical edge. 1187 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() && 1188 "SCEV is not expected to evaluate a block terminator"); 1189 1190 // Reuse the IV increment that SCEVExpander created as long as it dominates 1191 // NarrowUse. 1192 Instruction *WideUse = nullptr; 1193 if (WideAddRec == WideIncExpr 1194 && Rewriter.hoistIVInc(WideInc, DU.NarrowUse)) 1195 WideUse = WideInc; 1196 else { 1197 WideUse = CloneIVUser(DU); 1198 if (!WideUse) 1199 return nullptr; 1200 } 1201 // Evaluation of WideAddRec ensured that the narrow expression could be 1202 // extended outside the loop without overflow. This suggests that the wide use 1203 // evaluates to the same expression as the extended narrow use, but doesn't 1204 // absolutely guarantee it. Hence the following failsafe check. In rare cases 1205 // where it fails, we simply throw away the newly created wide use. 1206 if (WideAddRec != SE->getSCEV(WideUse)) { 1207 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse 1208 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n"); 1209 DeadInsts.emplace_back(WideUse); 1210 return nullptr; 1211 } 1212 1213 // Returning WideUse pushes it on the worklist. 1214 return WideUse; 1215 } 1216 1217 /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers. 1218 /// 1219 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) { 1220 for (User *U : NarrowDef->users()) { 1221 Instruction *NarrowUser = cast<Instruction>(U); 1222 1223 // Handle data flow merges and bizarre phi cycles. 1224 if (!Widened.insert(NarrowUser).second) 1225 continue; 1226 1227 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUser, WideDef)); 1228 } 1229 } 1230 1231 /// CreateWideIV - Process a single induction variable. First use the 1232 /// SCEVExpander to create a wide induction variable that evaluates to the same 1233 /// recurrence as the original narrow IV. Then use a worklist to forward 1234 /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all 1235 /// interesting IV users, the narrow IV will be isolated for removal by 1236 /// DeleteDeadPHIs. 1237 /// 1238 /// It would be simpler to delete uses as they are processed, but we must avoid 1239 /// invalidating SCEV expressions. 1240 /// 1241 PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) { 1242 // Is this phi an induction variable? 1243 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi)); 1244 if (!AddRec) 1245 return nullptr; 1246 1247 // Widen the induction variable expression. 1248 const SCEV *WideIVExpr = IsSigned ? 1249 SE->getSignExtendExpr(AddRec, WideType) : 1250 SE->getZeroExtendExpr(AddRec, WideType); 1251 1252 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType && 1253 "Expect the new IV expression to preserve its type"); 1254 1255 // Can the IV be extended outside the loop without overflow? 1256 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr); 1257 if (!AddRec || AddRec->getLoop() != L) 1258 return nullptr; 1259 1260 // An AddRec must have loop-invariant operands. Since this AddRec is 1261 // materialized by a loop header phi, the expression cannot have any post-loop 1262 // operands, so they must dominate the loop header. 1263 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) && 1264 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) 1265 && "Loop header phi recurrence inputs do not dominate the loop"); 1266 1267 // The rewriter provides a value for the desired IV expression. This may 1268 // either find an existing phi or materialize a new one. Either way, we 1269 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part 1270 // of the phi-SCC dominates the loop entry. 1271 Instruction *InsertPt = L->getHeader()->begin(); 1272 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt)); 1273 1274 // Remembering the WideIV increment generated by SCEVExpander allows 1275 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't 1276 // employ a general reuse mechanism because the call above is the only call to 1277 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses. 1278 if (BasicBlock *LatchBlock = L->getLoopLatch()) { 1279 WideInc = 1280 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock)); 1281 WideIncExpr = SE->getSCEV(WideInc); 1282 } 1283 1284 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n"); 1285 ++NumWidened; 1286 1287 // Traverse the def-use chain using a worklist starting at the original IV. 1288 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" ); 1289 1290 Widened.insert(OrigPhi); 1291 pushNarrowIVUsers(OrigPhi, WidePhi); 1292 1293 while (!NarrowIVUsers.empty()) { 1294 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val(); 1295 1296 // Process a def-use edge. This may replace the use, so don't hold a 1297 // use_iterator across it. 1298 Instruction *WideUse = WidenIVUse(DU, Rewriter); 1299 1300 // Follow all def-use edges from the previous narrow use. 1301 if (WideUse) 1302 pushNarrowIVUsers(DU.NarrowUse, WideUse); 1303 1304 // WidenIVUse may have removed the def-use edge. 1305 if (DU.NarrowDef->use_empty()) 1306 DeadInsts.emplace_back(DU.NarrowDef); 1307 } 1308 return WidePhi; 1309 } 1310 1311 //===----------------------------------------------------------------------===// 1312 // Live IV Reduction - Minimize IVs live across the loop. 1313 //===----------------------------------------------------------------------===// 1314 1315 1316 //===----------------------------------------------------------------------===// 1317 // Simplification of IV users based on SCEV evaluation. 1318 //===----------------------------------------------------------------------===// 1319 1320 namespace { 1321 class IndVarSimplifyVisitor : public IVVisitor { 1322 ScalarEvolution *SE; 1323 const TargetTransformInfo *TTI; 1324 PHINode *IVPhi; 1325 1326 public: 1327 WideIVInfo WI; 1328 1329 IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV, 1330 const TargetTransformInfo *TTI, 1331 const DominatorTree *DTree) 1332 : SE(SCEV), TTI(TTI), IVPhi(IV) { 1333 DT = DTree; 1334 WI.NarrowIV = IVPhi; 1335 if (ReduceLiveIVs) 1336 setSplitOverflowIntrinsics(); 1337 } 1338 1339 // Implement the interface used by simplifyUsersOfIV. 1340 void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); } 1341 }; 1342 } 1343 1344 /// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV 1345 /// users. Each successive simplification may push more users which may 1346 /// themselves be candidates for simplification. 1347 /// 1348 /// Sign/Zero extend elimination is interleaved with IV simplification. 1349 /// 1350 void IndVarSimplify::SimplifyAndExtend(Loop *L, 1351 SCEVExpander &Rewriter, 1352 LPPassManager &LPM) { 1353 SmallVector<WideIVInfo, 8> WideIVs; 1354 1355 SmallVector<PHINode*, 8> LoopPhis; 1356 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 1357 LoopPhis.push_back(cast<PHINode>(I)); 1358 } 1359 // Each round of simplification iterates through the SimplifyIVUsers worklist 1360 // for all current phis, then determines whether any IVs can be 1361 // widened. Widening adds new phis to LoopPhis, inducing another round of 1362 // simplification on the wide IVs. 1363 while (!LoopPhis.empty()) { 1364 // Evaluate as many IV expressions as possible before widening any IVs. This 1365 // forces SCEV to set no-wrap flags before evaluating sign/zero 1366 // extension. The first time SCEV attempts to normalize sign/zero extension, 1367 // the result becomes final. So for the most predictable results, we delay 1368 // evaluation of sign/zero extend evaluation until needed, and avoid running 1369 // other SCEV based analysis prior to SimplifyAndExtend. 1370 do { 1371 PHINode *CurrIV = LoopPhis.pop_back_val(); 1372 1373 // Information about sign/zero extensions of CurrIV. 1374 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT); 1375 1376 Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &Visitor); 1377 1378 if (Visitor.WI.WidestNativeType) { 1379 WideIVs.push_back(Visitor.WI); 1380 } 1381 } while(!LoopPhis.empty()); 1382 1383 for (; !WideIVs.empty(); WideIVs.pop_back()) { 1384 WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts); 1385 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) { 1386 Changed = true; 1387 LoopPhis.push_back(WidePhi); 1388 } 1389 } 1390 } 1391 } 1392 1393 //===----------------------------------------------------------------------===// 1394 // LinearFunctionTestReplace and its kin. Rewrite the loop exit condition. 1395 //===----------------------------------------------------------------------===// 1396 1397 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken 1398 /// count expression can be safely and cheaply expanded into an instruction 1399 /// sequence that can be used by LinearFunctionTestReplace. 1400 /// 1401 /// TODO: This fails for pointer-type loop counters with greater than one byte 1402 /// strides, consequently preventing LFTR from running. For the purpose of LFTR 1403 /// we could skip this check in the case that the LFTR loop counter (chosen by 1404 /// FindLoopCounter) is also pointer type. Instead, we could directly convert 1405 /// the loop test to an inequality test by checking the target data's alignment 1406 /// of element types (given that the initial pointer value originates from or is 1407 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint). 1408 /// However, we don't yet have a strong motivation for converting loop tests 1409 /// into inequality tests. 1410 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE, 1411 SCEVExpander &Rewriter) { 1412 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 1413 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) || 1414 BackedgeTakenCount->isZero()) 1415 return false; 1416 1417 if (!L->getExitingBlock()) 1418 return false; 1419 1420 // Can't rewrite non-branch yet. 1421 if (!isa<BranchInst>(L->getExitingBlock()->getTerminator())) 1422 return false; 1423 1424 if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L)) 1425 return false; 1426 1427 return true; 1428 } 1429 1430 /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop 1431 /// invariant value to the phi. 1432 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) { 1433 Instruction *IncI = dyn_cast<Instruction>(IncV); 1434 if (!IncI) 1435 return nullptr; 1436 1437 switch (IncI->getOpcode()) { 1438 case Instruction::Add: 1439 case Instruction::Sub: 1440 break; 1441 case Instruction::GetElementPtr: 1442 // An IV counter must preserve its type. 1443 if (IncI->getNumOperands() == 2) 1444 break; 1445 default: 1446 return nullptr; 1447 } 1448 1449 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0)); 1450 if (Phi && Phi->getParent() == L->getHeader()) { 1451 if (isLoopInvariant(IncI->getOperand(1), L, DT)) 1452 return Phi; 1453 return nullptr; 1454 } 1455 if (IncI->getOpcode() == Instruction::GetElementPtr) 1456 return nullptr; 1457 1458 // Allow add/sub to be commuted. 1459 Phi = dyn_cast<PHINode>(IncI->getOperand(1)); 1460 if (Phi && Phi->getParent() == L->getHeader()) { 1461 if (isLoopInvariant(IncI->getOperand(0), L, DT)) 1462 return Phi; 1463 } 1464 return nullptr; 1465 } 1466 1467 /// Return the compare guarding the loop latch, or NULL for unrecognized tests. 1468 static ICmpInst *getLoopTest(Loop *L) { 1469 assert(L->getExitingBlock() && "expected loop exit"); 1470 1471 BasicBlock *LatchBlock = L->getLoopLatch(); 1472 // Don't bother with LFTR if the loop is not properly simplified. 1473 if (!LatchBlock) 1474 return nullptr; 1475 1476 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1477 assert(BI && "expected exit branch"); 1478 1479 return dyn_cast<ICmpInst>(BI->getCondition()); 1480 } 1481 1482 /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show 1483 /// that the current exit test is already sufficiently canonical. 1484 static bool needsLFTR(Loop *L, DominatorTree *DT) { 1485 // Do LFTR to simplify the exit condition to an ICMP. 1486 ICmpInst *Cond = getLoopTest(L); 1487 if (!Cond) 1488 return true; 1489 1490 // Do LFTR to simplify the exit ICMP to EQ/NE 1491 ICmpInst::Predicate Pred = Cond->getPredicate(); 1492 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ) 1493 return true; 1494 1495 // Look for a loop invariant RHS 1496 Value *LHS = Cond->getOperand(0); 1497 Value *RHS = Cond->getOperand(1); 1498 if (!isLoopInvariant(RHS, L, DT)) { 1499 if (!isLoopInvariant(LHS, L, DT)) 1500 return true; 1501 std::swap(LHS, RHS); 1502 } 1503 // Look for a simple IV counter LHS 1504 PHINode *Phi = dyn_cast<PHINode>(LHS); 1505 if (!Phi) 1506 Phi = getLoopPhiForCounter(LHS, L, DT); 1507 1508 if (!Phi) 1509 return true; 1510 1511 // Do LFTR if PHI node is defined in the loop, but is *not* a counter. 1512 int Idx = Phi->getBasicBlockIndex(L->getLoopLatch()); 1513 if (Idx < 0) 1514 return true; 1515 1516 // Do LFTR if the exit condition's IV is *not* a simple counter. 1517 Value *IncV = Phi->getIncomingValue(Idx); 1518 return Phi != getLoopPhiForCounter(IncV, L, DT); 1519 } 1520 1521 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils 1522 /// down to checking that all operands are constant and listing instructions 1523 /// that may hide undef. 1524 static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited, 1525 unsigned Depth) { 1526 if (isa<Constant>(V)) 1527 return !isa<UndefValue>(V); 1528 1529 if (Depth >= 6) 1530 return false; 1531 1532 // Conservatively handle non-constant non-instructions. For example, Arguments 1533 // may be undef. 1534 Instruction *I = dyn_cast<Instruction>(V); 1535 if (!I) 1536 return false; 1537 1538 // Load and return values may be undef. 1539 if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I)) 1540 return false; 1541 1542 // Optimistically handle other instructions. 1543 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) { 1544 if (!Visited.insert(*OI).second) 1545 continue; 1546 if (!hasConcreteDefImpl(*OI, Visited, Depth+1)) 1547 return false; 1548 } 1549 return true; 1550 } 1551 1552 /// Return true if the given value is concrete. We must prove that undef can 1553 /// never reach it. 1554 /// 1555 /// TODO: If we decide that this is a good approach to checking for undef, we 1556 /// may factor it into a common location. 1557 static bool hasConcreteDef(Value *V) { 1558 SmallPtrSet<Value*, 8> Visited; 1559 Visited.insert(V); 1560 return hasConcreteDefImpl(V, Visited, 0); 1561 } 1562 1563 /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to 1564 /// be rewritten) loop exit test. 1565 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) { 1566 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); 1567 Value *IncV = Phi->getIncomingValue(LatchIdx); 1568 1569 for (User *U : Phi->users()) 1570 if (U != Cond && U != IncV) return false; 1571 1572 for (User *U : IncV->users()) 1573 if (U != Cond && U != Phi) return false; 1574 return true; 1575 } 1576 1577 /// FindLoopCounter - Find an affine IV in canonical form. 1578 /// 1579 /// BECount may be an i8* pointer type. The pointer difference is already 1580 /// valid count without scaling the address stride, so it remains a pointer 1581 /// expression as far as SCEV is concerned. 1582 /// 1583 /// Currently only valid for LFTR. See the comments on hasConcreteDef below. 1584 /// 1585 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount 1586 /// 1587 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride. 1588 /// This is difficult in general for SCEV because of potential overflow. But we 1589 /// could at least handle constant BECounts. 1590 static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount, 1591 ScalarEvolution *SE, DominatorTree *DT) { 1592 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType()); 1593 1594 Value *Cond = 1595 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition(); 1596 1597 // Loop over all of the PHI nodes, looking for a simple counter. 1598 PHINode *BestPhi = nullptr; 1599 const SCEV *BestInit = nullptr; 1600 BasicBlock *LatchBlock = L->getLoopLatch(); 1601 assert(LatchBlock && "needsLFTR should guarantee a loop latch"); 1602 1603 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 1604 PHINode *Phi = cast<PHINode>(I); 1605 if (!SE->isSCEVable(Phi->getType())) 1606 continue; 1607 1608 // Avoid comparing an integer IV against a pointer Limit. 1609 if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy()) 1610 continue; 1611 1612 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi)); 1613 if (!AR || AR->getLoop() != L || !AR->isAffine()) 1614 continue; 1615 1616 // AR may be a pointer type, while BECount is an integer type. 1617 // AR may be wider than BECount. With eq/ne tests overflow is immaterial. 1618 // AR may not be a narrower type, or we may never exit. 1619 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType()); 1620 if (PhiWidth < BCWidth || 1621 !L->getHeader()->getModule()->getDataLayout().isLegalInteger(PhiWidth)) 1622 continue; 1623 1624 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)); 1625 if (!Step || !Step->isOne()) 1626 continue; 1627 1628 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); 1629 Value *IncV = Phi->getIncomingValue(LatchIdx); 1630 if (getLoopPhiForCounter(IncV, L, DT) != Phi) 1631 continue; 1632 1633 // Avoid reusing a potentially undef value to compute other values that may 1634 // have originally had a concrete definition. 1635 if (!hasConcreteDef(Phi)) { 1636 // We explicitly allow unknown phis as long as they are already used by 1637 // the loop test. In this case we assume that performing LFTR could not 1638 // increase the number of undef users. 1639 if (ICmpInst *Cond = getLoopTest(L)) { 1640 if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT) 1641 && Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) { 1642 continue; 1643 } 1644 } 1645 } 1646 const SCEV *Init = AR->getStart(); 1647 1648 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) { 1649 // Don't force a live loop counter if another IV can be used. 1650 if (AlmostDeadIV(Phi, LatchBlock, Cond)) 1651 continue; 1652 1653 // Prefer to count-from-zero. This is a more "canonical" counter form. It 1654 // also prefers integer to pointer IVs. 1655 if (BestInit->isZero() != Init->isZero()) { 1656 if (BestInit->isZero()) 1657 continue; 1658 } 1659 // If two IVs both count from zero or both count from nonzero then the 1660 // narrower is likely a dead phi that has been widened. Use the wider phi 1661 // to allow the other to be eliminated. 1662 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType())) 1663 continue; 1664 } 1665 BestPhi = Phi; 1666 BestInit = Init; 1667 } 1668 return BestPhi; 1669 } 1670 1671 /// genLoopLimit - Help LinearFunctionTestReplace by generating a value that 1672 /// holds the RHS of the new loop test. 1673 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L, 1674 SCEVExpander &Rewriter, ScalarEvolution *SE) { 1675 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar)); 1676 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter"); 1677 const SCEV *IVInit = AR->getStart(); 1678 1679 // IVInit may be a pointer while IVCount is an integer when FindLoopCounter 1680 // finds a valid pointer IV. Sign extend BECount in order to materialize a 1681 // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing 1682 // the existing GEPs whenever possible. 1683 if (IndVar->getType()->isPointerTy() 1684 && !IVCount->getType()->isPointerTy()) { 1685 1686 // IVOffset will be the new GEP offset that is interpreted by GEP as a 1687 // signed value. IVCount on the other hand represents the loop trip count, 1688 // which is an unsigned value. FindLoopCounter only allows induction 1689 // variables that have a positive unit stride of one. This means we don't 1690 // have to handle the case of negative offsets (yet) and just need to zero 1691 // extend IVCount. 1692 Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType()); 1693 const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy); 1694 1695 // Expand the code for the iteration count. 1696 assert(SE->isLoopInvariant(IVOffset, L) && 1697 "Computed iteration count is not loop invariant!"); 1698 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1699 Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI); 1700 1701 Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader()); 1702 assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter"); 1703 // We could handle pointer IVs other than i8*, but we need to compensate for 1704 // gep index scaling. See canExpandBackedgeTakenCount comments. 1705 assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()), 1706 cast<PointerType>(GEPBase->getType())->getElementType())->isOne() 1707 && "unit stride pointer IV must be i8*"); 1708 1709 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 1710 return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit"); 1711 } 1712 else { 1713 // In any other case, convert both IVInit and IVCount to integers before 1714 // comparing. This may result in SCEV expension of pointers, but in practice 1715 // SCEV will fold the pointer arithmetic away as such: 1716 // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc). 1717 // 1718 // Valid Cases: (1) both integers is most common; (2) both may be pointers 1719 // for simple memset-style loops. 1720 // 1721 // IVInit integer and IVCount pointer would only occur if a canonical IV 1722 // were generated on top of case #2, which is not expected. 1723 1724 const SCEV *IVLimit = nullptr; 1725 // For unit stride, IVCount = Start + BECount with 2's complement overflow. 1726 // For non-zero Start, compute IVCount here. 1727 if (AR->getStart()->isZero()) 1728 IVLimit = IVCount; 1729 else { 1730 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride"); 1731 const SCEV *IVInit = AR->getStart(); 1732 1733 // For integer IVs, truncate the IV before computing IVInit + BECount. 1734 if (SE->getTypeSizeInBits(IVInit->getType()) 1735 > SE->getTypeSizeInBits(IVCount->getType())) 1736 IVInit = SE->getTruncateExpr(IVInit, IVCount->getType()); 1737 1738 IVLimit = SE->getAddExpr(IVInit, IVCount); 1739 } 1740 // Expand the code for the iteration count. 1741 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1742 IRBuilder<> Builder(BI); 1743 assert(SE->isLoopInvariant(IVLimit, L) && 1744 "Computed iteration count is not loop invariant!"); 1745 // Ensure that we generate the same type as IndVar, or a smaller integer 1746 // type. In the presence of null pointer values, we have an integer type 1747 // SCEV expression (IVInit) for a pointer type IV value (IndVar). 1748 Type *LimitTy = IVCount->getType()->isPointerTy() ? 1749 IndVar->getType() : IVCount->getType(); 1750 return Rewriter.expandCodeFor(IVLimit, LimitTy, BI); 1751 } 1752 } 1753 1754 /// LinearFunctionTestReplace - This method rewrites the exit condition of the 1755 /// loop to be a canonical != comparison against the incremented loop induction 1756 /// variable. This pass is able to rewrite the exit tests of any loop where the 1757 /// SCEV analysis can determine a loop-invariant trip count of the loop, which 1758 /// is actually a much broader range than just linear tests. 1759 Value *IndVarSimplify:: 1760 LinearFunctionTestReplace(Loop *L, 1761 const SCEV *BackedgeTakenCount, 1762 PHINode *IndVar, 1763 SCEVExpander &Rewriter) { 1764 assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition"); 1765 1766 // Initialize CmpIndVar and IVCount to their preincremented values. 1767 Value *CmpIndVar = IndVar; 1768 const SCEV *IVCount = BackedgeTakenCount; 1769 1770 // If the exiting block is the same as the backedge block, we prefer to 1771 // compare against the post-incremented value, otherwise we must compare 1772 // against the preincremented value. 1773 if (L->getExitingBlock() == L->getLoopLatch()) { 1774 // Add one to the "backedge-taken" count to get the trip count. 1775 // This addition may overflow, which is valid as long as the comparison is 1776 // truncated to BackedgeTakenCount->getType(). 1777 IVCount = SE->getAddExpr(BackedgeTakenCount, 1778 SE->getConstant(BackedgeTakenCount->getType(), 1)); 1779 // The BackedgeTaken expression contains the number of times that the 1780 // backedge branches to the loop header. This is one less than the 1781 // number of times the loop executes, so use the incremented indvar. 1782 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock()); 1783 } 1784 1785 Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE); 1786 assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy() 1787 && "genLoopLimit missed a cast"); 1788 1789 // Insert a new icmp_ne or icmp_eq instruction before the branch. 1790 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1791 ICmpInst::Predicate P; 1792 if (L->contains(BI->getSuccessor(0))) 1793 P = ICmpInst::ICMP_NE; 1794 else 1795 P = ICmpInst::ICMP_EQ; 1796 1797 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n" 1798 << " LHS:" << *CmpIndVar << '\n' 1799 << " op:\t" 1800 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n" 1801 << " RHS:\t" << *ExitCnt << "\n" 1802 << " IVCount:\t" << *IVCount << "\n"); 1803 1804 IRBuilder<> Builder(BI); 1805 1806 // LFTR can ignore IV overflow and truncate to the width of 1807 // BECount. This avoids materializing the add(zext(add)) expression. 1808 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType()); 1809 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType()); 1810 if (CmpIndVarSize > ExitCntSize) { 1811 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar)); 1812 const SCEV *ARStart = AR->getStart(); 1813 const SCEV *ARStep = AR->getStepRecurrence(*SE); 1814 // For constant IVCount, avoid truncation. 1815 if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) { 1816 const APInt &Start = cast<SCEVConstant>(ARStart)->getValue()->getValue(); 1817 APInt Count = cast<SCEVConstant>(IVCount)->getValue()->getValue(); 1818 // Note that the post-inc value of BackedgeTakenCount may have overflowed 1819 // above such that IVCount is now zero. 1820 if (IVCount != BackedgeTakenCount && Count == 0) { 1821 Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize); 1822 ++Count; 1823 } 1824 else 1825 Count = Count.zext(CmpIndVarSize); 1826 APInt NewLimit; 1827 if (cast<SCEVConstant>(ARStep)->getValue()->isNegative()) 1828 NewLimit = Start - Count; 1829 else 1830 NewLimit = Start + Count; 1831 ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit); 1832 1833 DEBUG(dbgs() << " Widen RHS:\t" << *ExitCnt << "\n"); 1834 } else { 1835 CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(), 1836 "lftr.wideiv"); 1837 } 1838 } 1839 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond"); 1840 Value *OrigCond = BI->getCondition(); 1841 // It's tempting to use replaceAllUsesWith here to fully replace the old 1842 // comparison, but that's not immediately safe, since users of the old 1843 // comparison may not be dominated by the new comparison. Instead, just 1844 // update the branch to use the new comparison; in the common case this 1845 // will make old comparison dead. 1846 BI->setCondition(Cond); 1847 DeadInsts.push_back(OrigCond); 1848 1849 ++NumLFTR; 1850 Changed = true; 1851 return Cond; 1852 } 1853 1854 //===----------------------------------------------------------------------===// 1855 // SinkUnusedInvariants. A late subpass to cleanup loop preheaders. 1856 //===----------------------------------------------------------------------===// 1857 1858 /// If there's a single exit block, sink any loop-invariant values that 1859 /// were defined in the preheader but not used inside the loop into the 1860 /// exit block to reduce register pressure in the loop. 1861 void IndVarSimplify::SinkUnusedInvariants(Loop *L) { 1862 BasicBlock *ExitBlock = L->getExitBlock(); 1863 if (!ExitBlock) return; 1864 1865 BasicBlock *Preheader = L->getLoopPreheader(); 1866 if (!Preheader) return; 1867 1868 Instruction *InsertPt = ExitBlock->getFirstInsertionPt(); 1869 BasicBlock::iterator I = Preheader->getTerminator(); 1870 while (I != Preheader->begin()) { 1871 --I; 1872 // New instructions were inserted at the end of the preheader. 1873 if (isa<PHINode>(I)) 1874 break; 1875 1876 // Don't move instructions which might have side effects, since the side 1877 // effects need to complete before instructions inside the loop. Also don't 1878 // move instructions which might read memory, since the loop may modify 1879 // memory. Note that it's okay if the instruction might have undefined 1880 // behavior: LoopSimplify guarantees that the preheader dominates the exit 1881 // block. 1882 if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 1883 continue; 1884 1885 // Skip debug info intrinsics. 1886 if (isa<DbgInfoIntrinsic>(I)) 1887 continue; 1888 1889 // Skip eh pad instructions. 1890 if (I->isEHPad()) 1891 continue; 1892 1893 // Don't sink alloca: we never want to sink static alloca's out of the 1894 // entry block, and correctly sinking dynamic alloca's requires 1895 // checks for stacksave/stackrestore intrinsics. 1896 // FIXME: Refactor this check somehow? 1897 if (isa<AllocaInst>(I)) 1898 continue; 1899 1900 // Determine if there is a use in or before the loop (direct or 1901 // otherwise). 1902 bool UsedInLoop = false; 1903 for (Use &U : I->uses()) { 1904 Instruction *User = cast<Instruction>(U.getUser()); 1905 BasicBlock *UseBB = User->getParent(); 1906 if (PHINode *P = dyn_cast<PHINode>(User)) { 1907 unsigned i = 1908 PHINode::getIncomingValueNumForOperand(U.getOperandNo()); 1909 UseBB = P->getIncomingBlock(i); 1910 } 1911 if (UseBB == Preheader || L->contains(UseBB)) { 1912 UsedInLoop = true; 1913 break; 1914 } 1915 } 1916 1917 // If there is, the def must remain in the preheader. 1918 if (UsedInLoop) 1919 continue; 1920 1921 // Otherwise, sink it to the exit block. 1922 Instruction *ToMove = I; 1923 bool Done = false; 1924 1925 if (I != Preheader->begin()) { 1926 // Skip debug info intrinsics. 1927 do { 1928 --I; 1929 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin()); 1930 1931 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin()) 1932 Done = true; 1933 } else { 1934 Done = true; 1935 } 1936 1937 ToMove->moveBefore(InsertPt); 1938 if (Done) break; 1939 InsertPt = ToMove; 1940 } 1941 } 1942 1943 //===----------------------------------------------------------------------===// 1944 // IndVarSimplify driver. Manage several subpasses of IV simplification. 1945 //===----------------------------------------------------------------------===// 1946 1947 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) { 1948 if (skipOptnoneFunction(L)) 1949 return false; 1950 1951 // If LoopSimplify form is not available, stay out of trouble. Some notes: 1952 // - LSR currently only supports LoopSimplify-form loops. Indvars' 1953 // canonicalization can be a pessimization without LSR to "clean up" 1954 // afterwards. 1955 // - We depend on having a preheader; in particular, 1956 // Loop::getCanonicalInductionVariable only supports loops with preheaders, 1957 // and we're in trouble if we can't find the induction variable even when 1958 // we've manually inserted one. 1959 if (!L->isLoopSimplifyForm()) 1960 return false; 1961 1962 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1963 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1964 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1965 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 1966 TLI = TLIP ? &TLIP->getTLI() : nullptr; 1967 auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>(); 1968 TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr; 1969 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 1970 1971 DeadInsts.clear(); 1972 Changed = false; 1973 1974 // If there are any floating-point recurrences, attempt to 1975 // transform them to use integer recurrences. 1976 RewriteNonIntegerIVs(L); 1977 1978 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 1979 1980 // Create a rewriter object which we'll use to transform the code with. 1981 SCEVExpander Rewriter(*SE, DL, "indvars"); 1982 #ifndef NDEBUG 1983 Rewriter.setDebugType(DEBUG_TYPE); 1984 #endif 1985 1986 // Eliminate redundant IV users. 1987 // 1988 // Simplification works best when run before other consumers of SCEV. We 1989 // attempt to avoid evaluating SCEVs for sign/zero extend operations until 1990 // other expressions involving loop IVs have been evaluated. This helps SCEV 1991 // set no-wrap flags before normalizing sign/zero extension. 1992 Rewriter.disableCanonicalMode(); 1993 SimplifyAndExtend(L, Rewriter, LPM); 1994 1995 // Check to see if this loop has a computable loop-invariant execution count. 1996 // If so, this means that we can compute the final value of any expressions 1997 // that are recurrent in the loop, and substitute the exit values from the 1998 // loop into any instructions outside of the loop that use the final values of 1999 // the current expressions. 2000 // 2001 if (ReplaceExitValue != NeverRepl && 2002 !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 2003 RewriteLoopExitValues(L, Rewriter); 2004 2005 // Eliminate redundant IV cycles. 2006 NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts); 2007 2008 // If we have a trip count expression, rewrite the loop's exit condition 2009 // using it. We can currently only handle loops with a single exit. 2010 if (canExpandBackedgeTakenCount(L, SE, Rewriter) && needsLFTR(L, DT)) { 2011 PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT); 2012 if (IndVar) { 2013 // Check preconditions for proper SCEVExpander operation. SCEV does not 2014 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any 2015 // pass that uses the SCEVExpander must do it. This does not work well for 2016 // loop passes because SCEVExpander makes assumptions about all loops, 2017 // while LoopPassManager only forces the current loop to be simplified. 2018 // 2019 // FIXME: SCEV expansion has no way to bail out, so the caller must 2020 // explicitly check any assumptions made by SCEV. Brittle. 2021 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount); 2022 if (!AR || AR->getLoop()->getLoopPreheader()) 2023 (void)LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, 2024 Rewriter); 2025 } 2026 } 2027 // Clear the rewriter cache, because values that are in the rewriter's cache 2028 // can be deleted in the loop below, causing the AssertingVH in the cache to 2029 // trigger. 2030 Rewriter.clear(); 2031 2032 // Now that we're done iterating through lists, clean up any instructions 2033 // which are now dead. 2034 while (!DeadInsts.empty()) 2035 if (Instruction *Inst = 2036 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val())) 2037 RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI); 2038 2039 // The Rewriter may not be used from this point on. 2040 2041 // Loop-invariant instructions in the preheader that aren't used in the 2042 // loop may be sunk below the loop to reduce register pressure. 2043 SinkUnusedInvariants(L); 2044 2045 // Clean up dead instructions. 2046 Changed |= DeleteDeadPHIs(L->getHeader(), TLI); 2047 // Check a post-condition. 2048 assert(L->isLCSSAForm(*DT) && 2049 "Indvars did not leave the loop in lcssa form!"); 2050 2051 // Verify that LFTR, and any other change have not interfered with SCEV's 2052 // ability to compute trip count. 2053 #ifndef NDEBUG 2054 if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) { 2055 SE->forgetLoop(L); 2056 const SCEV *NewBECount = SE->getBackedgeTakenCount(L); 2057 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) < 2058 SE->getTypeSizeInBits(NewBECount->getType())) 2059 NewBECount = SE->getTruncateOrNoop(NewBECount, 2060 BackedgeTakenCount->getType()); 2061 else 2062 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, 2063 NewBECount->getType()); 2064 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV"); 2065 } 2066 #endif 2067 2068 return Changed; 2069 } 2070