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