blob: 21cb73cbf2651a3a70ead481dd1e75850fe77700 [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// 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 Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// 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 Gohmanea73f3c2009-06-14 22:38:41 +000020// 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 Lattner40bf8b42004-04-02 20:24:31 +000024//
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 Gohmanc2c4cbf2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000038//
39//===----------------------------------------------------------------------===//
40
Chris Lattner0e5f4992006-12-19 21:40:18 +000041#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000042#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000044#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000045#include "llvm/Instructions.h"
Devang Patel7b9f6b12010-03-15 22:23:03 +000046#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000047#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000048#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000049#include "llvm/Analysis/Dominators.h"
50#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000051#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000053#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000054#include "llvm/Support/CFG.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000055#include "llvm/Support/CommandLine.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000056#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000057#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000058#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000059#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000060#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000062#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000063using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumInserted, "Number of canonical indvars added");
67STATISTIC(NumReplaced, "Number of exit values replaced");
68STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000071 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000072 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000073 LoopInfo *LI;
74 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000075 DominatorTree *DT;
Chris Lattner15cad752003-12-23 07:47:09 +000076 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000077 public:
Devang Patel794fd752007-05-01 21:15:47 +000078
Dan Gohman5668cf72009-07-15 01:26:32 +000079 static char ID; // Pass identification, replacement for typeid
80 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000081
Dan Gohman5668cf72009-07-15 01:26:32 +000082 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000083
Dan Gohman5668cf72009-07-15 01:26:32 +000084 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<DominatorTree>();
86 AU.addRequired<LoopInfo>();
87 AU.addRequired<ScalarEvolution>();
88 AU.addRequiredID(LoopSimplifyID);
89 AU.addRequiredID(LCSSAID);
90 AU.addRequired<IVUsers>();
91 AU.addPreserved<ScalarEvolution>();
92 AU.addPreservedID(LoopSimplifyID);
93 AU.addPreservedID(LCSSAID);
94 AU.addPreserved<IVUsers>();
95 AU.setPreservesCFG();
96 }
Chris Lattner15cad752003-12-23 07:47:09 +000097
Chris Lattner40bf8b42004-04-02 20:24:31 +000098 private:
Devang Patel5ee99972007-03-07 06:39:01 +000099
Dan Gohman931e3452010-04-12 02:21:50 +0000100 void EliminateIVComparisons();
Dan Gohmana590b792010-04-13 01:46:36 +0000101 void EliminateIVRemainders();
Dan Gohman60f8a632009-02-17 20:49:49 +0000102 void RewriteNonIntegerIVs(Loop *L);
103
Dan Gohman0bba49c2009-07-07 17:06:11 +0000104 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +0000105 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000106 BasicBlock *ExitingBlock,
107 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000108 SCEVExpander &Rewriter);
Dan Gohman454d26d2010-02-22 04:11:59 +0000109 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000110
Dan Gohman454d26d2010-02-22 04:11:59 +0000111 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000112
Dan Gohman667d7872009-06-26 22:53:46 +0000113 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000114
115 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000116 };
Chris Lattner5e761402002-09-10 05:24:05 +0000117}
Chris Lattner394437f2001-12-04 04:32:29 +0000118
Dan Gohman844731a2008-05-13 00:00:25 +0000119char IndVarSimplify::ID = 0;
120static RegisterPass<IndVarSimplify>
121X("indvars", "Canonicalize Induction Variables");
122
Daniel Dunbar394f0442008-10-22 23:32:42 +0000123Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000124 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000125}
126
Chris Lattner40bf8b42004-04-02 20:24:31 +0000127/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000128/// loop to be a canonical != comparison against the incremented loop induction
129/// variable. This pass is able to rewrite the exit tests of any loop where the
130/// SCEV analysis can determine a loop-invariant trip count of the loop, which
131/// is actually a much broader range than just linear tests.
Dan Gohman81db61a2009-05-12 02:17:14 +0000132ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman0bba49c2009-07-07 17:06:11 +0000133 const SCEV *BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000134 Value *IndVar,
135 BasicBlock *ExitingBlock,
136 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000137 SCEVExpander &Rewriter) {
Dan Gohmanca9b7032010-04-12 21:13:43 +0000138 // Special case: If the backedge-taken count is a UDiv, it's very likely a
139 // UDiv that ScalarEvolution produced in order to compute a precise
140 // expression, rather than a UDiv from the user's code. If we can't find a
141 // UDiv in the code with some simple searching, assume the former and forego
142 // rewriting the loop.
143 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
144 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
145 if (!OrigCond) return 0;
146 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
147 R = SE->getMinusSCEV(R, SE->getIntegerSCEV(1, R->getType()));
148 if (R != BackedgeTakenCount) {
149 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
150 L = SE->getMinusSCEV(L, SE->getIntegerSCEV(1, L->getType()));
151 if (L != BackedgeTakenCount)
152 return 0;
153 }
154 }
155
Chris Lattnerd2440572004-04-15 20:26:22 +0000156 // If the exiting block is not the same as the backedge block, we must compare
157 // against the preincremented value, otherwise we prefer to compare against
158 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000159 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000160 const SCEV *RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000161 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000162 // Add one to the "backedge-taken" count to get the trip count.
163 // If this addition may overflow, we have to be more pessimistic and
164 // cast the induction variable before doing the add.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000165 const SCEV *Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
166 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000167 SE->getAddExpr(BackedgeTakenCount,
168 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000169 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000170 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000171 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000172 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000173 } else {
174 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000175 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
176 IndVar->getType());
177 RHS = SE->getAddExpr(RHS,
178 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000179 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000180
Dan Gohman46bdfb02009-02-24 18:55:53 +0000181 // The BackedgeTaken expression contains the number of times that the
182 // backedge branches to the loop header. This is one less than the
183 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000184 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000185 } else {
186 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000187 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
188 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000189 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000190 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000191
Dan Gohman667d7872009-06-26 22:53:46 +0000192 // Expand the code for the iteration count.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000193 assert(RHS->isLoopInvariant(L) &&
194 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000195 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000196
Reid Spencere4d87aa2006-12-23 06:05:41 +0000197 // Insert a new icmp_ne or icmp_eq instruction before the branch.
198 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000199 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000200 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000201 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000202 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000203
David Greenef67ef312010-01-05 01:27:06 +0000204 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000205 << " LHS:" << *CmpIndVar << '\n'
206 << " op:\t"
207 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
208 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000209
Owen Anderson333c4002009-07-09 23:48:35 +0000210 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000211
Dan Gohman24440802010-02-22 02:07:36 +0000212 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000213 // It's tempting to use replaceAllUsesWith here to fully replace the old
214 // comparison, but that's not immediately safe, since users of the old
215 // comparison may not be dominated by the new comparison. Instead, just
216 // update the branch to use the new comparison; in the common case this
217 // will make old comparison dead.
218 BI->setCondition(Cond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000219 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
220
Chris Lattner40bf8b42004-04-02 20:24:31 +0000221 ++NumLFTR;
222 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000223 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000224}
225
Chris Lattner40bf8b42004-04-02 20:24:31 +0000226/// RewriteLoopExitValues - Check to see if this loop has a computable
227/// loop-invariant execution count. If so, this means that we can compute the
228/// final value of any expressions that are recurrent in the loop, and
229/// substitute the exit values from the loop into any instructions outside of
230/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000231///
232/// This is mostly redundant with the regular IndVarSimplify activities that
233/// happen later, except that it's more powerful in some cases, because it's
234/// able to brute-force evaluate arbitrary instructions as long as they have
235/// constant operands at the beginning of the loop.
Dan Gohman890f92b2009-04-18 17:56:28 +0000236void IndVarSimplify::RewriteLoopExitValues(Loop *L,
Dan Gohman667d7872009-06-26 22:53:46 +0000237 SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000238 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000239 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000240
Devang Patelb7211a22007-08-21 00:31:24 +0000241 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000242 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000243
Chris Lattner9f3d7382007-03-04 03:43:23 +0000244 // Find all values that are computed inside the loop, but used outside of it.
245 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
246 // the exit blocks of the loop to find them.
247 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
248 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000249
Chris Lattner9f3d7382007-03-04 03:43:23 +0000250 // If there are no PHI nodes in this exit block, then no values defined
251 // inside the loop are used on this path, skip it.
252 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
253 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000254
Chris Lattner9f3d7382007-03-04 03:43:23 +0000255 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000256
Chris Lattner9f3d7382007-03-04 03:43:23 +0000257 // Iterate over all of the PHI nodes.
258 BasicBlock::iterator BBI = ExitBB->begin();
259 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000260 if (PN->use_empty())
261 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000262
263 // SCEV only supports integer expressions for now.
264 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
265 continue;
266
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000267 // It's necessary to tell ScalarEvolution about this explicitly so that
268 // it can walk the def-use list and forget all SCEVs, as it may not be
269 // watching the PHI itself. Once the new exit value is in place, there
270 // may not be a def-use connection between the loop and every instruction
271 // which got a SCEVAddRecExpr for that loop.
272 SE->forgetValue(PN);
273
Chris Lattner9f3d7382007-03-04 03:43:23 +0000274 // Iterate over all of the values in all the PHI nodes.
275 for (unsigned i = 0; i != NumPreds; ++i) {
276 // If the value being merged in is not integer or is not defined
277 // in the loop, skip it.
278 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000279 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000280 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000281
Chris Lattner9f3d7382007-03-04 03:43:23 +0000282 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000283 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000284 continue; // The Block is in a subloop, skip it.
285
286 // Check that InVal is defined in the loop.
287 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000288 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000289 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000290
Chris Lattner9f3d7382007-03-04 03:43:23 +0000291 // Okay, this instruction has a user outside of the current loop
292 // and varies predictably *inside* the loop. Evaluate the value it
293 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000294 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +0000295 if (!ExitValue->isLoopInvariant(L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000296 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000297
Chris Lattner9f3d7382007-03-04 03:43:23 +0000298 Changed = true;
299 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000300
Dan Gohman667d7872009-06-26 22:53:46 +0000301 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000302
David Greenef67ef312010-01-05 01:27:06 +0000303 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000304 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000305
306 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000307
Dan Gohman81db61a2009-05-12 02:17:14 +0000308 // If this instruction is dead now, delete it.
309 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000310
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000311 if (NumPreds == 1) {
312 // Completely replace a single-pred PHI. This is safe, because the
313 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
314 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000315 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000316 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000317 }
318 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000319 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000320 // Clone the PHI and delete the original one. This lets IVUsers and
321 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000322 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000323 NewPN->takeName(PN);
324 NewPN->insertBefore(PN);
325 PN->replaceAllUsesWith(NewPN);
326 PN->eraseFromParent();
327 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000328 }
329 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000330
331 // The insertion point instruction may have been deleted; clear it out
332 // so that the rewriter doesn't trip over it later.
333 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000334}
335
Dan Gohman60f8a632009-02-17 20:49:49 +0000336void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000337 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000338 // If there are, change them into integer recurrences, permitting analysis by
339 // the SCEV routines.
340 //
341 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000342
Dan Gohman81db61a2009-05-12 02:17:14 +0000343 SmallVector<WeakVH, 8> PHIs;
344 for (BasicBlock::iterator I = Header->begin();
345 PHINode *PN = dyn_cast<PHINode>(I); ++I)
346 PHIs.push_back(PN);
347
348 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
349 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
350 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000351
Dan Gohman2d1be872009-04-16 03:18:22 +0000352 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000353 // may not have been able to compute a trip count. Now that we've done some
354 // re-writing, the trip count may be computable.
355 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000356 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000357}
358
Dan Gohman931e3452010-04-12 02:21:50 +0000359void IndVarSimplify::EliminateIVComparisons() {
Dan Gohmandd842e32010-04-12 07:29:15 +0000360 SmallVector<WeakVH, 16> DeadInsts;
361
Dan Gohman931e3452010-04-12 02:21:50 +0000362 // Look for ICmp users.
Dan Gohmandd842e32010-04-12 07:29:15 +0000363 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
364 IVStrideUse &UI = *I;
Dan Gohman931e3452010-04-12 02:21:50 +0000365 ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
366 if (!ICmp) continue;
367
368 bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
369 ICmpInst::Predicate Pred = ICmp->getPredicate();
370 if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
371
372 // Get the SCEVs for the ICmp operands.
373 const SCEV *S = IU->getReplacementExpr(UI);
374 const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
375
376 // Simplify unnecessary loops away.
377 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
378 S = SE->getSCEVAtScope(S, ICmpLoop);
379 X = SE->getSCEVAtScope(X, ICmpLoop);
380
381 // If the condition is always true or always false, replace it with
382 // a constant value.
383 if (SE->isKnownPredicate(Pred, S, X))
384 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
385 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
386 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
387 else
388 continue;
389
390 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Dan Gohmandd842e32010-04-12 07:29:15 +0000391 DeadInsts.push_back(ICmp);
Dan Gohman931e3452010-04-12 02:21:50 +0000392 }
Dan Gohmandd842e32010-04-12 07:29:15 +0000393
394 // Now that we're done iterating through lists, clean up any instructions
395 // which are now dead.
396 while (!DeadInsts.empty())
397 if (Instruction *Inst =
398 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
399 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohman931e3452010-04-12 02:21:50 +0000400}
401
Dan Gohmana590b792010-04-13 01:46:36 +0000402void IndVarSimplify::EliminateIVRemainders() {
403 SmallVector<WeakVH, 16> DeadInsts;
404
405 // Look for SRem and URem users.
406 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
407 IVStrideUse &UI = *I;
408 BinaryOperator *Rem = dyn_cast<BinaryOperator>(UI.getUser());
409 if (!Rem) continue;
410
411 bool isSigned = Rem->getOpcode() == Instruction::SRem;
412 if (!isSigned && Rem->getOpcode() != Instruction::URem)
413 continue;
414
415 // We're only interested in the case where we know something about
416 // the numerator.
417 if (UI.getOperandValToReplace() != Rem->getOperand(0))
418 continue;
419
420 // Get the SCEVs for the ICmp operands.
421 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
422 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
423
424 // Simplify unnecessary loops away.
425 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
426 S = SE->getSCEVAtScope(S, ICmpLoop);
427 X = SE->getSCEVAtScope(X, ICmpLoop);
428
429 // i % n --> i if i is in [0,n).
430 if ((!isSigned || SE->isKnownNonNegative(S)) &&
431 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
432 S, X))
433 Rem->replaceAllUsesWith(Rem->getOperand(0));
434 else {
435 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
436 const SCEV *LessOne =
437 SE->getMinusSCEV(S, SE->getIntegerSCEV(1, S->getType()));
438 if ((!isSigned || SE->isKnownNonNegative(LessOne)) &&
439 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
440 LessOne, X)) {
441 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
442 Rem->getOperand(0), Rem->getOperand(1),
443 "tmp");
444 SelectInst *Sel =
445 SelectInst::Create(ICmp,
446 ConstantInt::get(Rem->getType(), 0),
447 Rem->getOperand(0), "tmp", Rem);
448 Rem->replaceAllUsesWith(Sel);
449 } else
450 continue;
451 }
452
453 // Inform IVUsers about the new users.
454 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
455 IU->AddUsersIfInteresting(I);
456
457 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
458 DeadInsts.push_back(Rem);
459 }
460
461 // Now that we're done iterating through lists, clean up any instructions
462 // which are now dead.
463 while (!DeadInsts.empty())
464 if (Instruction *Inst =
465 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
466 RecursivelyDeleteTriviallyDeadInstructions(Inst);
467}
468
Dan Gohmanc2390b12009-02-12 22:19:27 +0000469bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000470 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000471 LI = &getAnalysis<LoopInfo>();
472 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +0000473 DT = &getAnalysis<DominatorTree>();
Devang Patel5ee99972007-03-07 06:39:01 +0000474 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000475
Dan Gohman2d1be872009-04-16 03:18:22 +0000476 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000477 // transform them to use integer recurrences.
478 RewriteNonIntegerIVs(L);
479
Dan Gohman81db61a2009-05-12 02:17:14 +0000480 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
Dan Gohman0bba49c2009-07-07 17:06:11 +0000481 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000482
Dan Gohman667d7872009-06-26 22:53:46 +0000483 // Create a rewriter object which we'll use to transform the code with.
484 SCEVExpander Rewriter(*SE);
485
Chris Lattner40bf8b42004-04-02 20:24:31 +0000486 // Check to see if this loop has a computable loop-invariant execution count.
487 // If so, this means that we can compute the final value of any expressions
488 // that are recurrent in the loop, and substitute the exit values from the
489 // loop into any instructions outside of the loop that use the final values of
490 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000491 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000492 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +0000493 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +0000494
Dan Gohmand890f292010-04-12 07:56:56 +0000495 // Simplify ICmp IV users.
496 EliminateIVComparisons();
497
Dan Gohmana590b792010-04-13 01:46:36 +0000498 // Simplify SRem and URem IV users.
499 EliminateIVRemainders();
500
Dan Gohman81db61a2009-05-12 02:17:14 +0000501 // Compute the type of the largest recurrence expression, and decide whether
502 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000503 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000504 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000505 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
506 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000507 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000508 // If we have a known trip count and a single exit block, we'll be
509 // rewriting the loop exit test condition below, which requires a
510 // canonical induction variable.
511 if (ExitingBlock)
512 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000513 }
Dan Gohman572645c2010-02-12 10:34:29 +0000514 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
515 const Type *Ty =
516 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000517 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000518 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000519 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000520 LargestType = Ty;
Dan Gohman572645c2010-02-12 10:34:29 +0000521 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000522 }
523
Dan Gohmanf451cb82010-02-10 16:03:48 +0000524 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +0000525 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000526 Value *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000527 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +0000528 // Check to see if the loop already has any canonical-looking induction
529 // variables. If any are present and wider than the planned canonical
530 // induction variable, temporarily remove them, so that the Rewriter
531 // doesn't attempt to reuse them.
532 SmallVector<PHINode *, 2> OldCannIVs;
533 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000534 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
535 SE->getTypeSizeInBits(LargestType))
536 OldCannIV->removeFromParent();
537 else
Dan Gohman85669632010-02-25 06:57:05 +0000538 break;
539 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000540 }
541
Dan Gohman667d7872009-06-26 22:53:46 +0000542 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000543
Dan Gohmanc2390b12009-02-12 22:19:27 +0000544 ++NumInserted;
545 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +0000546 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +0000547
548 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +0000549 // any old canonical-looking variables after it so that the IR remains
550 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +0000551 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +0000552 while (!OldCannIVs.empty()) {
553 PHINode *OldCannIV = OldCannIVs.pop_back_val();
554 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
555 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000556 }
Chris Lattner15cad752003-12-23 07:47:09 +0000557
Dan Gohmanc2390b12009-02-12 22:19:27 +0000558 // If we have a trip count expression, rewrite the loop's exit condition
559 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000560 ICmpInst *NewICmp = 0;
Dan Gohman85669632010-02-25 06:57:05 +0000561 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
562 !BackedgeTakenCount->isZero() &&
563 ExitingBlock) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000564 assert(NeedCannIV &&
565 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000566 // Can't rewrite non-branch yet.
Dan Gohmand890f292010-04-12 07:56:56 +0000567 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
Dan Gohman81db61a2009-05-12 02:17:14 +0000568 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
569 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000570 }
571
Torok Edwin3d431382009-05-24 20:08:21 +0000572 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman454d26d2010-02-22 04:11:59 +0000573 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000574
Dan Gohman667d7872009-06-26 22:53:46 +0000575 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +0000576
Dan Gohman81db61a2009-05-12 02:17:14 +0000577 // Loop-invariant instructions in the preheader that aren't used in the
578 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +0000579 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000580
581 // For completeness, inform IVUsers of the IV use in the newly-created
582 // loop exit test instruction.
583 if (NewICmp)
584 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
585
586 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +0000587 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +0000588 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000589 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000590 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000591}
Devang Pateld22a8492008-09-09 21:41:07 +0000592
Dan Gohman448db1c2010-04-07 22:27:08 +0000593// FIXME: It is an extremely bad idea to indvar substitute anything more
594// complex than affine induction variables. Doing so will put expensive
595// polynomial evaluations inside of the loop, and the str reduction pass
596// currently can only reduce affine polynomials. For now just disable
597// indvar subst on anything more complex than an affine addrec, unless
598// it can be expanded to a trivial value.
599static bool isSafe(const SCEV *S, const Loop *L) {
600 // Loop-invariant values are safe.
601 if (S->isLoopInvariant(L)) return true;
602
603 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
604 // to transform them into efficient code.
605 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
606 return AR->isAffine();
607
608 // An add is safe it all its operands are safe.
609 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
610 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
611 E = Commutative->op_end(); I != E; ++I)
612 if (!isSafe(*I, L)) return false;
613 return true;
614 }
615
616 // A cast is safe if its operand is.
617 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
618 return isSafe(C->getOperand(), L);
619
620 // A udiv is safe if its operands are.
621 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
622 return isSafe(UD->getLHS(), L) &&
623 isSafe(UD->getRHS(), L);
624
625 // SCEVUnknown is always safe.
626 if (isa<SCEVUnknown>(S))
627 return true;
628
629 // Nothing else is safe.
630 return false;
631}
632
Dan Gohman454d26d2010-02-22 04:11:59 +0000633void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000634 SmallVector<WeakVH, 16> DeadInsts;
635
636 // Rewrite all induction variable expressions in terms of the canonical
637 // induction variable.
638 //
639 // If there were induction variables of other sizes or offsets, manually
640 // add the offsets to the primary induction variable and cast, avoiding
641 // the need for the code evaluation methods to insert induction variables
642 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +0000643 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
Dan Gohman572645c2010-02-12 10:34:29 +0000644 Value *Op = UI->getOperandValToReplace();
645 const Type *UseTy = Op->getType();
646 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000647
Dan Gohman572645c2010-02-12 10:34:29 +0000648 // Compute the final addrec to expand into code.
649 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +0000650
Dan Gohman572645c2010-02-12 10:34:29 +0000651 // Evaluate the expression out of the loop, if possible.
652 if (!L->contains(UI->getUser())) {
653 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
654 if (ExitVal->isLoopInvariant(L))
655 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +0000656 }
Dan Gohman572645c2010-02-12 10:34:29 +0000657
658 // FIXME: It is an extremely bad idea to indvar substitute anything more
659 // complex than affine induction variables. Doing so will put expensive
660 // polynomial evaluations inside of the loop, and the str reduction pass
661 // currently can only reduce affine polynomials. For now just disable
662 // indvar subst on anything more complex than an affine addrec, unless
663 // it can be expanded to a trivial value.
Dan Gohman448db1c2010-04-07 22:27:08 +0000664 if (!isSafe(AR, L))
Dan Gohman572645c2010-02-12 10:34:29 +0000665 continue;
666
667 // Determine the insertion point for this user. By default, insert
668 // immediately before the user. The SCEVExpander class will automatically
669 // hoist loop invariants out of the loop. For PHI nodes, there may be
670 // multiple uses, so compute the nearest common dominator for the
671 // incoming blocks.
672 Instruction *InsertPt = User;
673 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
674 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
675 if (PHI->getIncomingValue(i) == Op) {
676 if (InsertPt == User)
677 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
678 else
679 InsertPt =
680 DT->findNearestCommonDominator(InsertPt->getParent(),
681 PHI->getIncomingBlock(i))
682 ->getTerminator();
683 }
684
685 // Now expand it into actual Instructions and patch it into place.
686 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
687
Dan Gohmand7bfd002010-04-02 14:48:31 +0000688 // Inform ScalarEvolution that this value is changing. The change doesn't
689 // affect its value, but it does potentially affect which use lists the
690 // value will be on after the replacement, which affects ScalarEvolution's
691 // ability to walk use lists and drop dangling pointers when a value is
692 // deleted.
693 SE->forgetValue(User);
694
Dan Gohman572645c2010-02-12 10:34:29 +0000695 // Patch the new value into place.
696 if (Op->hasName())
697 NewVal->takeName(Op);
698 User->replaceUsesOfWith(Op, NewVal);
699 UI->setOperandValToReplace(NewVal);
700 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
701 << " into = " << *NewVal << "\n");
702 ++NumRemoved;
703 Changed = true;
704
705 // The old value may be dead now.
706 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +0000707 }
708
Torok Edwin3d431382009-05-24 20:08:21 +0000709 // Clear the rewriter cache, because values that are in the rewriter's cache
710 // can be deleted in the loop below, causing the AssertingVH in the cache to
711 // trigger.
712 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000713 // Now that we're done iterating through lists, clean up any instructions
714 // which are now dead.
Dan Gohmana10756e2010-01-21 02:09:26 +0000715 while (!DeadInsts.empty())
716 if (Instruction *Inst =
717 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
Dan Gohman81db61a2009-05-12 02:17:14 +0000718 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohman81db61a2009-05-12 02:17:14 +0000719}
720
721/// If there's a single exit block, sink any loop-invariant values that
722/// were defined in the preheader but not used inside the loop into the
723/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +0000724void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000725 BasicBlock *ExitBlock = L->getExitBlock();
726 if (!ExitBlock) return;
727
Dan Gohman81db61a2009-05-12 02:17:14 +0000728 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +0000729 if (!Preheader) return;
730
731 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +0000732 BasicBlock::iterator I = Preheader->getTerminator();
733 while (I != Preheader->begin()) {
734 --I;
Dan Gohman667d7872009-06-26 22:53:46 +0000735 // New instructions were inserted at the end of the preheader.
736 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +0000737 break;
Bill Wendling87a10f52010-03-23 21:15:59 +0000738
Eli Friedman0c77db32009-07-15 22:48:29 +0000739 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +0000740 // effects need to complete before instructions inside the loop. Also don't
741 // move instructions which might read memory, since the loop may modify
742 // memory. Note that it's okay if the instruction might have undefined
743 // behavior: LoopSimplify guarantees that the preheader dominates the exit
744 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +0000745 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +0000746 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000747
Devang Patel7b9f6b12010-03-15 22:23:03 +0000748 // Skip debug info intrinsics.
749 if (isa<DbgInfoIntrinsic>(I))
750 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000751
Dan Gohman76f497a2009-08-25 17:42:10 +0000752 // Don't sink static AllocaInsts out of the entry block, which would
753 // turn them into dynamic allocas!
754 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
755 if (AI->isStaticAlloca())
756 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000757
Dan Gohman81db61a2009-05-12 02:17:14 +0000758 // Determine if there is a use in or before the loop (direct or
759 // otherwise).
760 bool UsedInLoop = false;
761 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
762 UI != UE; ++UI) {
763 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
764 if (PHINode *P = dyn_cast<PHINode>(UI)) {
765 unsigned i =
766 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
767 UseBB = P->getIncomingBlock(i);
768 }
769 if (UseBB == Preheader || L->contains(UseBB)) {
770 UsedInLoop = true;
771 break;
772 }
773 }
Bill Wendling87a10f52010-03-23 21:15:59 +0000774
Dan Gohman81db61a2009-05-12 02:17:14 +0000775 // If there is, the def must remain in the preheader.
776 if (UsedInLoop)
777 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000778
Dan Gohman81db61a2009-05-12 02:17:14 +0000779 // Otherwise, sink it to the exit block.
780 Instruction *ToMove = I;
781 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +0000782
783 if (I != Preheader->begin()) {
784 // Skip debug info intrinsics.
785 do {
786 --I;
787 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
788
789 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
790 Done = true;
791 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +0000792 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +0000793 }
794
Dan Gohman667d7872009-06-26 22:53:46 +0000795 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +0000796 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +0000797 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +0000798 }
799}
800
Chris Lattnerbbb91492010-04-03 06:41:49 +0000801/// ConvertToSInt - Convert APF to an integer, if possible.
802static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
Devang Patelcd402332008-11-17 23:27:13 +0000803 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000804 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
805 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +0000806 // See if we can convert this to an int64_t
807 uint64_t UIntVal;
808 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
809 &isExact) != APFloat::opOK || !isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000810 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +0000811 IntVal = UIntVal;
Devang Patelcd402332008-11-17 23:27:13 +0000812 return true;
Devang Patelcd402332008-11-17 23:27:13 +0000813}
814
Devang Patel58d43d42008-11-03 18:32:19 +0000815/// HandleFloatingPointIV - If the loop has floating induction variable
816/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000817/// For example,
818/// for(double i = 0; i < 10000; ++i)
819/// bar(i)
820/// is converted into
821/// for(int i = 0; i < 10000; ++i)
822/// bar((double)i);
823///
Chris Lattnerc91961e2010-04-03 06:17:08 +0000824void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
825 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
Devang Patel84e35152008-11-17 21:32:02 +0000826 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000827
Devang Patel84e35152008-11-17 21:32:02 +0000828 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000829 ConstantFP *InitValueVal =
Chris Lattnerc91961e2010-04-03 06:17:08 +0000830 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Chris Lattner96fd7662010-04-03 07:18:48 +0000831
Chris Lattnerbbb91492010-04-03 06:41:49 +0000832 int64_t InitValue;
Chris Lattner96fd7662010-04-03 07:18:48 +0000833 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +0000834 return;
835
Chris Lattnerc91961e2010-04-03 06:17:08 +0000836 // Check IV increment. Reject this PN if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +0000837 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000838 BinaryOperator *Incr =
Chris Lattnerc91961e2010-04-03 06:17:08 +0000839 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +0000840 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
841
842 // If this is not an add of the PHI with a constantfp, or if the constant fp
843 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000844 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
Chris Lattner96fd7662010-04-03 07:18:48 +0000845 int64_t IncValue;
Chris Lattnerc91961e2010-04-03 06:17:08 +0000846 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
Chris Lattner96fd7662010-04-03 07:18:48 +0000847 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
Devang Patelcd402332008-11-17 23:27:13 +0000848 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000849
Chris Lattnerc91961e2010-04-03 06:17:08 +0000850 // Check Incr uses. One user is PN and the other user is an exit condition
Chris Lattner07aa76a2010-04-03 05:54:59 +0000851 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000852 Value::use_iterator IncrUse = Incr->use_begin();
853 Instruction *U1 = cast<Instruction>(IncrUse++);
854 if (IncrUse == Incr->use_end()) return;
855 Instruction *U2 = cast<Instruction>(IncrUse++);
856 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000857
Chris Lattner07aa76a2010-04-03 05:54:59 +0000858 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
859 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +0000860 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
861 if (!Compare)
862 Compare = dyn_cast<FCmpInst>(U2);
863 if (Compare == 0 || !Compare->hasOneUse() ||
864 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +0000865 return;
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000866
Chris Lattnerca703bd2010-04-03 06:11:07 +0000867 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +0000868
Chris Lattnerd52c0722010-04-03 07:21:39 +0000869 // We need to verify that the branch actually controls the iteration count
870 // of the loop. If not, the new IV can overflow and no one will notice.
871 // The branch block must be in the loop and one of the successors must be out
872 // of the loop.
873 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
874 if (!L->contains(TheBr->getParent()) ||
875 (L->contains(TheBr->getSuccessor(0)) &&
876 L->contains(TheBr->getSuccessor(1))))
877 return;
Chris Lattner96fd7662010-04-03 07:18:48 +0000878
879
Chris Lattner07aa76a2010-04-03 05:54:59 +0000880 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
881 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +0000882 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattnerbbb91492010-04-03 06:41:49 +0000883 int64_t ExitValue;
884 if (ExitValueVal == 0 ||
885 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +0000886 return;
Chris Lattnerbbb91492010-04-03 06:41:49 +0000887
Devang Patel84e35152008-11-17 21:32:02 +0000888 // Find new predicate for integer comparison.
889 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +0000890 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000891 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +0000892 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000893 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Chris Lattner96fd7662010-04-03 07:18:48 +0000894 case CmpInst::FCMP_ONE:
895 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
Devang Patel84e35152008-11-17 21:32:02 +0000896 case CmpInst::FCMP_OGT:
Chris Lattnera40e4a02010-04-03 06:25:21 +0000897 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
Devang Patel84e35152008-11-17 21:32:02 +0000898 case CmpInst::FCMP_OGE:
Chris Lattnera40e4a02010-04-03 06:25:21 +0000899 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
Devang Patel84e35152008-11-17 21:32:02 +0000900 case CmpInst::FCMP_OLT:
Chris Lattner43b85272010-04-03 06:30:03 +0000901 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
Devang Patel84e35152008-11-17 21:32:02 +0000902 case CmpInst::FCMP_OLE:
Chris Lattner43b85272010-04-03 06:30:03 +0000903 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Devang Patel58d43d42008-11-03 18:32:19 +0000904 }
Chris Lattner96fd7662010-04-03 07:18:48 +0000905
906 // We convert the floating point induction variable to a signed i32 value if
907 // we can. This is only safe if the comparison will not overflow in a way
908 // that won't be trapped by the integer equivalent operations. Check for this
909 // now.
910 // TODO: We could use i64 if it is native and the range requires it.
911
912 // The start/stride/exit values must all fit in signed i32.
913 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
914 return;
915
916 // If not actually striding (add x, 0.0), avoid touching the code.
917 if (IncValue == 0)
918 return;
919
920 // Positive and negative strides have different safety conditions.
921 if (IncValue > 0) {
922 // If we have a positive stride, we require the init to be less than the
923 // exit value and an equality or less than comparison.
924 if (InitValue >= ExitValue ||
925 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
926 return;
927
928 uint32_t Range = uint32_t(ExitValue-InitValue);
929 if (NewPred == CmpInst::ICMP_SLE) {
930 // Normalize SLE -> SLT, check for infinite loop.
931 if (++Range == 0) return; // Range overflows.
932 }
933
934 unsigned Leftover = Range % uint32_t(IncValue);
935
936 // If this is an equality comparison, we require that the strided value
937 // exactly land on the exit value, otherwise the IV condition will wrap
938 // around and do things the fp IV wouldn't.
939 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
940 Leftover != 0)
941 return;
942
943 // If the stride would wrap around the i32 before exiting, we can't
944 // transform the IV.
945 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
946 return;
947
948 } else {
949 // If we have a negative stride, we require the init to be greater than the
950 // exit value and an equality or greater than comparison.
951 if (InitValue >= ExitValue ||
952 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
953 return;
954
955 uint32_t Range = uint32_t(InitValue-ExitValue);
956 if (NewPred == CmpInst::ICMP_SGE) {
957 // Normalize SGE -> SGT, check for infinite loop.
958 if (++Range == 0) return; // Range overflows.
959 }
960
961 unsigned Leftover = Range % uint32_t(-IncValue);
962
963 // If this is an equality comparison, we require that the strided value
964 // exactly land on the exit value, otherwise the IV condition will wrap
965 // around and do things the fp IV wouldn't.
966 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
967 Leftover != 0)
968 return;
969
970 // If the stride would wrap around the i32 before exiting, we can't
971 // transform the IV.
972 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
973 return;
974 }
975
976 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Dan Gohmancafb8132009-02-17 19:13:57 +0000977
Chris Lattnerbbb91492010-04-03 06:41:49 +0000978 // Insert new integer induction variable.
Chris Lattnerc91961e2010-04-03 06:17:08 +0000979 PHINode *NewPHI = PHINode::Create(Int32Ty, PN->getName()+".int", PN);
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000980 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Chris Lattnerc91961e2010-04-03 06:17:08 +0000981 PN->getIncomingBlock(IncomingEdge));
Devang Patel84e35152008-11-17 21:32:02 +0000982
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000983 Value *NewAdd =
Chris Lattner96fd7662010-04-03 07:18:48 +0000984 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000985 Incr->getName()+".int", Incr);
Chris Lattnerc91961e2010-04-03 06:17:08 +0000986 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Devang Patel84e35152008-11-17 21:32:02 +0000987
Chris Lattnerca703bd2010-04-03 06:11:07 +0000988 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
989 ConstantInt::get(Int32Ty, ExitValue),
990 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +0000991
Chris Lattnerc91961e2010-04-03 06:17:08 +0000992 // In the following deletions, PN may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +0000993 // Use a WeakVH to observe whether this happens.
Chris Lattnerc91961e2010-04-03 06:17:08 +0000994 WeakVH WeakPH = PN;
Dan Gohman81db61a2009-05-12 02:17:14 +0000995
Chris Lattnerca703bd2010-04-03 06:11:07 +0000996 // Delete the old floating point exit comparison. The branch starts using the
997 // new comparison.
998 NewCompare->takeName(Compare);
999 Compare->replaceAllUsesWith(NewCompare);
1000 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +00001001
Chris Lattnerca703bd2010-04-03 06:11:07 +00001002 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001003 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +00001004 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001005
Chris Lattner70c0d4f2010-04-03 06:16:22 +00001006 // If the FP induction variable still has uses, this is because something else
1007 // in the loop uses its value. In order to canonicalize the induction
1008 // variable, we chose to eliminate the IV and rewrite it in terms of an
1009 // int->fp cast.
1010 //
1011 // We give preference to sitofp over uitofp because it is faster on most
1012 // platforms.
1013 if (WeakPH) {
Chris Lattnera40e4a02010-04-03 06:25:21 +00001014 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1015 PN->getParent()->getFirstNonPHI());
1016 PN->replaceAllUsesWith(Conv);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001017 RecursivelyDeleteTriviallyDeadInstructions(PN);
Devang Patelcd402332008-11-17 23:27:13 +00001018 }
Devang Patel58d43d42008-11-03 18:32:19 +00001019
Dan Gohman81db61a2009-05-12 02:17:14 +00001020 // Add a new IVUsers entry for the newly-created integer PHI.
1021 IU->AddUsersIfInteresting(NewPHI);
1022}