blob: 369be4768417287a8785a25ce7b843b25a06d889 [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattnerc01ccfd2003-09-10 05:10:34 +000010// Guarantees that all loops with identifiable, linear, induction variables will
Chris Lattner3adf51d2003-09-10 05:24:46 +000011// be transformed to have a single, canonical, induction variable. After this
Chris Lattnerc01ccfd2003-09-10 05:10:34 +000012// pass runs, it guarantees the the first PHI node of the header block in the
Chris Lattner3adf51d2003-09-10 05:24:46 +000013// loop is the canonical induction variable if there is one.
Chris Lattner6148c022001-12-03 17:28:42 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattner022103b2002-05-07 20:03:00 +000017#include "llvm/Transforms/Scalar.h"
Chris Lattnerba4f3f62003-12-10 18:06:47 +000018#include "llvm/Constants.h"
19#include "llvm/Type.h"
Chris Lattner6148c022001-12-03 17:28:42 +000020#include "llvm/iPHINode.h"
Chris Lattner394437f2001-12-04 04:32:29 +000021#include "llvm/iOther.h"
Chris Lattnerba4f3f62003-12-10 18:06:47 +000022#include "llvm/Analysis/InductionVariable.h"
23#include "llvm/Analysis/LoopInfo.h"
Chris Lattner455889a2002-02-12 22:39:50 +000024#include "llvm/Support/CFG.h"
Chris Lattnerba4f3f62003-12-10 18:06:47 +000025#include "llvm/Transforms/Utils/Local.h"
Chris Lattner6806f562003-08-01 22:15:03 +000026#include "Support/Debug.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000027#include "Support/Statistic.h"
Chris Lattner6806f562003-08-01 22:15:03 +000028#include "Support/STLExtras.h"
Chris Lattnerba4f3f62003-12-10 18:06:47 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner5e761402002-09-10 05:24:05 +000031namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000032 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattner3adf51d2003-09-10 05:24:46 +000033 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattner5e761402002-09-10 05:24:05 +000034}
Chris Lattner394437f2001-12-04 04:32:29 +000035
36// InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
37// name...
38//
Chris Lattner5e761402002-09-10 05:24:05 +000039static Instruction *InsertCast(Value *Val, const Type *Ty,
Chris Lattner2a7c23e2002-09-10 17:04:02 +000040 Instruction *InsertBefore) {
41 return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore);
Chris Lattner394437f2001-12-04 04:32:29 +000042}
43
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000044static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
Chris Lattner6148c022001-12-03 17:28:42 +000045 // Transform all subloops before this loop...
46 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
47 Loop->getSubLoops().end(),
Chris Lattner697954c2002-01-20 22:54:45 +000048 std::bind1st(std::ptr_fun(TransformLoop), Loops));
Chris Lattner6148c022001-12-03 17:28:42 +000049 // Get the header node for this loop. All of the phi nodes that could be
50 // induction variables must live in this basic block.
Chris Lattner3dec1f22002-05-10 15:38:35 +000051 //
Chris Lattner3adf51d2003-09-10 05:24:46 +000052 BasicBlock *Header = Loop->getHeader();
Chris Lattner6148c022001-12-03 17:28:42 +000053
54 // Loop over all of the PHI nodes in the basic block, calculating the
55 // induction variables that they represent... stuffing the induction variable
56 // info into a vector...
57 //
Chris Lattner697954c2002-01-20 22:54:45 +000058 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner7e708292002-06-25 16:13:24 +000059 BasicBlock::iterator AfterPHIIt = Header->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000060 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
Chris Lattner6148c022001-12-03 17:28:42 +000061 IndVars.push_back(InductionVariable(PN, Loops));
Misha Brukmancf00c4a2003-10-10 17:57:28 +000062 // AfterPHIIt now points to first non-phi instruction...
Chris Lattner6148c022001-12-03 17:28:42 +000063
Chris Lattner394437f2001-12-04 04:32:29 +000064 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner6148c022001-12-03 17:28:42 +000065 if (IndVars.empty()) return Changed;
66
Chris Lattner3adf51d2003-09-10 05:24:46 +000067 // Loop over the induction variables, looking for a canonical induction
Chris Lattner6148c022001-12-03 17:28:42 +000068 // variable, and checking to make sure they are not all unknown induction
69 // variables.
70 //
71 bool FoundIndVars = false;
Chris Lattner3adf51d2003-09-10 05:24:46 +000072 InductionVariable *Canonical = 0;
Chris Lattner6148c022001-12-03 17:28:42 +000073 for (unsigned i = 0; i < IndVars.size(); ++i) {
Chris Lattner3adf51d2003-09-10 05:24:46 +000074 if (IndVars[i].InductionType == InductionVariable::Canonical &&
Chris Lattner5e761402002-09-10 05:24:05 +000075 !isa<PointerType>(IndVars[i].Phi->getType()))
Chris Lattner3adf51d2003-09-10 05:24:46 +000076 Canonical = &IndVars[i];
Chris Lattner6148c022001-12-03 17:28:42 +000077 if (IndVars[i].InductionType != InductionVariable::Unknown)
78 FoundIndVars = true;
79 }
80
Chris Lattner3adf51d2003-09-10 05:24:46 +000081 // No induction variables, bail early... don't add a canonical indvar
Chris Lattner6148c022001-12-03 17:28:42 +000082 if (!FoundIndVars) return Changed;
83
Chris Lattner3adf51d2003-09-10 05:24:46 +000084 // Okay, we want to convert other induction variables to use a canonical
Chris Lattner6148c022001-12-03 17:28:42 +000085 // indvar. If we don't have one, add one now...
Chris Lattner3adf51d2003-09-10 05:24:46 +000086 if (!Canonical) {
Chris Lattner2a7c23e2002-09-10 17:04:02 +000087 // Create the PHI node for the new induction variable, and insert the phi
Chris Lattner332ae7f2003-09-23 20:26:48 +000088 // node at the start of the PHI nodes...
89 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", Header->begin());
Chris Lattner394437f2001-12-04 04:32:29 +000090
91 // Create the increment instruction to add one to the counter...
92 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
93 ConstantUInt::get(Type::UIntTy,1),
Chris Lattner2a7c23e2002-09-10 17:04:02 +000094 "add1-indvar", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +000095
96 // Figure out which block is incoming and which is the backedge for the loop
97 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner455889a2002-02-12 22:39:50 +000098 pred_iterator PI = pred_begin(Header);
99 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000100 if (Loop->contains(*PI)) { // First pred is back edge...
101 BackEdgeBlock = *PI++;
102 Incoming = *PI++;
103 } else {
104 Incoming = *PI++;
105 BackEdgeBlock = *PI++;
106 }
Chris Lattner455889a2002-02-12 22:39:50 +0000107 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000108
109 // Add incoming values for the PHI node...
Chris Lattner1a18b7c2002-04-27 02:25:14 +0000110 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
Chris Lattner394437f2001-12-04 04:32:29 +0000111 PN->addIncoming(Add, BackEdgeBlock);
112
113 // Analyze the new induction variable...
114 IndVars.push_back(InductionVariable(PN, Loops));
Chris Lattner3adf51d2003-09-10 05:24:46 +0000115 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
116 "Just inserted canonical indvar that is not canonical!");
117 Canonical = &IndVars.back();
Chris Lattner3dec1f22002-05-10 15:38:35 +0000118 ++NumInserted;
Chris Lattner4753bf22001-12-05 19:41:33 +0000119 Changed = true;
Chris Lattner332ae7f2003-09-23 20:26:48 +0000120 } else {
121 // If we have a canonical induction variable, make sure that it is the first
122 // one in the basic block.
123 if (&Header->front() != Canonical->Phi)
124 Header->getInstList().splice(Header->begin(), Header->getInstList(),
125 Canonical->Phi);
Chris Lattner394437f2001-12-04 04:32:29 +0000126 }
127
Anand Shukla5ba99bd2002-06-25 21:07:58 +0000128 DEBUG(std::cerr << "Induction variables:\n");
Chris Lattner394437f2001-12-04 04:32:29 +0000129
130 // Get the current loop iteration count, which is always the value of the
Chris Lattner3adf51d2003-09-10 05:24:46 +0000131 // canonical phi node...
Chris Lattner394437f2001-12-04 04:32:29 +0000132 //
Chris Lattner3adf51d2003-09-10 05:24:46 +0000133 PHINode *IterCount = Canonical->Phi;
Chris Lattner394437f2001-12-04 04:32:29 +0000134
Chris Lattner3adf51d2003-09-10 05:24:46 +0000135 // Loop through and replace all of the auxiliary induction variables with
136 // references to the canonical induction variable...
Chris Lattner394437f2001-12-04 04:32:29 +0000137 //
Chris Lattner394437f2001-12-04 04:32:29 +0000138 for (unsigned i = 0; i < IndVars.size(); ++i) {
139 InductionVariable *IV = &IndVars[i];
Chris Lattnerf016ea42002-05-22 17:17:27 +0000140
Chris Lattnera59cbb22002-07-27 01:12:17 +0000141 DEBUG(IV->print(std::cerr));
Chris Lattnerf016ea42002-05-22 17:17:27 +0000142
Chris Lattner5e761402002-09-10 05:24:05 +0000143 // Don't do math with pointers...
144 const Type *IVTy = IV->Phi->getType();
145 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
146
Chris Lattner3adf51d2003-09-10 05:24:46 +0000147 // Don't modify the canonical indvar or unrecognized indvars...
148 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner394437f2001-12-04 04:32:29 +0000149 Instruction *Val = IterCount;
150 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
151 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner394437f2001-12-04 04:32:29 +0000152
153 // If the types are not compatible, insert a cast now...
Chris Lattner5e761402002-09-10 05:24:05 +0000154 if (Val->getType() != IVTy)
155 Val = InsertCast(Val, IVTy, AfterPHIIt);
156 if (IV->Step->getType() != IVTy)
157 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000158
Chris Lattner5e761402002-09-10 05:24:05 +0000159 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000160 IV->Phi->getName()+"-scale", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000161 }
162
Chris Lattner5e761402002-09-10 05:24:05 +0000163 // If the start != 0
164 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
Chris Lattner394437f2001-12-04 04:32:29 +0000165 // If the types are not compatible, insert a cast now...
Chris Lattner5e761402002-09-10 05:24:05 +0000166 if (Val->getType() != IVTy)
167 Val = InsertCast(Val, IVTy, AfterPHIIt);
168 if (IV->Start->getType() != IVTy)
169 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000170
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000171 // Insert the instruction after the phi nodes...
Chris Lattner5e761402002-09-10 05:24:05 +0000172 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000173 IV->Phi->getName()+"-offset", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000174 }
175
176 // If the PHI node has a different type than val is, insert a cast now...
177 if (Val->getType() != IV->Phi->getType())
Chris Lattner7e708292002-06-25 16:13:24 +0000178 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000179
180 // Replace all uses of the old PHI node with the new computed value...
181 IV->Phi->replaceAllUsesWith(Val);
182
183 // Move the PHI name to it's new equivalent value...
Chris Lattner697954c2002-01-20 22:54:45 +0000184 std::string OldName = IV->Phi->getName();
Chris Lattner394437f2001-12-04 04:32:29 +0000185 IV->Phi->setName("");
186 Val->setName(OldName);
187
Chris Lattnerba4f3f62003-12-10 18:06:47 +0000188 // Get the incoming values used by the PHI node
189 std::vector<Value*> PHIOps;
190 PHIOps.reserve(IV->Phi->getNumIncomingValues());
191 for (unsigned i = 0, e = IV->Phi->getNumIncomingValues(); i != e; ++i)
192 PHIOps.push_back(IV->Phi->getIncomingValue(i));
193
Chris Lattner394437f2001-12-04 04:32:29 +0000194 // Delete the old, now unused, phi node...
Chris Lattner7e708292002-06-25 16:13:24 +0000195 Header->getInstList().erase(IV->Phi);
Chris Lattnerba4f3f62003-12-10 18:06:47 +0000196
197 // If the PHI is the last user of any instructions for computing PHI nodes
198 // that are irrelevant now, delete those instructions.
199 while (!PHIOps.empty()) {
200 Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back());
201 PHIOps.pop_back();
202
203 if (MaybeDead && isInstructionTriviallyDead(MaybeDead)) {
204 PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(),
205 MaybeDead->op_end());
206 MaybeDead->getParent()->getInstList().erase(MaybeDead);
207 }
208 }
209
Chris Lattner4753bf22001-12-05 19:41:33 +0000210 Changed = true;
Chris Lattner3dec1f22002-05-10 15:38:35 +0000211 ++NumRemoved;
Chris Lattner394437f2001-12-04 04:32:29 +0000212 }
Chris Lattner6148c022001-12-03 17:28:42 +0000213 }
214
215 return Changed;
216}
217
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000218namespace {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000219 struct InductionVariableSimplify : public FunctionPass {
Chris Lattner7e708292002-06-25 16:13:24 +0000220 virtual bool runOnFunction(Function &) {
Chris Lattner3dec1f22002-05-10 15:38:35 +0000221 LoopInfo &LI = getAnalysis<LoopInfo>();
222
223 // Induction Variables live in the header nodes of loops
224 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
225 LI.getTopLevelLoops().end(),
226 std::bind1st(std::ptr_fun(TransformLoop), &LI));
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000227 }
228
Chris Lattnerf57b8452002-04-27 06:56:12 +0000229 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner5f0eb8d2002-08-08 19:01:30 +0000230 AU.addRequired<LoopInfo>();
Chris Lattner98bf4362003-10-12 21:52:28 +0000231 AU.addRequiredID(LoopSimplifyID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000232 AU.setPreservesCFG();
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000233 }
234 };
Chris Lattnera6275cc2002-07-26 21:12:46 +0000235 RegisterOpt<InductionVariableSimplify> X("indvars",
Chris Lattner3adf51d2003-09-10 05:24:46 +0000236 "Canonicalize Induction Variables");
Chris Lattner793c6b82002-01-31 00:45:11 +0000237}
238
Chris Lattnerba4f3f62003-12-10 18:06:47 +0000239Pass *llvm::createIndVarSimplifyPass() {
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000240 return new InductionVariableSimplify();
Chris Lattner793c6b82002-01-31 00:45:11 +0000241}
Brian Gaeked0fde302003-11-11 22:41:34 +0000242