Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 1 | //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
John Criswell | b576c94 | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 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. |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
John Criswell | b576c94 | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 9 | // |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 10 | // 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 | // |
| 14 | // This transformation make the following changes to each loop with an |
| 15 | // 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 Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 37 | // |
| 38 | //===----------------------------------------------------------------------===// |
| 39 | |
Chris Lattner | 022103b | 2002-05-07 20:03:00 +0000 | [diff] [blame] | 40 | #include "llvm/Transforms/Scalar.h" |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 41 | #include "llvm/BasicBlock.h" |
Chris Lattner | 59fdaee | 2004-04-15 15:21:43 +0000 | [diff] [blame] | 42 | #include "llvm/Constants.h" |
Chris Lattner | 18b3c97 | 2003-12-22 05:02:01 +0000 | [diff] [blame] | 43 | #include "llvm/Instructions.h" |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 44 | #include "llvm/Type.h" |
Nate Begeman | 36f891b | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 45 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
John Criswell | 47df12d | 2003-12-18 17:19:19 +0000 | [diff] [blame] | 46 | #include "llvm/Analysis/LoopInfo.h" |
Chris Lattner | 455889a | 2002-02-12 22:39:50 +0000 | [diff] [blame] | 47 | #include "llvm/Support/CFG.h" |
Chris Lattner | a4b9c78 | 2004-10-11 23:06:50 +0000 | [diff] [blame] | 48 | #include "llvm/Support/GetElementPtrTypeIterator.h" |
John Criswell | 47df12d | 2003-12-18 17:19:19 +0000 | [diff] [blame] | 49 | #include "llvm/Transforms/Utils/Local.h" |
Reid Spencer | 551ccae | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 50 | #include "llvm/Support/CommandLine.h" |
| 51 | #include "llvm/ADT/Statistic.h" |
John Criswell | 47df12d | 2003-12-18 17:19:19 +0000 | [diff] [blame] | 52 | using namespace llvm; |
Brian Gaeke | d0fde30 | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 53 | |
Chris Lattner | 5e76140 | 2002-09-10 05:24:05 +0000 | [diff] [blame] | 54 | namespace { |
Chris Lattner | a92f696 | 2002-10-01 22:38:41 +0000 | [diff] [blame] | 55 | Statistic<> NumRemoved ("indvars", "Number of aux indvars removed"); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 56 | Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted"); |
Chris Lattner | 3adf51d | 2003-09-10 05:24:46 +0000 | [diff] [blame] | 57 | Statistic<> NumInserted("indvars", "Number of canonical indvars added"); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 58 | Statistic<> NumReplaced("indvars", "Number of exit values replaced"); |
| 59 | Statistic<> NumLFTR ("indvars", "Number of loop exit tests replaced"); |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 60 | |
| 61 | class IndVarSimplify : public FunctionPass { |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 62 | LoopInfo *LI; |
| 63 | ScalarEvolution *SE; |
Chris Lattner | 15cad75 | 2003-12-23 07:47:09 +0000 | [diff] [blame] | 64 | bool Changed; |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 65 | public: |
| 66 | virtual bool runOnFunction(Function &) { |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 67 | LI = &getAnalysis<LoopInfo>(); |
| 68 | SE = &getAnalysis<ScalarEvolution>(); |
Chris Lattner | 15cad75 | 2003-12-23 07:47:09 +0000 | [diff] [blame] | 69 | Changed = false; |
| 70 | |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 71 | // Induction Variables live in the header nodes of loops |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 72 | for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) |
Chris Lattner | 329c1c6 | 2004-01-08 00:09:44 +0000 | [diff] [blame] | 73 | runOnLoop(*I); |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 74 | return Changed; |
| 75 | } |
| 76 | |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 77 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 78 | AU.addRequiredID(LoopSimplifyID); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 79 | AU.addRequired<ScalarEvolution>(); |
| 80 | AU.addRequired<LoopInfo>(); |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 81 | AU.addPreservedID(LoopSimplifyID); |
| 82 | AU.setPreservesCFG(); |
| 83 | } |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 84 | private: |
| 85 | void runOnLoop(Loop *L); |
| 86 | void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader, |
| 87 | std::set<Instruction*> &DeadInsts); |
| 88 | void LinearFunctionTestReplace(Loop *L, SCEV *IterationCount, |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 89 | SCEVExpander &RW); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 90 | void RewriteLoopExitValues(Loop *L); |
| 91 | |
| 92 | void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts); |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 93 | }; |
| 94 | RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables"); |
Chris Lattner | 5e76140 | 2002-09-10 05:24:05 +0000 | [diff] [blame] | 95 | } |
Chris Lattner | 394437f | 2001-12-04 04:32:29 +0000 | [diff] [blame] | 96 | |
Chris Lattner | 4b50156 | 2004-09-20 04:43:15 +0000 | [diff] [blame] | 97 | FunctionPass *llvm::createIndVarSimplifyPass() { |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 98 | return new IndVarSimplify(); |
Chris Lattner | 394437f | 2001-12-04 04:32:29 +0000 | [diff] [blame] | 99 | } |
| 100 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 101 | /// DeleteTriviallyDeadInstructions - If any of the instructions is the |
| 102 | /// specified set are trivially dead, delete them and see if this makes any of |
| 103 | /// their operands subsequently dead. |
| 104 | void IndVarSimplify:: |
| 105 | DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) { |
| 106 | while (!Insts.empty()) { |
| 107 | Instruction *I = *Insts.begin(); |
| 108 | Insts.erase(Insts.begin()); |
| 109 | if (isInstructionTriviallyDead(I)) { |
| 110 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) |
| 111 | if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i))) |
| 112 | Insts.insert(U); |
| 113 | SE->deleteInstructionFromRecords(I); |
Chris Lattner | a4b9c78 | 2004-10-11 23:06:50 +0000 | [diff] [blame] | 114 | I->eraseFromParent(); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 115 | Changed = true; |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | |
| 121 | /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer |
| 122 | /// recurrence. If so, change it into an integer recurrence, permitting |
| 123 | /// analysis by the SCEV routines. |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 124 | void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN, |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 125 | BasicBlock *Preheader, |
| 126 | std::set<Instruction*> &DeadInsts) { |
| 127 | assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!"); |
| 128 | unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader); |
| 129 | unsigned BackedgeIdx = PreheaderIdx^1; |
| 130 | if (GetElementPtrInst *GEPI = |
Chris Lattner | cda9ca5 | 2005-08-10 01:12:06 +0000 | [diff] [blame] | 131 | dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx))) |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 132 | if (GEPI->getOperand(0) == PN) { |
Chris Lattner | cda9ca5 | 2005-08-10 01:12:06 +0000 | [diff] [blame] | 133 | assert(GEPI->getNumOperands() == 2 && "GEP types must match!"); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 134 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 135 | // Okay, we found a pointer recurrence. Transform this pointer |
| 136 | // recurrence into an integer recurrence. Compute the value that gets |
| 137 | // added to the pointer at every iteration. |
| 138 | Value *AddedVal = GEPI->getOperand(1); |
| 139 | |
| 140 | // Insert a new integer PHI node into the top of the block. |
| 141 | PHINode *NewPhi = new PHINode(AddedVal->getType(), |
| 142 | PN->getName()+".rec", PN); |
Chris Lattner | c5c5e6a | 2004-06-20 05:04:01 +0000 | [diff] [blame] | 143 | NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader); |
| 144 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 145 | // Create the new add instruction. |
Chris Lattner | c5c5e6a | 2004-06-20 05:04:01 +0000 | [diff] [blame] | 146 | Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal, |
| 147 | GEPI->getName()+".rec", GEPI); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 148 | NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx)); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 149 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 150 | // Update the existing GEP to use the recurrence. |
| 151 | GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx)); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 152 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 153 | // Update the GEP to use the new recurrence we just inserted. |
| 154 | GEPI->setOperand(1, NewAdd); |
| 155 | |
Chris Lattner | a4b9c78 | 2004-10-11 23:06:50 +0000 | [diff] [blame] | 156 | // If the incoming value is a constant expr GEP, try peeling out the array |
| 157 | // 0 index if possible to make things simpler. |
| 158 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0))) |
| 159 | if (CE->getOpcode() == Instruction::GetElementPtr) { |
| 160 | unsigned NumOps = CE->getNumOperands(); |
| 161 | assert(NumOps > 1 && "CE folding didn't work!"); |
| 162 | if (CE->getOperand(NumOps-1)->isNullValue()) { |
| 163 | // Check to make sure the last index really is an array index. |
Chris Lattner | 1730078 | 2005-11-18 18:30:47 +0000 | [diff] [blame] | 164 | gep_type_iterator GTI = gep_type_begin(CE); |
Chris Lattner | ceda605 | 2005-11-17 19:35:42 +0000 | [diff] [blame] | 165 | for (unsigned i = 1, e = CE->getNumOperands()-1; |
Chris Lattner | a4b9c78 | 2004-10-11 23:06:50 +0000 | [diff] [blame] | 166 | i != e; ++i, ++GTI) |
| 167 | /*empty*/; |
| 168 | if (isa<SequentialType>(*GTI)) { |
| 169 | // Pull the last index out of the constant expr GEP. |
| 170 | std::vector<Value*> CEIdxs(CE->op_begin()+1, CE->op_end()-1); |
| 171 | Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0), |
| 172 | CEIdxs); |
| 173 | GetElementPtrInst *NGEPI = |
| 174 | new GetElementPtrInst(NCE, Constant::getNullValue(Type::IntTy), |
| 175 | NewAdd, GEPI->getName(), GEPI); |
| 176 | GEPI->replaceAllUsesWith(NGEPI); |
| 177 | GEPI->eraseFromParent(); |
| 178 | GEPI = NGEPI; |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 184 | // Finally, if there are any other users of the PHI node, we must |
| 185 | // insert a new GEP instruction that uses the pre-incremented version |
| 186 | // of the induction amount. |
| 187 | if (!PN->use_empty()) { |
| 188 | BasicBlock::iterator InsertPos = PN; ++InsertPos; |
| 189 | while (isa<PHINode>(InsertPos)) ++InsertPos; |
| 190 | std::string Name = PN->getName(); PN->setName(""); |
| 191 | Value *PreInc = |
| 192 | new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx), |
| 193 | std::vector<Value*>(1, NewPhi), Name, |
| 194 | InsertPos); |
| 195 | PN->replaceAllUsesWith(PreInc); |
| 196 | } |
| 197 | |
| 198 | // Delete the old PHI for sure, and the GEP if its otherwise unused. |
| 199 | DeadInsts.insert(PN); |
| 200 | |
| 201 | ++NumPointer; |
| 202 | Changed = true; |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | /// LinearFunctionTestReplace - This method rewrites the exit condition of the |
Chris Lattner | 59fdaee | 2004-04-15 15:21:43 +0000 | [diff] [blame] | 207 | /// loop to be a canonical != comparison against the incremented loop induction |
| 208 | /// variable. This pass is able to rewrite the exit tests of any loop where the |
| 209 | /// SCEV analysis can determine a loop-invariant trip count of the loop, which |
| 210 | /// is actually a much broader range than just linear tests. |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 211 | void IndVarSimplify::LinearFunctionTestReplace(Loop *L, SCEV *IterationCount, |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 212 | SCEVExpander &RW) { |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 213 | // Find the exit block for the loop. We can currently only handle loops with |
| 214 | // a single exit. |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 215 | std::vector<BasicBlock*> ExitBlocks; |
| 216 | L->getExitBlocks(ExitBlocks); |
| 217 | if (ExitBlocks.size() != 1) return; |
| 218 | BasicBlock *ExitBlock = ExitBlocks[0]; |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 219 | |
| 220 | // Make sure there is only one predecessor block in the loop. |
| 221 | BasicBlock *ExitingBlock = 0; |
| 222 | for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock); |
| 223 | PI != PE; ++PI) |
| 224 | if (L->contains(*PI)) { |
| 225 | if (ExitingBlock == 0) |
| 226 | ExitingBlock = *PI; |
| 227 | else |
| 228 | return; // Multiple exits from loop to this block. |
| 229 | } |
| 230 | assert(ExitingBlock && "Loop info is broken"); |
| 231 | |
| 232 | if (!isa<BranchInst>(ExitingBlock->getTerminator())) |
| 233 | return; // Can't rewrite non-branch yet |
| 234 | BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator()); |
| 235 | assert(BI->isConditional() && "Must be conditional to be part of loop!"); |
| 236 | |
| 237 | std::set<Instruction*> InstructionsToDelete; |
| 238 | if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition())) |
| 239 | InstructionsToDelete.insert(Cond); |
| 240 | |
Chris Lattner | d244057 | 2004-04-15 20:26:22 +0000 | [diff] [blame] | 241 | // If the exiting block is not the same as the backedge block, we must compare |
| 242 | // against the preincremented value, otherwise we prefer to compare against |
| 243 | // the post-incremented value. |
| 244 | BasicBlock *Header = L->getHeader(); |
| 245 | pred_iterator HPI = pred_begin(Header); |
| 246 | assert(HPI != pred_end(Header) && "Loop with zero preds???"); |
| 247 | if (!L->contains(*HPI)) ++HPI; |
| 248 | assert(HPI != pred_end(Header) && L->contains(*HPI) && |
| 249 | "No backedge in loop?"); |
Chris Lattner | 59fdaee | 2004-04-15 15:21:43 +0000 | [diff] [blame] | 250 | |
Chris Lattner | d244057 | 2004-04-15 20:26:22 +0000 | [diff] [blame] | 251 | SCEVHandle TripCount = IterationCount; |
| 252 | Value *IndVar; |
| 253 | if (*HPI == ExitingBlock) { |
| 254 | // The IterationCount expression contains the number of times that the |
| 255 | // backedge actually branches to the loop header. This is one less than the |
| 256 | // number of times the loop executes, so add one to it. |
| 257 | Constant *OneC = ConstantInt::get(IterationCount->getType(), 1); |
| 258 | TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC)); |
| 259 | IndVar = L->getCanonicalInductionVariableIncrement(); |
| 260 | } else { |
| 261 | // We have to use the preincremented value... |
| 262 | IndVar = L->getCanonicalInductionVariable(); |
| 263 | } |
Chris Lattner | 59fdaee | 2004-04-15 15:21:43 +0000 | [diff] [blame] | 264 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 265 | // Expand the code for the iteration count into the preheader of the loop. |
| 266 | BasicBlock *Preheader = L->getLoopPreheader(); |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 267 | Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(), |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 268 | IndVar->getType()); |
| 269 | |
| 270 | // Insert a new setne or seteq instruction before the branch. |
| 271 | Instruction::BinaryOps Opcode; |
| 272 | if (L->contains(BI->getSuccessor(0))) |
| 273 | Opcode = Instruction::SetNE; |
| 274 | else |
| 275 | Opcode = Instruction::SetEQ; |
| 276 | |
| 277 | Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI); |
| 278 | BI->setCondition(Cond); |
| 279 | ++NumLFTR; |
| 280 | Changed = true; |
| 281 | |
| 282 | DeleteTriviallyDeadInstructions(InstructionsToDelete); |
| 283 | } |
| 284 | |
| 285 | |
| 286 | /// RewriteLoopExitValues - Check to see if this loop has a computable |
| 287 | /// loop-invariant execution count. If so, this means that we can compute the |
| 288 | /// final value of any expressions that are recurrent in the loop, and |
| 289 | /// substitute the exit values from the loop into any instructions outside of |
| 290 | /// the loop that use the final values of the current expressions. |
| 291 | void IndVarSimplify::RewriteLoopExitValues(Loop *L) { |
| 292 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 293 | |
| 294 | // Scan all of the instructions in the loop, looking at those that have |
| 295 | // extra-loop users and which are recurrences. |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 296 | SCEVExpander Rewriter(*SE, *LI); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 297 | |
| 298 | // We insert the code into the preheader of the loop if the loop contains |
| 299 | // multiple exit blocks, or in the exit block if there is exactly one. |
| 300 | BasicBlock *BlockToInsertInto; |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 301 | std::vector<BasicBlock*> ExitBlocks; |
| 302 | L->getExitBlocks(ExitBlocks); |
| 303 | if (ExitBlocks.size() == 1) |
| 304 | BlockToInsertInto = ExitBlocks[0]; |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 305 | else |
| 306 | BlockToInsertInto = Preheader; |
| 307 | BasicBlock::iterator InsertPt = BlockToInsertInto->begin(); |
| 308 | while (isa<PHINode>(InsertPt)) ++InsertPt; |
| 309 | |
Chris Lattner | 20aa098 | 2004-04-17 18:44:09 +0000 | [diff] [blame] | 310 | bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L)); |
| 311 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 312 | std::set<Instruction*> InstructionsToDelete; |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 313 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 314 | for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) |
| 315 | if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop... |
| 316 | BasicBlock *BB = L->getBlocks()[i]; |
Chris Lattner | 4bd09d7 | 2005-06-15 21:29:31 +0000 | [diff] [blame] | 317 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 318 | if (I->getType()->isInteger()) { // Is an integer instruction |
| 319 | SCEVHandle SH = SE->getSCEV(I); |
Chris Lattner | 20aa098 | 2004-04-17 18:44:09 +0000 | [diff] [blame] | 320 | if (SH->hasComputableLoopEvolution(L) || // Varies predictably |
| 321 | HasConstantItCount) { |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 322 | // Find out if this predictably varying value is actually used |
| 323 | // outside of the loop. "extra" as opposed to "intra". |
Chris Lattner | eb83f4e | 2006-06-17 01:02:31 +0000 | [diff] [blame^] | 324 | std::vector<Instruction*> ExtraLoopUsers; |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 325 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); |
Chris Lattner | eb83f4e | 2006-06-17 01:02:31 +0000 | [diff] [blame^] | 326 | UI != E; ++UI) { |
| 327 | Instruction *User = cast<Instruction>(*UI); |
| 328 | if (!L->contains(User->getParent())) { |
| 329 | // If this is a PHI node in the exit block and we're inserting, |
| 330 | // into the exit block, it must have a single entry. In this |
| 331 | // case, we can't insert the code after the PHI and have the PHI |
| 332 | // still use it. Instead, don't insert the the PHI. |
| 333 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
| 334 | // FIXME: This is a case where LCSSA pessimizes code, this |
| 335 | // should be fixed better. |
| 336 | if (PN->getNumOperands() == 2 && |
| 337 | PN->getParent() == BlockToInsertInto) |
| 338 | continue; |
| 339 | } |
| 340 | ExtraLoopUsers.push_back(User); |
| 341 | } |
| 342 | } |
| 343 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 344 | if (!ExtraLoopUsers.empty()) { |
| 345 | // Okay, this instruction has a user outside of the current loop |
| 346 | // and varies predictably in this loop. Evaluate the value it |
| 347 | // contains when the loop exits, and insert code for it. |
Chris Lattner | 20aa098 | 2004-04-17 18:44:09 +0000 | [diff] [blame] | 348 | SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop()); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 349 | if (!isa<SCEVCouldNotCompute>(ExitValue)) { |
| 350 | Changed = true; |
| 351 | ++NumReplaced; |
Chris Lattner | 4bd09d7 | 2005-06-15 21:29:31 +0000 | [diff] [blame] | 352 | // Remember the next instruction. The rewriter can move code |
| 353 | // around in some cases. |
| 354 | BasicBlock::iterator NextI = I; ++NextI; |
| 355 | |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 356 | Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt, |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 357 | I->getType()); |
| 358 | |
| 359 | // Rewrite any users of the computed value outside of the loop |
| 360 | // with the newly computed value. |
| 361 | for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) |
| 362 | ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal); |
| 363 | |
| 364 | // If this instruction is dead now, schedule it to be removed. |
| 365 | if (I->use_empty()) |
| 366 | InstructionsToDelete.insert(I); |
Chris Lattner | 4bd09d7 | 2005-06-15 21:29:31 +0000 | [diff] [blame] | 367 | I = NextI; |
| 368 | continue; // Skip the ++I |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 369 | } |
| 370 | } |
| 371 | } |
| 372 | } |
Chris Lattner | 4bd09d7 | 2005-06-15 21:29:31 +0000 | [diff] [blame] | 373 | |
| 374 | // Next instruction. Continue instruction skips this. |
| 375 | ++I; |
| 376 | } |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 377 | } |
| 378 | |
| 379 | DeleteTriviallyDeadInstructions(InstructionsToDelete); |
| 380 | } |
| 381 | |
| 382 | |
| 383 | void IndVarSimplify::runOnLoop(Loop *L) { |
| 384 | // First step. Check to see if there are any trivial GEP pointer recurrences. |
| 385 | // If there are, change them into integer recurrences, permitting analysis by |
| 386 | // the SCEV routines. |
| 387 | // |
| 388 | BasicBlock *Header = L->getHeader(); |
| 389 | BasicBlock *Preheader = L->getLoopPreheader(); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 390 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 391 | std::set<Instruction*> DeadInsts; |
Reid Spencer | 2da5c3d | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 392 | for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { |
| 393 | PHINode *PN = cast<PHINode>(I); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 394 | if (isa<PointerType>(PN->getType())) |
| 395 | EliminatePointerRecurrence(PN, Preheader, DeadInsts); |
Reid Spencer | 2da5c3d | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 396 | } |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 397 | |
| 398 | if (!DeadInsts.empty()) |
| 399 | DeleteTriviallyDeadInstructions(DeadInsts); |
| 400 | |
| 401 | |
| 402 | // Next, transform all loops nesting inside of this loop. |
| 403 | for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I) |
Chris Lattner | 329c1c6 | 2004-01-08 00:09:44 +0000 | [diff] [blame] | 404 | runOnLoop(*I); |
Chris Lattner | 3324e71 | 2003-12-22 03:58:44 +0000 | [diff] [blame] | 405 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 406 | // Check to see if this loop has a computable loop-invariant execution count. |
| 407 | // If so, this means that we can compute the final value of any expressions |
| 408 | // that are recurrent in the loop, and substitute the exit values from the |
| 409 | // loop into any instructions outside of the loop that use the final values of |
| 410 | // the current expressions. |
Chris Lattner | 3dec1f2 | 2002-05-10 15:38:35 +0000 | [diff] [blame] | 411 | // |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 412 | SCEVHandle IterationCount = SE->getIterationCount(L); |
| 413 | if (!isa<SCEVCouldNotCompute>(IterationCount)) |
| 414 | RewriteLoopExitValues(L); |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 415 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 416 | // Next, analyze all of the induction variables in the loop, canonicalizing |
| 417 | // auxillary induction variables. |
| 418 | std::vector<std::pair<PHINode*, SCEVHandle> > IndVars; |
| 419 | |
Reid Spencer | 2da5c3d | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 420 | for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { |
| 421 | PHINode *PN = cast<PHINode>(I); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 422 | if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable! |
| 423 | SCEVHandle SCEV = SE->getSCEV(PN); |
| 424 | if (SCEV->hasComputableLoopEvolution(L)) |
Chris Lattner | cda9ca5 | 2005-08-10 01:12:06 +0000 | [diff] [blame] | 425 | // FIXME: It is an extremely bad idea to indvar substitute anything more |
| 426 | // complex than affine induction variables. Doing so will put expensive |
| 427 | // polynomial evaluations inside of the loop, and the str reduction pass |
| 428 | // currently can only reduce affine polynomials. For now just disable |
| 429 | // indvar subst on anything more complex than an affine addrec. |
Chris Lattner | 595ee7e | 2004-07-26 02:47:12 +0000 | [diff] [blame] | 430 | if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV)) |
Chris Lattner | cda9ca5 | 2005-08-10 01:12:06 +0000 | [diff] [blame] | 431 | if (AR->isAffine()) |
Chris Lattner | 595ee7e | 2004-07-26 02:47:12 +0000 | [diff] [blame] | 432 | IndVars.push_back(std::make_pair(PN, SCEV)); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 433 | } |
Reid Spencer | 2da5c3d | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 434 | } |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 435 | |
| 436 | // If there are no induction variables in the loop, there is nothing more to |
| 437 | // do. |
Chris Lattner | f50af08 | 2004-04-17 18:08:33 +0000 | [diff] [blame] | 438 | if (IndVars.empty()) { |
| 439 | // Actually, if we know how many times the loop iterates, lets insert a |
| 440 | // canonical induction variable to help subsequent passes. |
| 441 | if (!isa<SCEVCouldNotCompute>(IterationCount)) { |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 442 | SCEVExpander Rewriter(*SE, *LI); |
| 443 | Rewriter.getOrInsertCanonicalInductionVariable(L, |
Chris Lattner | f50af08 | 2004-04-17 18:08:33 +0000 | [diff] [blame] | 444 | IterationCount->getType()); |
| 445 | LinearFunctionTestReplace(L, IterationCount, Rewriter); |
| 446 | } |
| 447 | return; |
| 448 | } |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 449 | |
| 450 | // Compute the type of the largest recurrence expression. |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 451 | // |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 452 | const Type *LargestType = IndVars[0].first->getType(); |
Chris Lattner | fcb81f5 | 2004-04-22 14:59:40 +0000 | [diff] [blame] | 453 | bool DifferingSizes = false; |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 454 | for (unsigned i = 1, e = IndVars.size(); i != e; ++i) { |
| 455 | const Type *Ty = IndVars[i].first->getType(); |
Chris Lattner | fcb81f5 | 2004-04-22 14:59:40 +0000 | [diff] [blame] | 456 | DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize(); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 457 | if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize()) |
| 458 | LargestType = Ty; |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 459 | } |
| 460 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 461 | // Create a rewriter object which we'll use to transform the code with. |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 462 | SCEVExpander Rewriter(*SE, *LI); |
Chris Lattner | 15cad75 | 2003-12-23 07:47:09 +0000 | [diff] [blame] | 463 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 464 | // Now that we know the largest of of the induction variables in this loop, |
| 465 | // insert a canonical induction variable of the largest size. |
Chris Lattner | 006118f | 2004-04-16 06:03:17 +0000 | [diff] [blame] | 466 | LargestType = LargestType->getUnsignedVersion(); |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 467 | Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 468 | ++NumInserted; |
| 469 | Changed = true; |
Chris Lattner | 15cad75 | 2003-12-23 07:47:09 +0000 | [diff] [blame] | 470 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 471 | if (!isa<SCEVCouldNotCompute>(IterationCount)) |
Chris Lattner | 59fdaee | 2004-04-15 15:21:43 +0000 | [diff] [blame] | 472 | LinearFunctionTestReplace(L, IterationCount, Rewriter); |
Chris Lattner | 15cad75 | 2003-12-23 07:47:09 +0000 | [diff] [blame] | 473 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 474 | // Now that we have a canonical induction variable, we can rewrite any |
| 475 | // recurrences in terms of the induction variable. Start with the auxillary |
| 476 | // induction variables, and recursively rewrite any of their uses. |
| 477 | BasicBlock::iterator InsertPt = Header->begin(); |
| 478 | while (isa<PHINode>(InsertPt)) ++InsertPt; |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 479 | |
Chris Lattner | 5d461d2 | 2004-04-21 22:22:01 +0000 | [diff] [blame] | 480 | // If there were induction variables of other sizes, cast the primary |
| 481 | // induction variable to the right size for them, avoiding the need for the |
| 482 | // code evaluation methods to insert induction variables of different sizes. |
Chris Lattner | fcb81f5 | 2004-04-22 14:59:40 +0000 | [diff] [blame] | 483 | if (DifferingSizes) { |
| 484 | bool InsertedSizes[17] = { false }; |
| 485 | InsertedSizes[LargestType->getPrimitiveSize()] = true; |
| 486 | for (unsigned i = 0, e = IndVars.size(); i != e; ++i) |
| 487 | if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) { |
| 488 | PHINode *PN = IndVars[i].first; |
| 489 | InsertedSizes[PN->getType()->getPrimitiveSize()] = true; |
| 490 | Instruction *New = new CastInst(IndVar, |
| 491 | PN->getType()->getUnsignedVersion(), |
| 492 | "indvar", InsertPt); |
| 493 | Rewriter.addInsertedValue(New, SE->getSCEV(New)); |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | // If there were induction variables of other sizes, cast the primary |
| 498 | // induction variable to the right size for them, avoiding the need for the |
| 499 | // code evaluation methods to insert induction variables of different sizes. |
Chris Lattner | 5d461d2 | 2004-04-21 22:22:01 +0000 | [diff] [blame] | 500 | std::map<unsigned, Value*> InsertedSizes; |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 501 | while (!IndVars.empty()) { |
| 502 | PHINode *PN = IndVars.back().first; |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 503 | Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt, |
Chris Lattner | fcb81f5 | 2004-04-22 14:59:40 +0000 | [diff] [blame] | 504 | PN->getType()); |
| 505 | std::string Name = PN->getName(); |
| 506 | PN->setName(""); |
| 507 | NewVal->setName(Name); |
Chris Lattner | 5d461d2 | 2004-04-21 22:22:01 +0000 | [diff] [blame] | 508 | |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 509 | // Replace the old PHI Node with the inserted computation. |
Chris Lattner | fcb81f5 | 2004-04-22 14:59:40 +0000 | [diff] [blame] | 510 | PN->replaceAllUsesWith(NewVal); |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 511 | DeadInsts.insert(PN); |
| 512 | IndVars.pop_back(); |
| 513 | ++NumRemoved; |
Chris Lattner | 4753bf2 | 2001-12-05 19:41:33 +0000 | [diff] [blame] | 514 | Changed = true; |
Chris Lattner | 394437f | 2001-12-04 04:32:29 +0000 | [diff] [blame] | 515 | } |
| 516 | |
Chris Lattner | b4782d1 | 2004-04-22 15:12:36 +0000 | [diff] [blame] | 517 | #if 0 |
Chris Lattner | 1363e85 | 2004-04-21 23:36:08 +0000 | [diff] [blame] | 518 | // Now replace all derived expressions in the loop body with simpler |
| 519 | // expressions. |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 520 | for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) |
| 521 | if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop... |
| 522 | BasicBlock *BB = L->getBlocks()[i]; |
| 523 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) |
| 524 | if (I->getType()->isInteger() && // Is an integer instruction |
Chris Lattner | 1363e85 | 2004-04-21 23:36:08 +0000 | [diff] [blame] | 525 | !I->use_empty() && |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 526 | !Rewriter.isInsertedInstruction(I)) { |
| 527 | SCEVHandle SH = SE->getSCEV(I); |
Chris Lattner | 4a7553e | 2004-04-23 21:29:48 +0000 | [diff] [blame] | 528 | Value *V = Rewriter.expandCodeFor(SH, I, I->getType()); |
Chris Lattner | 1363e85 | 2004-04-21 23:36:08 +0000 | [diff] [blame] | 529 | if (V != I) { |
| 530 | if (isa<Instruction>(V)) { |
| 531 | std::string Name = I->getName(); |
| 532 | I->setName(""); |
| 533 | V->setName(Name); |
| 534 | } |
| 535 | I->replaceAllUsesWith(V); |
| 536 | DeadInsts.insert(I); |
| 537 | ++NumRemoved; |
| 538 | Changed = true; |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 539 | } |
Chris Lattner | 40bf8b4 | 2004-04-02 20:24:31 +0000 | [diff] [blame] | 540 | } |
Chris Lattner | 394437f | 2001-12-04 04:32:29 +0000 | [diff] [blame] | 541 | } |
Chris Lattner | b4782d1 | 2004-04-22 15:12:36 +0000 | [diff] [blame] | 542 | #endif |
Chris Lattner | 1363e85 | 2004-04-21 23:36:08 +0000 | [diff] [blame] | 543 | |
Chris Lattner | 1363e85 | 2004-04-21 23:36:08 +0000 | [diff] [blame] | 544 | DeleteTriviallyDeadInstructions(DeadInsts); |
Chris Lattner | 6148c02 | 2001-12-03 17:28:42 +0000 | [diff] [blame] | 545 | } |