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