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