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