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