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