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