1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// 2 // 3 // InductionVariableSimplify - Transform induction variables in a program 4 // to all use a single cannonical induction variable per loop. 5 // 6 //===----------------------------------------------------------------------===// 7 8 #include "llvm/Transforms/Scalar.h" 9 #include "llvm/Analysis/InductionVariable.h" 10 #include "llvm/Analysis/LoopInfo.h" 11 #include "llvm/iPHINode.h" 12 #include "llvm/iOther.h" 13 #include "llvm/Type.h" 14 #include "llvm/Constants.h" 15 #include "llvm/Support/CFG.h" 16 #include "Support/Debug.h" 17 #include "Support/Statistic.h" 18 #include "Support/STLExtras.h" 19 20 namespace { 21 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed"); 22 Statistic<> NumInserted("indvars", "Number of cannonical indvars added"); 23 } 24 25 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a 26 // name... 27 // 28 static Instruction *InsertCast(Value *Val, const Type *Ty, 29 Instruction *InsertBefore) { 30 return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore); 31 } 32 33 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) { 34 // Transform all subloops before this loop... 35 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(), 36 Loop->getSubLoops().end(), 37 std::bind1st(std::ptr_fun(TransformLoop), Loops)); 38 // Get the header node for this loop. All of the phi nodes that could be 39 // induction variables must live in this basic block. 40 // 41 BasicBlock *Header = Loop->getBlocks().front(); 42 43 // Loop over all of the PHI nodes in the basic block, calculating the 44 // induction variables that they represent... stuffing the induction variable 45 // info into a vector... 46 // 47 std::vector<InductionVariable> IndVars; // Induction variables for block 48 BasicBlock::iterator AfterPHIIt = Header->begin(); 49 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt) 50 IndVars.push_back(InductionVariable(PN, Loops)); 51 // AfterPHIIt now points to first nonphi instruction... 52 53 // If there are no phi nodes in this basic block, there can't be indvars... 54 if (IndVars.empty()) return Changed; 55 56 // Loop over the induction variables, looking for a cannonical induction 57 // variable, and checking to make sure they are not all unknown induction 58 // variables. 59 // 60 bool FoundIndVars = false; 61 InductionVariable *Cannonical = 0; 62 for (unsigned i = 0; i < IndVars.size(); ++i) { 63 if (IndVars[i].InductionType == InductionVariable::Cannonical && 64 !isa<PointerType>(IndVars[i].Phi->getType())) 65 Cannonical = &IndVars[i]; 66 if (IndVars[i].InductionType != InductionVariable::Unknown) 67 FoundIndVars = true; 68 } 69 70 // No induction variables, bail early... don't add a cannonnical indvar 71 if (!FoundIndVars) return Changed; 72 73 // Okay, we want to convert other induction variables to use a cannonical 74 // indvar. If we don't have one, add one now... 75 if (!Cannonical) { 76 // Create the PHI node for the new induction variable, and insert the phi 77 // node at the end of the other phi nodes... 78 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", AfterPHIIt); 79 80 // Create the increment instruction to add one to the counter... 81 Instruction *Add = BinaryOperator::create(Instruction::Add, PN, 82 ConstantUInt::get(Type::UIntTy,1), 83 "add1-indvar", AfterPHIIt); 84 85 // Figure out which block is incoming and which is the backedge for the loop 86 BasicBlock *Incoming, *BackEdgeBlock; 87 pred_iterator PI = pred_begin(Header); 88 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!"); 89 if (Loop->contains(*PI)) { // First pred is back edge... 90 BackEdgeBlock = *PI++; 91 Incoming = *PI++; 92 } else { 93 Incoming = *PI++; 94 BackEdgeBlock = *PI++; 95 } 96 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!"); 97 98 // Add incoming values for the PHI node... 99 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming); 100 PN->addIncoming(Add, BackEdgeBlock); 101 102 // Analyze the new induction variable... 103 IndVars.push_back(InductionVariable(PN, Loops)); 104 assert(IndVars.back().InductionType == InductionVariable::Cannonical && 105 "Just inserted cannonical indvar that is not cannonical!"); 106 Cannonical = &IndVars.back(); 107 ++NumInserted; 108 Changed = true; 109 } 110 111 DEBUG(std::cerr << "Induction variables:\n"); 112 113 // Get the current loop iteration count, which is always the value of the 114 // cannonical phi node... 115 // 116 PHINode *IterCount = Cannonical->Phi; 117 118 // Loop through and replace all of the auxillary induction variables with 119 // references to the primary induction variable... 120 // 121 for (unsigned i = 0; i < IndVars.size(); ++i) { 122 InductionVariable *IV = &IndVars[i]; 123 124 DEBUG(IV->print(std::cerr)); 125 126 // Don't do math with pointers... 127 const Type *IVTy = IV->Phi->getType(); 128 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy; 129 130 // Don't modify the cannonical indvar or unrecognized indvars... 131 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) { 132 Instruction *Val = IterCount; 133 if (!isa<ConstantInt>(IV->Step) || // If the step != 1 134 !cast<ConstantInt>(IV->Step)->equalsInt(1)) { 135 136 // If the types are not compatible, insert a cast now... 137 if (Val->getType() != IVTy) 138 Val = InsertCast(Val, IVTy, AfterPHIIt); 139 if (IV->Step->getType() != IVTy) 140 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt); 141 142 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, 143 IV->Phi->getName()+"-scale", AfterPHIIt); 144 } 145 146 // If the start != 0 147 if (IV->Start != Constant::getNullValue(IV->Start->getType())) { 148 // If the types are not compatible, insert a cast now... 149 if (Val->getType() != IVTy) 150 Val = InsertCast(Val, IVTy, AfterPHIIt); 151 if (IV->Start->getType() != IVTy) 152 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt); 153 154 // Insert the instruction after the phi nodes... 155 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, 156 IV->Phi->getName()+"-offset", AfterPHIIt); 157 } 158 159 // If the PHI node has a different type than val is, insert a cast now... 160 if (Val->getType() != IV->Phi->getType()) 161 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt); 162 163 // Replace all uses of the old PHI node with the new computed value... 164 IV->Phi->replaceAllUsesWith(Val); 165 166 // Move the PHI name to it's new equivalent value... 167 std::string OldName = IV->Phi->getName(); 168 IV->Phi->setName(""); 169 Val->setName(OldName); 170 171 // Delete the old, now unused, phi node... 172 Header->getInstList().erase(IV->Phi); 173 Changed = true; 174 ++NumRemoved; 175 } 176 } 177 178 return Changed; 179 } 180 181 namespace { 182 struct InductionVariableSimplify : public FunctionPass { 183 virtual bool runOnFunction(Function &) { 184 LoopInfo &LI = getAnalysis<LoopInfo>(); 185 186 // Induction Variables live in the header nodes of loops 187 return reduce_apply_bool(LI.getTopLevelLoops().begin(), 188 LI.getTopLevelLoops().end(), 189 std::bind1st(std::ptr_fun(TransformLoop), &LI)); 190 } 191 192 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 193 AU.addRequired<LoopInfo>(); 194 AU.setPreservesCFG(); 195 } 196 }; 197 RegisterOpt<InductionVariableSimplify> X("indvars", 198 "Cannonicalize Induction Variables"); 199 } 200 201 Pass *createIndVarSimplifyPass() { 202 return new InductionVariableSimplify(); 203 } 204