blob: 205efca6ce244b4f6496b510edd18cb1773fea9e [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.
20// 3. Any pointer arithmetic recurrences are raised to use array subscripts.
21//
22// If the trip count of a loop is computable, this pass also makes the following
23// changes:
24// 1. The exit condition for the loop is canonicalized to compare the
25// induction value against the exit value. This turns loops like:
26// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
27// 2. Any use outside of the loop of an expression derived from the indvar
28// is changed to compute the derived value outside of the loop, eliminating
29// the dependence on the exit value of the induction variable. If the only
30// purpose of the loop is to compute the exit value of some derived
31// expression, this transformation will make the loop dead.
32//
33// This transformation should be followed by strength reduction after all of the
34// desired loop transformations have been performed. Additionally, on targets
35// where it is profitable, the loop could be transformed to count down to zero
36// (the "do loop" optimization).
Chris Lattner6148c022001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattner0e5f4992006-12-19 21:40:18 +000040#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000041#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000042#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000043#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000044#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000045#include "llvm/Type.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
Chris Lattnera4b9c782004-10-11 23:06:50 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswell47df12d2003-12-18 17:19:19 +000053#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Dan Gohmanc2390b12009-02-12 22:19:27 +000056#include "llvm/ADT/SetVector.h"
Chris Lattner1a6111f2008-11-16 07:17:51 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000059using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000060
Chris Lattner0e5f4992006-12-19 21:40:18 +000061STATISTIC(NumRemoved , "Number of aux indvars removed");
62STATISTIC(NumPointer , "Number of pointer indvars promoted");
63STATISTIC(NumInserted, "Number of canonical indvars added");
64STATISTIC(NumReplaced, "Number of exit values replaced");
65STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000066
Chris Lattner0e5f4992006-12-19 21:40:18 +000067namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000068 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000069 LoopInfo *LI;
70 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000071 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000072 public:
Devang Patel794fd752007-05-01 21:15:47 +000073
Nick Lewyckyecd94c82007-05-06 13:37:16 +000074 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000075 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000076
Dan Gohman60f8a632009-02-17 20:49:49 +000077 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
78
Devang Patel5ee99972007-03-07 06:39:01 +000079 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelbc533cd2007-09-10 18:08:23 +000080 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000081 AU.addRequiredID(LCSSAID);
82 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000083 AU.addRequired<LoopInfo>();
Dan Gohman474cecf2009-02-23 16:29:41 +000084 AU.addPreserved<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000085 AU.addPreservedID(LoopSimplifyID);
86 AU.addPreservedID(LCSSAID);
87 AU.setPreservesCFG();
88 }
Chris Lattner15cad752003-12-23 07:47:09 +000089
Chris Lattner40bf8b42004-04-02 20:24:31 +000090 private:
Devang Patel5ee99972007-03-07 06:39:01 +000091
Dan Gohman60f8a632009-02-17 20:49:49 +000092 void RewriteNonIntegerIVs(Loop *L);
93
Chris Lattner40bf8b42004-04-02 20:24:31 +000094 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +000095 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohman46bdfb02009-02-24 18:55:53 +000096 void LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +000097 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +000098 BasicBlock *ExitingBlock,
99 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000100 SCEVExpander &Rewriter);
Dan Gohman46bdfb02009-02-24 18:55:53 +0000101 void RewriteLoopExitValues(Loop *L, SCEV *BackedgeTakenCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000102
Chris Lattner1a6111f2008-11-16 07:17:51 +0000103 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +0000104
Dan Gohmancafb8132009-02-17 19:13:57 +0000105 void HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000106 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner3324e712003-12-22 03:58:44 +0000107 };
Chris Lattner5e761402002-09-10 05:24:05 +0000108}
Chris Lattner394437f2001-12-04 04:32:29 +0000109
Dan Gohman844731a2008-05-13 00:00:25 +0000110char IndVarSimplify::ID = 0;
111static RegisterPass<IndVarSimplify>
112X("indvars", "Canonicalize Induction Variables");
113
Daniel Dunbar394f0442008-10-22 23:32:42 +0000114Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000115 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000116}
117
Chris Lattner40bf8b42004-04-02 20:24:31 +0000118/// DeleteTriviallyDeadInstructions - If any of the instructions is the
119/// specified set are trivially dead, delete them and see if this makes any of
120/// their operands subsequently dead.
121void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000122DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000123 while (!Insts.empty()) {
124 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000125 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000126 if (isInstructionTriviallyDead(I)) {
127 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
128 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
129 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000130 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000131 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000132 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000133 Changed = true;
134 }
135 }
136}
137
138
139/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
140/// recurrence. If so, change it into an integer recurrence, permitting
141/// analysis by the SCEV routines.
Misha Brukmanfd939082005-04-21 23:48:37 +0000142void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000143 BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +0000144 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000145 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
146 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
147 unsigned BackedgeIdx = PreheaderIdx^1;
148 if (GetElementPtrInst *GEPI =
Chris Lattnercda9ca52005-08-10 01:12:06 +0000149 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000150 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000151 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattneree4f13a2007-01-07 01:14:12 +0000152 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
Dan Gohmancafb8132009-02-17 19:13:57 +0000153
Chris Lattner40bf8b42004-04-02 20:24:31 +0000154 // Okay, we found a pointer recurrence. Transform this pointer
155 // recurrence into an integer recurrence. Compute the value that gets
156 // added to the pointer at every iteration.
157 Value *AddedVal = GEPI->getOperand(1);
158
159 // Insert a new integer PHI node into the top of the block.
Gabor Greif051a9502008-04-06 20:25:17 +0000160 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
161 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000162 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
163
Chris Lattner40bf8b42004-04-02 20:24:31 +0000164 // Create the new add instruction.
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000165 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000166 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000167 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000168
Chris Lattner40bf8b42004-04-02 20:24:31 +0000169 // Update the existing GEP to use the recurrence.
170 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000171
Chris Lattner40bf8b42004-04-02 20:24:31 +0000172 // Update the GEP to use the new recurrence we just inserted.
173 GEPI->setOperand(1, NewAdd);
174
Chris Lattnera4b9c782004-10-11 23:06:50 +0000175 // If the incoming value is a constant expr GEP, try peeling out the array
176 // 0 index if possible to make things simpler.
177 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
178 if (CE->getOpcode() == Instruction::GetElementPtr) {
179 unsigned NumOps = CE->getNumOperands();
180 assert(NumOps > 1 && "CE folding didn't work!");
181 if (CE->getOperand(NumOps-1)->isNullValue()) {
182 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000183 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000184 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000185 i != e; ++i, ++GTI)
186 /*empty*/;
187 if (isa<SequentialType>(*GTI)) {
188 // Pull the last index out of the constant expr GEP.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000189 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000190 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000191 &CEIdxs[0],
192 CEIdxs.size());
David Greeneb8f74792007-09-04 15:46:09 +0000193 Value *Idx[2];
194 Idx[0] = Constant::getNullValue(Type::Int32Ty);
195 Idx[1] = NewAdd;
Gabor Greif051a9502008-04-06 20:25:17 +0000196 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
Dan Gohmancafb8132009-02-17 19:13:57 +0000197 NCE, Idx, Idx + 2,
Reid Spencercae57542007-03-02 00:28:52 +0000198 GEPI->getName(), GEPI);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000199 SE->deleteValueFromRecords(GEPI);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000200 GEPI->replaceAllUsesWith(NGEPI);
201 GEPI->eraseFromParent();
202 GEPI = NGEPI;
203 }
204 }
205 }
206
207
Chris Lattner40bf8b42004-04-02 20:24:31 +0000208 // Finally, if there are any other users of the PHI node, we must
209 // insert a new GEP instruction that uses the pre-incremented version
210 // of the induction amount.
211 if (!PN->use_empty()) {
212 BasicBlock::iterator InsertPos = PN; ++InsertPos;
213 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000214 Value *PreInc =
Gabor Greif051a9502008-04-06 20:25:17 +0000215 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
216 NewPhi, "", InsertPos);
Chris Lattner6934a042007-02-11 01:23:03 +0000217 PreInc->takeName(PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000218 PN->replaceAllUsesWith(PreInc);
219 }
220
221 // Delete the old PHI for sure, and the GEP if its otherwise unused.
222 DeadInsts.insert(PN);
223
224 ++NumPointer;
225 Changed = true;
226 }
227}
228
229/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000230/// loop to be a canonical != comparison against the incremented loop induction
231/// variable. This pass is able to rewrite the exit tests of any loop where the
232/// SCEV analysis can determine a loop-invariant trip count of the loop, which
233/// is actually a much broader range than just linear tests.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000234void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman46bdfb02009-02-24 18:55:53 +0000235 SCEVHandle BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000236 Value *IndVar,
237 BasicBlock *ExitingBlock,
238 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000239 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000240 // If the exiting block is not the same as the backedge block, we must compare
241 // against the preincremented value, otherwise we prefer to compare against
242 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000243 Value *CmpIndVar;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000244 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000245 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000246 // Add one to the "backedge-taken" count to get the trip count.
247 // If this addition may overflow, we have to be more pessimistic and
248 // cast the induction variable before doing the add.
249 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000250 SCEVHandle N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000251 SE->getAddExpr(BackedgeTakenCount,
252 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000253 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
254 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
255 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000256 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000257 } else {
258 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000259 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
260 IndVar->getType());
261 RHS = SE->getAddExpr(RHS,
262 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000263 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000264
Dan Gohman46bdfb02009-02-24 18:55:53 +0000265 // The BackedgeTaken expression contains the number of times that the
266 // backedge branches to the loop header. This is one less than the
267 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000268 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000269 } else {
270 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000271 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
272 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000273 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000274 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000275
Chris Lattner40bf8b42004-04-02 20:24:31 +0000276 // Expand the code for the iteration count into the preheader of the loop.
277 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman46bdfb02009-02-24 18:55:53 +0000278 Value *ExitCnt = Rewriter.expandCodeFor(RHS,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000279 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000280
Reid Spencere4d87aa2006-12-23 06:05:41 +0000281 // Insert a new icmp_ne or icmp_eq instruction before the branch.
282 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000283 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000284 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000285 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000286 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000287
Dan Gohmanc2390b12009-02-12 22:19:27 +0000288 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
289 << " LHS:" << *CmpIndVar // includes a newline
290 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000291 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman46bdfb02009-02-24 18:55:53 +0000292 << " RHS:\t" << *RHS << "\n";
Dan Gohmanc2390b12009-02-12 22:19:27 +0000293
294 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000295 BI->setCondition(Cond);
296 ++NumLFTR;
297 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000298}
299
Chris Lattner40bf8b42004-04-02 20:24:31 +0000300/// RewriteLoopExitValues - Check to see if this loop has a computable
301/// loop-invariant execution count. If so, this means that we can compute the
302/// final value of any expressions that are recurrent in the loop, and
303/// substitute the exit values from the loop into any instructions outside of
304/// the loop that use the final values of the current expressions.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000305void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *BackedgeTakenCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000306 BasicBlock *Preheader = L->getLoopPreheader();
307
308 // Scan all of the instructions in the loop, looking at those that have
309 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000310 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000311
312 // We insert the code into the preheader of the loop if the loop contains
313 // multiple exit blocks, or in the exit block if there is exactly one.
314 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000315 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000316 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000317 if (ExitBlocks.size() == 1)
318 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000319 else
320 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000321 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000322
Dan Gohman46bdfb02009-02-24 18:55:53 +0000323 bool HasConstantItCount = isa<SCEVConstant>(BackedgeTakenCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000324
Chris Lattner1a6111f2008-11-16 07:17:51 +0000325 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000326 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000327
Chris Lattner9f3d7382007-03-04 03:43:23 +0000328 // Find all values that are computed inside the loop, but used outside of it.
329 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
330 // the exit blocks of the loop to find them.
331 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
332 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000333
Chris Lattner9f3d7382007-03-04 03:43:23 +0000334 // If there are no PHI nodes in this exit block, then no values defined
335 // inside the loop are used on this path, skip it.
336 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
337 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000338
Chris Lattner9f3d7382007-03-04 03:43:23 +0000339 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000340
Chris Lattner9f3d7382007-03-04 03:43:23 +0000341 // Iterate over all of the PHI nodes.
342 BasicBlock::iterator BBI = ExitBB->begin();
343 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000344
Chris Lattner9f3d7382007-03-04 03:43:23 +0000345 // Iterate over all of the values in all the PHI nodes.
346 for (unsigned i = 0; i != NumPreds; ++i) {
347 // If the value being merged in is not integer or is not defined
348 // in the loop, skip it.
349 Value *InVal = PN->getIncomingValue(i);
350 if (!isa<Instruction>(InVal) ||
351 // SCEV only supports integer expressions for now.
352 !isa<IntegerType>(InVal->getType()))
353 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000354
Chris Lattner9f3d7382007-03-04 03:43:23 +0000355 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000356 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000357 continue; // The Block is in a subloop, skip it.
358
359 // Check that InVal is defined in the loop.
360 Instruction *Inst = cast<Instruction>(InVal);
361 if (!L->contains(Inst->getParent()))
362 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000363
Chris Lattner9f3d7382007-03-04 03:43:23 +0000364 // We require that this value either have a computable evolution or that
365 // the loop have a constant iteration count. In the case where the loop
366 // has a constant iteration count, we can sometimes force evaluation of
367 // the exit value through brute force.
368 SCEVHandle SH = SE->getSCEV(Inst);
369 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
370 continue; // Cannot get exit evolution for the loop value.
Dan Gohmancafb8132009-02-17 19:13:57 +0000371
Chris Lattner9f3d7382007-03-04 03:43:23 +0000372 // Okay, this instruction has a user outside of the current loop
373 // and varies predictably *inside* the loop. Evaluate the value it
374 // contains when the loop exits, if possible.
375 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
376 if (isa<SCEVCouldNotCompute>(ExitValue) ||
377 !ExitValue->isLoopInvariant(L))
378 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000379
Chris Lattner9f3d7382007-03-04 03:43:23 +0000380 Changed = true;
381 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000382
Chris Lattner9f3d7382007-03-04 03:43:23 +0000383 // See if we already computed the exit value for the instruction, if so,
384 // just reuse it.
385 Value *&ExitVal = ExitValues[Inst];
386 if (!ExitVal)
Dan Gohmand19534a2007-06-15 14:38:12 +0000387 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000388
Chris Lattner9f3d7382007-03-04 03:43:23 +0000389 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
390 << " LoopVal = " << *Inst << "\n";
391
392 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000393
Chris Lattner9f3d7382007-03-04 03:43:23 +0000394 // If this instruction is dead now, schedule it to be removed.
395 if (Inst->use_empty())
396 InstructionsToDelete.insert(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000397
Chris Lattner9f3d7382007-03-04 03:43:23 +0000398 // See if this is a single-entry LCSSA PHI node. If so, we can (and
399 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000400 // the PHI entirely. This is safe, because the NewVal won't be variant
401 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000402 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000403 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000404 PN->replaceAllUsesWith(ExitVal);
405 PN->eraseFromParent();
406 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000407 }
408 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000409 }
410 }
Dan Gohmancafb8132009-02-17 19:13:57 +0000411
Chris Lattner40bf8b42004-04-02 20:24:31 +0000412 DeleteTriviallyDeadInstructions(InstructionsToDelete);
413}
414
Dan Gohman60f8a632009-02-17 20:49:49 +0000415void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000416 // First step. Check to see if there are any trivial GEP pointer recurrences.
417 // If there are, change them into integer recurrences, permitting analysis by
418 // the SCEV routines.
419 //
420 BasicBlock *Header = L->getHeader();
421 BasicBlock *Preheader = L->getLoopPreheader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000422
Chris Lattner1a6111f2008-11-16 07:17:51 +0000423 SmallPtrSet<Instruction*, 16> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000424 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
425 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000426 if (isa<PointerType>(PN->getType()))
427 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patel84e35152008-11-17 21:32:02 +0000428 else
429 HandleFloatingPointIV(L, PN, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000430 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000431
Dan Gohman60f8a632009-02-17 20:49:49 +0000432 // If the loop previously had a pointer or floating-point IV, ScalarEvolution
433 // may not have been able to compute a trip count. Now that we've done some
434 // re-writing, the trip count may be computable.
435 if (Changed)
Dan Gohman46bdfb02009-02-24 18:55:53 +0000436 SE->forgetLoopBackedgeTakenCount(L);
Dan Gohman60f8a632009-02-17 20:49:49 +0000437
Chris Lattner40bf8b42004-04-02 20:24:31 +0000438 if (!DeadInsts.empty())
439 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patel5ee99972007-03-07 06:39:01 +0000440}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000441
Dan Gohmanc2390b12009-02-12 22:19:27 +0000442/// getEffectiveIndvarType - Determine the widest type that the
443/// induction-variable PHINode Phi is cast to.
444///
445static const Type *getEffectiveIndvarType(const PHINode *Phi) {
446 const Type *Ty = Phi->getType();
Chris Lattner3324e712003-12-22 03:58:44 +0000447
Dan Gohmanc2390b12009-02-12 22:19:27 +0000448 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
449 UI != UE; ++UI) {
450 const Type *CandidateType = NULL;
451 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
452 CandidateType = ZI->getDestTy();
453 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
454 CandidateType = SI->getDestTy();
455 if (CandidateType &&
456 CandidateType->getPrimitiveSizeInBits() >
457 Ty->getPrimitiveSizeInBits())
458 Ty = CandidateType;
459 }
460
461 return Ty;
462}
463
Dan Gohmanaa036492009-02-14 02:31:09 +0000464/// TestOrigIVForWrap - Analyze the original induction variable
Dan Gohmand2067fd2009-02-18 00:52:00 +0000465/// that controls the loop's iteration to determine whether it
Dan Gohmanf5a309e2009-02-18 17:22:41 +0000466/// would ever undergo signed or unsigned overflow. Also, check
467/// whether an induction variable in the same type that starts
468/// at 0 would undergo signed overflow.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000469///
Dan Gohman15cab282009-02-23 23:20:35 +0000470/// In addition to setting the NoSignedWrap, and NoUnsignedWrap,
471/// variables, return the PHI for this induction variable.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000472///
473/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000474/// Perhaps this can be merged with
475/// ScalarEvolution::getBackedgeTakenCount
Dan Gohmanaa036492009-02-14 02:31:09 +0000476/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000477///
Dan Gohmand2067fd2009-02-18 00:52:00 +0000478static const PHINode *TestOrigIVForWrap(const Loop *L,
479 const BranchInst *BI,
480 const Instruction *OrigCond,
481 bool &NoSignedWrap,
Dan Gohman15cab282009-02-23 23:20:35 +0000482 bool &NoUnsignedWrap) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000483 // Verify that the loop is sane and find the exit condition.
484 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmand2067fd2009-02-18 00:52:00 +0000485 if (!Cmp) return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000486
Dan Gohmanaa036492009-02-14 02:31:09 +0000487 const Value *CmpLHS = Cmp->getOperand(0);
488 const Value *CmpRHS = Cmp->getOperand(1);
489 const BasicBlock *TrueBB = BI->getSuccessor(0);
490 const BasicBlock *FalseBB = BI->getSuccessor(1);
491 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000492
Dan Gohmanaa036492009-02-14 02:31:09 +0000493 // Canonicalize a constant to the RHS.
494 if (isa<ConstantInt>(CmpLHS)) {
495 Pred = ICmpInst::getSwappedPredicate(Pred);
496 std::swap(CmpLHS, CmpRHS);
497 }
498 // Canonicalize SLE to SLT.
499 if (Pred == ICmpInst::ICMP_SLE)
500 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
501 if (!CI->getValue().isMaxSignedValue()) {
502 CmpRHS = ConstantInt::get(CI->getValue() + 1);
503 Pred = ICmpInst::ICMP_SLT;
504 }
505 // Canonicalize SGT to SGE.
506 if (Pred == ICmpInst::ICMP_SGT)
507 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
508 if (!CI->getValue().isMaxSignedValue()) {
509 CmpRHS = ConstantInt::get(CI->getValue() + 1);
510 Pred = ICmpInst::ICMP_SGE;
511 }
512 // Canonicalize SGE to SLT.
513 if (Pred == ICmpInst::ICMP_SGE) {
514 std::swap(TrueBB, FalseBB);
515 Pred = ICmpInst::ICMP_SLT;
516 }
517 // Canonicalize ULE to ULT.
518 if (Pred == ICmpInst::ICMP_ULE)
519 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
520 if (!CI->getValue().isMaxValue()) {
521 CmpRHS = ConstantInt::get(CI->getValue() + 1);
522 Pred = ICmpInst::ICMP_ULT;
523 }
524 // Canonicalize UGT to UGE.
525 if (Pred == ICmpInst::ICMP_UGT)
526 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
527 if (!CI->getValue().isMaxValue()) {
528 CmpRHS = ConstantInt::get(CI->getValue() + 1);
529 Pred = ICmpInst::ICMP_UGE;
530 }
531 // Canonicalize UGE to ULT.
532 if (Pred == ICmpInst::ICMP_UGE) {
533 std::swap(TrueBB, FalseBB);
534 Pred = ICmpInst::ICMP_ULT;
535 }
536 // For now, analyze only LT loops for signed overflow.
537 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000538 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000539
540 bool isSigned = Pred == ICmpInst::ICMP_SLT;
541
542 // Get the increment instruction. Look past casts if we will
Dan Gohmanc2390b12009-02-12 22:19:27 +0000543 // be able to prove that the original induction variable doesn't
Dan Gohmanaa036492009-02-14 02:31:09 +0000544 // undergo signed or unsigned overflow, respectively.
545 const Value *IncrVal = CmpLHS;
546 if (isSigned) {
547 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
548 if (!isa<ConstantInt>(CmpRHS) ||
549 !cast<ConstantInt>(CmpRHS)->getValue()
550 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000551 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000552 IncrVal = SI->getOperand(0);
553 }
554 } else {
555 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
556 if (!isa<ConstantInt>(CmpRHS) ||
557 !cast<ConstantInt>(CmpRHS)->getValue()
558 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000559 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000560 IncrVal = ZI->getOperand(0);
561 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000562 }
563
564 // For now, only analyze induction variables that have simple increments.
565 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
566 if (!IncrOp ||
567 IncrOp->getOpcode() != Instruction::Add ||
568 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
569 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000570 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000571
572 // Make sure the PHI looks like a normal IV.
573 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
574 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000575 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000576 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
577 unsigned BackEdge = !IncomingEdge;
578 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
579 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000580 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000581 if (!L->contains(TrueBB))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000582 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000583
584 // For now, only analyze loops with a constant start value, so that
Dan Gohmanaa036492009-02-14 02:31:09 +0000585 // we can easily determine if the start value is not a maximum value
586 // which would wrap on the first iteration.
Dan Gohmancad24c92009-02-18 16:54:33 +0000587 const ConstantInt *InitialVal =
588 dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
589 if (!InitialVal)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000590 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000591
Dan Gohmanaa036492009-02-14 02:31:09 +0000592 // The original induction variable will start at some non-max value,
593 // it counts up by one, and the loop iterates only while it remans
594 // less than some value in the same type. As such, it will never wrap.
Dan Gohmanf5a309e2009-02-18 17:22:41 +0000595 if (isSigned && !InitialVal->getValue().isMaxSignedValue()) {
Dan Gohmanaa036492009-02-14 02:31:09 +0000596 NoSignedWrap = true;
Dan Gohmanf5a309e2009-02-18 17:22:41 +0000597 } else if (!isSigned && !InitialVal->getValue().isMaxValue())
Dan Gohmanaa036492009-02-14 02:31:09 +0000598 NoUnsignedWrap = true;
Dan Gohmand2067fd2009-02-18 00:52:00 +0000599 return PN;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000600}
601
602bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel5ee99972007-03-07 06:39:01 +0000603 LI = &getAnalysis<LoopInfo>();
604 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000605 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000606
607 // If there are any floating-point or pointer recurrences, attempt to
608 // transform them to use integer recurrences.
609 RewriteNonIntegerIVs(L);
610
Dan Gohmanc2390b12009-02-12 22:19:27 +0000611 BasicBlock *Header = L->getHeader();
612 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000613 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000614
Chris Lattner9caed542007-03-04 01:00:28 +0000615 // Verify the input to the pass in already in LCSSA form.
616 assert(L->isLCSSAForm());
617
Chris Lattner40bf8b42004-04-02 20:24:31 +0000618 // Check to see if this loop has a computable loop-invariant execution count.
619 // If so, this means that we can compute the final value of any expressions
620 // that are recurrent in the loop, and substitute the exit values from the
621 // loop into any instructions outside of the loop that use the final values of
622 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000623 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000624 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
625 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
626 RewriteLoopExitValues(L, BackedgeTakenCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000627
Chris Lattner40bf8b42004-04-02 20:24:31 +0000628 // Next, analyze all of the induction variables in the loop, canonicalizing
629 // auxillary induction variables.
630 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
631
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000632 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
633 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000634 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000635 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000636 // FIXME: It is an extremely bad idea to indvar substitute anything more
637 // complex than affine induction variables. Doing so will put expensive
638 // polynomial evaluations inside of the loop, and the str reduction pass
639 // currently can only reduce affine polynomials. For now just disable
640 // indvar subst on anything more complex than an affine addrec.
641 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
642 if (AR->getLoop() == L && AR->isAffine())
643 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000644 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000645 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000646
Dan Gohmanc2390b12009-02-12 22:19:27 +0000647 // Compute the type of the largest recurrence expression, and collect
648 // the set of the types of the other recurrence expressions.
649 const Type *LargestType = 0;
650 SmallSetVector<const Type *, 4> SizesToInsert;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000651 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
652 LargestType = BackedgeTakenCount->getType();
653 SizesToInsert.insert(BackedgeTakenCount->getType());
Chris Lattnerf50af082004-04-17 18:08:33 +0000654 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000655 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
656 const PHINode *PN = IndVars[i].first;
657 SizesToInsert.insert(PN->getType());
658 const Type *EffTy = getEffectiveIndvarType(PN);
659 SizesToInsert.insert(EffTy);
660 if (!LargestType ||
661 EffTy->getPrimitiveSizeInBits() >
662 LargestType->getPrimitiveSizeInBits())
663 LargestType = EffTy;
Chris Lattner6148c022001-12-03 17:28:42 +0000664 }
665
Chris Lattner40bf8b42004-04-02 20:24:31 +0000666 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000667 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000668
Chris Lattner40bf8b42004-04-02 20:24:31 +0000669 // Now that we know the largest of of the induction variables in this loop,
670 // insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000671 Value *IndVar = 0;
672 if (!SizesToInsert.empty()) {
673 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
674 ++NumInserted;
675 Changed = true;
676 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000677 }
Chris Lattner15cad752003-12-23 07:47:09 +0000678
Dan Gohmanc2390b12009-02-12 22:19:27 +0000679 // If we have a trip count expression, rewrite the loop's exit condition
680 // using it. We can currently only handle loops with a single exit.
Dan Gohmanaa036492009-02-14 02:31:09 +0000681 bool NoSignedWrap = false;
682 bool NoUnsignedWrap = false;
Dan Gohmand2067fd2009-02-18 00:52:00 +0000683 const PHINode *OrigControllingPHI = 0;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000684 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000685 // Can't rewrite non-branch yet.
686 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
687 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmanaa036492009-02-14 02:31:09 +0000688 // Determine if the OrigIV will ever undergo overflow.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000689 OrigControllingPHI =
690 TestOrigIVForWrap(L, BI, OrigCond,
Dan Gohman15cab282009-02-23 23:20:35 +0000691 NoSignedWrap, NoUnsignedWrap);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000692
693 // We'll be replacing the original condition, so it'll be dead.
694 DeadInsts.insert(OrigCond);
695 }
696
Dan Gohman46bdfb02009-02-24 18:55:53 +0000697 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
Dan Gohman15cab282009-02-23 23:20:35 +0000698 ExitingBlock, BI, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000699 }
700
Chris Lattner40bf8b42004-04-02 20:24:31 +0000701 // Now that we have a canonical induction variable, we can rewrite any
702 // recurrences in terms of the induction variable. Start with the auxillary
703 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000704 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000705
Chris Lattner5d461d22004-04-21 22:22:01 +0000706 // If there were induction variables of other sizes, cast the primary
707 // induction variable to the right size for them, avoiding the need for the
708 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000709 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
710 const Type *Ty = SizesToInsert[i];
711 if (Ty != LargestType) {
712 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
713 Rewriter.addInsertedValue(New, SE->getSCEV(New));
714 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
715 << *New << "\n";
Reid Spencera54b7cb2007-01-12 07:05:14 +0000716 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000717 }
718
Chris Lattneree4f13a2007-01-07 01:14:12 +0000719 // Rewrite all induction variables in terms of the canonical induction
720 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000721 while (!IndVars.empty()) {
722 PHINode *PN = IndVars.back().first;
Dan Gohman1a5e9362009-02-17 00:10:53 +0000723 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
724 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
725 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Chris Lattneree4f13a2007-01-07 01:14:12 +0000726 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000727 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000728
Dan Gohmanc2390b12009-02-12 22:19:27 +0000729 /// If the new canonical induction variable is wider than the original,
730 /// and the original has uses that are casts to wider types, see if the
731 /// truncate and extend can be omitted.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000732 if (PN == OrigControllingPHI && PN->getType() != LargestType)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000733 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmanaa036492009-02-14 02:31:09 +0000734 UI != UE; ++UI) {
735 if (isa<SExtInst>(UI) && NoSignedWrap) {
736 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000737 SE->getSignExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000738 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000739 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000740 SCEVHandle ExtendedAddRec =
741 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
742 if (LargestType != UI->getType())
743 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
744 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000745 UI->replaceAllUsesWith(TruncIndVar);
746 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
747 DeadInsts.insert(DeadUse);
748 }
Dan Gohmanaa036492009-02-14 02:31:09 +0000749 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
750 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000751 SE->getZeroExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000752 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000753 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000754 SCEVHandle ExtendedAddRec =
755 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
756 if (LargestType != UI->getType())
757 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
758 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
759 UI->replaceAllUsesWith(TruncIndVar);
760 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
761 DeadInsts.insert(DeadUse);
762 }
763 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000764
Chris Lattner40bf8b42004-04-02 20:24:31 +0000765 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000766 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000767 DeadInsts.insert(PN);
768 IndVars.pop_back();
769 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000770 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000771 }
772
Chris Lattner1363e852004-04-21 23:36:08 +0000773 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner9caed542007-03-04 01:00:28 +0000774 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000775 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000776}
Devang Pateld22a8492008-09-09 21:41:07 +0000777
Devang Patel13877bf2008-11-18 00:40:02 +0000778/// Return true if it is OK to use SIToFPInst for an inducation variable
779/// with given inital and exit values.
780static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
781 uint64_t intIV, uint64_t intEV) {
782
Dan Gohmancafb8132009-02-17 19:13:57 +0000783 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000784 return true;
785
786 // If the iteration range can be handled by SIToFPInst then use it.
787 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000788 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000789 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000790
Devang Patel13877bf2008-11-18 00:40:02 +0000791 return false;
792}
793
794/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000795static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
796
797 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000798 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
799 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000800 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000801 APFloat::rmTowardZero, &isExact)
802 != APFloat::opOK)
803 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000804 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000805 return false;
806 return true;
807
808}
809
Devang Patel58d43d42008-11-03 18:32:19 +0000810/// HandleFloatingPointIV - If the loop has floating induction variable
811/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000812/// For example,
813/// for(double i = 0; i < 10000; ++i)
814/// bar(i)
815/// is converted into
816/// for(int i = 0; i < 10000; ++i)
817/// bar((double)i);
818///
Dan Gohmancafb8132009-02-17 19:13:57 +0000819void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000820 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000821
Devang Patel84e35152008-11-17 21:32:02 +0000822 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
823 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000824
Devang Patel84e35152008-11-17 21:32:02 +0000825 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000826 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
827 if (!InitValue) return;
828 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
829 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
830 return;
831
832 // Check IV increment. Reject this PH if increement operation is not
833 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000834 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000835 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
836 if (!Incr) return;
837 if (Incr->getOpcode() != Instruction::Add) return;
838 ConstantFP *IncrValue = NULL;
839 unsigned IncrVIndex = 1;
840 if (Incr->getOperand(1) == PH)
841 IncrVIndex = 0;
842 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
843 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000844 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
845 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
846 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000847
Devang Patelcd402332008-11-17 23:27:13 +0000848 // Check Incr uses. One user is PH and the other users is exit condition used
849 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000850 Value::use_iterator IncrUse = Incr->use_begin();
851 Instruction *U1 = cast<Instruction>(IncrUse++);
852 if (IncrUse == Incr->use_end()) return;
853 Instruction *U2 = cast<Instruction>(IncrUse++);
854 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000855
Devang Patel84e35152008-11-17 21:32:02 +0000856 // Find exit condition.
857 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
858 if (!EC)
859 EC = dyn_cast<FCmpInst>(U2);
860 if (!EC) return;
861
862 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
863 if (!BI->isConditional()) return;
864 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000865 }
Devang Patel58d43d42008-11-03 18:32:19 +0000866
Devang Patelcd402332008-11-17 23:27:13 +0000867 // Find exit value. If exit value can not be represented as an interger then
868 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000869 ConstantFP *EV = NULL;
870 unsigned EVIndex = 1;
871 if (EC->getOperand(1) == Incr)
872 EVIndex = 0;
873 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
874 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000875 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000876 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000877 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000878
Devang Patel84e35152008-11-17 21:32:02 +0000879 // Find new predicate for integer comparison.
880 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
881 switch (EC->getPredicate()) {
882 case CmpInst::FCMP_OEQ:
883 case CmpInst::FCMP_UEQ:
884 NewPred = CmpInst::ICMP_EQ;
885 break;
886 case CmpInst::FCMP_OGT:
887 case CmpInst::FCMP_UGT:
888 NewPred = CmpInst::ICMP_UGT;
889 break;
890 case CmpInst::FCMP_OGE:
891 case CmpInst::FCMP_UGE:
892 NewPred = CmpInst::ICMP_UGE;
893 break;
894 case CmpInst::FCMP_OLT:
895 case CmpInst::FCMP_ULT:
896 NewPred = CmpInst::ICMP_ULT;
897 break;
898 case CmpInst::FCMP_OLE:
899 case CmpInst::FCMP_ULE:
900 NewPred = CmpInst::ICMP_ULE;
901 break;
902 default:
903 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000904 }
Devang Patel84e35152008-11-17 21:32:02 +0000905 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000906
Devang Patel84e35152008-11-17 21:32:02 +0000907 // Insert new integer induction variable.
908 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
909 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000910 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000911 PH->getIncomingBlock(IncomingEdge));
912
Dan Gohmancafb8132009-02-17 19:13:57 +0000913 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
914 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +0000915 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000916 Incr->getName()+".int", Incr);
917 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
918
919 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
920 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
921 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
Dan Gohmancafb8132009-02-17 19:13:57 +0000922 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +0000923 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +0000924
Devang Patel84e35152008-11-17 21:32:02 +0000925 // Delete old, floating point, exit comparision instruction.
926 EC->replaceAllUsesWith(NewEC);
927 DeadInsts.insert(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000928
Devang Patel84e35152008-11-17 21:32:02 +0000929 // Delete old, floating point, increment instruction.
930 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
931 DeadInsts.insert(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000932
Devang Patel13877bf2008-11-18 00:40:02 +0000933 // Replace floating induction variable. Give SIToFPInst preference over
934 // UIToFPInst because it is faster on platforms that are widely used.
935 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000936 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +0000937 PH->getParent()->getFirstNonPHI());
938 PH->replaceAllUsesWith(Conv);
939 } else {
Dan Gohmancafb8132009-02-17 19:13:57 +0000940 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +0000941 PH->getParent()->getFirstNonPHI());
942 PH->replaceAllUsesWith(Conv);
943 }
Devang Patel84e35152008-11-17 21:32:02 +0000944 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +0000945}
946