1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Guarantees that all loops with identifiable, linear, induction variables will
11 // be transformed to have a single, canonical, induction variable. After this
12 // pass runs, it guarantees the the first PHI node of the header block in the
13 // loop is the canonical induction variable if there is one.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Type.h"
20 #include "llvm/iPHINode.h"
21 #include "llvm/iOther.h"
22 #include "llvm/Analysis/InductionVariable.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "Support/Debug.h"
27 #include "Support/Statistic.h"
28 #include "Support/STLExtras.h"
32 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
33 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
36 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
39 static Instruction *InsertCast(Value *Val, const Type *Ty,
40 Instruction *InsertBefore) {
41 return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore);
44 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
45 // Transform all subloops before this loop...
46 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
47 Loop->getSubLoops().end(),
48 std::bind1st(std::ptr_fun(TransformLoop), Loops));
49 // Get the header node for this loop. All of the phi nodes that could be
50 // induction variables must live in this basic block.
52 BasicBlock *Header = Loop->getHeader();
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...
58 std::vector<InductionVariable> IndVars; // Induction variables for block
59 BasicBlock::iterator AfterPHIIt = Header->begin();
60 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
61 IndVars.push_back(InductionVariable(PN, Loops));
62 // AfterPHIIt now points to first non-phi instruction...
64 // If there are no phi nodes in this basic block, there can't be indvars...
65 if (IndVars.empty()) return Changed;
67 // Loop over the induction variables, looking for a canonical induction
68 // variable, and checking to make sure they are not all unknown induction
71 bool FoundIndVars = false;
72 InductionVariable *Canonical = 0;
73 for (unsigned i = 0; i < IndVars.size(); ++i) {
74 if (IndVars[i].InductionType == InductionVariable::Canonical &&
75 !isa<PointerType>(IndVars[i].Phi->getType()))
76 Canonical = &IndVars[i];
77 if (IndVars[i].InductionType != InductionVariable::Unknown)
81 // No induction variables, bail early... don't add a canonical indvar
82 if (!FoundIndVars) return Changed;
84 // Okay, we want to convert other induction variables to use a canonical
85 // indvar. If we don't have one, add one now...
87 // Create the PHI node for the new induction variable, and insert the phi
88 // node at the start of the PHI nodes...
89 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", Header->begin());
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),
94 "add1-indvar", AfterPHIIt);
96 // Figure out which block is incoming and which is the backedge for the loop
97 BasicBlock *Incoming, *BackEdgeBlock;
98 pred_iterator PI = pred_begin(Header);
99 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
100 if (Loop->contains(*PI)) { // First pred is back edge...
101 BackEdgeBlock = *PI++;
105 BackEdgeBlock = *PI++;
107 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
109 // Add incoming values for the PHI node...
110 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
111 PN->addIncoming(Add, BackEdgeBlock);
113 // Analyze the new induction variable...
114 IndVars.push_back(InductionVariable(PN, Loops));
115 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
116 "Just inserted canonical indvar that is not canonical!");
117 Canonical = &IndVars.back();
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(),
128 DEBUG(std::cerr << "Induction variables:\n");
130 // Get the current loop iteration count, which is always the value of the
131 // canonical phi node...
133 PHINode *IterCount = Canonical->Phi;
135 // Loop through and replace all of the auxiliary induction variables with
136 // references to the canonical induction variable...
138 for (unsigned i = 0; i < IndVars.size(); ++i) {
139 InductionVariable *IV = &IndVars[i];
141 DEBUG(IV->print(std::cerr));
143 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
145 // Don't do math with pointers...
146 const Type *IVTy = IV->Phi->getType();
147 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
149 // Don't modify the canonical indvar or unrecognized indvars...
150 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
151 Instruction *Val = IterCount;
152 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
153 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
155 // If the types are not compatible, insert a cast now...
156 if (Val->getType() != IVTy)
157 Val = InsertCast(Val, IVTy, AfterPHIIt);
158 if (IV->Step->getType() != IVTy)
159 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
161 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
162 IV->Phi->getName()+"-scale", AfterPHIIt);
166 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
167 // If the types are not compatible, insert a cast now...
168 if (Val->getType() != IVTy)
169 Val = InsertCast(Val, IVTy, AfterPHIIt);
170 if (IV->Start->getType() != IVTy)
171 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
173 // Insert the instruction after the phi nodes...
174 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
175 IV->Phi->getName()+"-offset", AfterPHIIt);
178 // If the PHI node has a different type than val is, insert a cast now...
179 if (Val->getType() != IV->Phi->getType())
180 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
182 // Replace all uses of the old PHI node with the new computed value...
183 IV->Phi->replaceAllUsesWith(Val);
185 // Move the PHI name to it's new equivalent value...
186 std::string OldName = IV->Phi->getName();
187 IV->Phi->setName("");
188 Val->setName(OldName);
190 // Get the incoming values used by the PHI node
191 std::vector<Value*> PHIOps;
192 PHIOps.reserve(IV->Phi->getNumIncomingValues());
193 for (unsigned i = 0, e = IV->Phi->getNumIncomingValues(); i != e; ++i)
194 PHIOps.push_back(IV->Phi->getIncomingValue(i));
196 // Delete the old, now unused, phi node...
197 Header->getInstList().erase(IV->Phi);
199 // If the PHI is the last user of any instructions for computing PHI nodes
200 // that are irrelevant now, delete those instructions.
201 while (!PHIOps.empty()) {
202 Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back());
205 if (MaybeDead && isInstructionTriviallyDead(MaybeDead)) {
206 PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(),
207 MaybeDead->op_end());
208 MaybeDead->getParent()->getInstList().erase(MaybeDead);
210 // Erasing the instruction could invalidate the AfterPHI iterator!
211 AfterPHIIt = Header->begin();
224 struct InductionVariableSimplify : public FunctionPass {
225 virtual bool runOnFunction(Function &) {
226 LoopInfo &LI = getAnalysis<LoopInfo>();
228 // Induction Variables live in the header nodes of loops
229 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
230 LI.getTopLevelLoops().end(),
231 std::bind1st(std::ptr_fun(TransformLoop), &LI));
234 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
235 AU.addRequired<LoopInfo>();
236 AU.addRequiredID(LoopSimplifyID);
237 AU.setPreservesCFG();
240 RegisterOpt<InductionVariableSimplify> X("indvars",
241 "Canonicalize Induction Variables");
244 Pass *llvm::createIndVarSimplifyPass() {
245 return new InductionVariableSimplify();