1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 // This transformation makes 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.
22 // If the trip count of a loop is computable, this pass also makes the following
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.
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).
38 //===----------------------------------------------------------------------===//
40 #define DEBUG_TYPE "indvars"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/BasicBlock.h"
43 #include "llvm/Constants.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/Type.h"
46 #include "llvm/Analysis/ScalarEvolutionExpander.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/LoopPass.h"
49 #include "llvm/Support/CFG.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Transforms/Utils/Local.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SetVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
61 STATISTIC(NumRemoved , "Number of aux indvars removed");
62 STATISTIC(NumPointer , "Number of pointer indvars promoted");
63 STATISTIC(NumInserted, "Number of canonical indvars added");
64 STATISTIC(NumReplaced, "Number of exit values replaced");
65 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
68 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
74 static char ID; // Pass identification, replacement for typeid
75 IndVarSimplify() : LoopPass(&ID) {}
77 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
79 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
80 AU.addRequired<ScalarEvolution>();
81 AU.addRequiredID(LCSSAID);
82 AU.addRequiredID(LoopSimplifyID);
83 AU.addRequired<LoopInfo>();
84 AU.addPreserved<ScalarEvolution>();
85 AU.addPreservedID(LoopSimplifyID);
86 AU.addPreservedID(LCSSAID);
92 void RewriteNonIntegerIVs(Loop *L);
94 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
95 SmallPtrSet<Instruction*, 16> &DeadInsts);
96 void LinearFunctionTestReplace(Loop *L, SCEVHandle IterationCount,
98 BasicBlock *ExitingBlock,
100 SCEVExpander &Rewriter);
101 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
103 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
105 void HandleFloatingPointIV(Loop *L, PHINode *PH,
106 SmallPtrSet<Instruction*, 16> &DeadInsts);
110 char IndVarSimplify::ID = 0;
111 static RegisterPass<IndVarSimplify>
112 X("indvars", "Canonicalize Induction Variables");
114 Pass *llvm::createIndVarSimplifyPass() {
115 return new IndVarSimplify();
118 /// 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.
121 void IndVarSimplify::
122 DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
123 while (!Insts.empty()) {
124 Instruction *I = *Insts.begin();
126 if (isInstructionTriviallyDead(I)) {
127 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
128 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
130 SE->deleteValueFromRecords(I);
131 DOUT << "INDVARS: Deleting: " << *I;
132 I->eraseFromParent();
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.
142 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
143 BasicBlock *Preheader,
144 SmallPtrSet<Instruction*, 16> &DeadInsts) {
145 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
146 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
147 unsigned BackedgeIdx = PreheaderIdx^1;
148 if (GetElementPtrInst *GEPI =
149 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
150 if (GEPI->getOperand(0) == PN) {
151 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
152 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
154 // 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);
159 // Insert a new integer PHI node into the top of the block.
160 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
161 PN->getName()+".rec", PN);
162 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
164 // Create the new add instruction.
165 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
166 GEPI->getName()+".rec", GEPI);
167 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
169 // Update the existing GEP to use the recurrence.
170 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
172 // Update the GEP to use the new recurrence we just inserted.
173 GEPI->setOperand(1, NewAdd);
175 // 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.
183 gep_type_iterator GTI = gep_type_begin(CE);
184 for (unsigned i = 1, e = CE->getNumOperands()-1;
187 if (isa<SequentialType>(*GTI)) {
188 // Pull the last index out of the constant expr GEP.
189 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
190 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
194 Idx[0] = Constant::getNullValue(Type::Int32Ty);
196 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
198 GEPI->getName(), GEPI);
199 SE->deleteValueFromRecords(GEPI);
200 GEPI->replaceAllUsesWith(NGEPI);
201 GEPI->eraseFromParent();
208 // 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;
215 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
216 NewPhi, "", InsertPos);
217 PreInc->takeName(PN);
218 PN->replaceAllUsesWith(PreInc);
221 // Delete the old PHI for sure, and the GEP if its otherwise unused.
222 DeadInsts.insert(PN);
229 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
230 /// 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.
234 void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
235 SCEVHandle IterationCount,
237 BasicBlock *ExitingBlock,
239 SCEVExpander &Rewriter) {
240 // 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.
244 if (ExitingBlock == L->getLoopLatch()) {
245 // What ScalarEvolution calls the "iteration count" is actually the
246 // number of times the branch is taken. Add one to get the number
247 // of times the branch is executed. If this addition may overflow,
248 // we have to be more pessimistic and cast the induction variable
249 // before doing the add.
250 SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
252 SE->getAddExpr(IterationCount,
253 SE->getIntegerSCEV(1, IterationCount->getType()));
254 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
255 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
256 // No overflow. Cast the sum.
257 IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
259 // Potential overflow. Cast before doing the add.
260 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
263 SE->getAddExpr(IterationCount,
264 SE->getIntegerSCEV(1, IndVar->getType()));
267 // The IterationCount expression contains the number of times that the
268 // backedge actually branches to the loop header. This is one less than the
269 // number of times the loop executes, so add one to it.
270 CmpIndVar = L->getCanonicalInductionVariableIncrement();
272 // We have to use the preincremented value...
273 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
278 // Expand the code for the iteration count into the preheader of the loop.
279 BasicBlock *Preheader = L->getLoopPreheader();
280 Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
281 Preheader->getTerminator());
283 // Insert a new icmp_ne or icmp_eq instruction before the branch.
284 ICmpInst::Predicate Opcode;
285 if (L->contains(BI->getSuccessor(0)))
286 Opcode = ICmpInst::ICMP_NE;
288 Opcode = ICmpInst::ICMP_EQ;
290 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
291 << " LHS:" << *CmpIndVar // includes a newline
293 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
294 << " RHS:\t" << *IterationCount << "\n";
296 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
297 BI->setCondition(Cond);
302 /// RewriteLoopExitValues - Check to see if this loop has a computable
303 /// loop-invariant execution count. If so, this means that we can compute the
304 /// final value of any expressions that are recurrent in the loop, and
305 /// substitute the exit values from the loop into any instructions outside of
306 /// the loop that use the final values of the current expressions.
307 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
308 BasicBlock *Preheader = L->getLoopPreheader();
310 // Scan all of the instructions in the loop, looking at those that have
311 // extra-loop users and which are recurrences.
312 SCEVExpander Rewriter(*SE, *LI);
314 // We insert the code into the preheader of the loop if the loop contains
315 // multiple exit blocks, or in the exit block if there is exactly one.
316 BasicBlock *BlockToInsertInto;
317 SmallVector<BasicBlock*, 8> ExitBlocks;
318 L->getUniqueExitBlocks(ExitBlocks);
319 if (ExitBlocks.size() == 1)
320 BlockToInsertInto = ExitBlocks[0];
322 BlockToInsertInto = Preheader;
323 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
325 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
327 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
328 std::map<Instruction*, Value*> ExitValues;
330 // Find all values that are computed inside the loop, but used outside of it.
331 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
332 // the exit blocks of the loop to find them.
333 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
334 BasicBlock *ExitBB = ExitBlocks[i];
336 // If there are no PHI nodes in this exit block, then no values defined
337 // inside the loop are used on this path, skip it.
338 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
341 unsigned NumPreds = PN->getNumIncomingValues();
343 // Iterate over all of the PHI nodes.
344 BasicBlock::iterator BBI = ExitBB->begin();
345 while ((PN = dyn_cast<PHINode>(BBI++))) {
347 // Iterate over all of the values in all the PHI nodes.
348 for (unsigned i = 0; i != NumPreds; ++i) {
349 // If the value being merged in is not integer or is not defined
350 // in the loop, skip it.
351 Value *InVal = PN->getIncomingValue(i);
352 if (!isa<Instruction>(InVal) ||
353 // SCEV only supports integer expressions for now.
354 !isa<IntegerType>(InVal->getType()))
357 // If this pred is for a subloop, not L itself, skip it.
358 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
359 continue; // The Block is in a subloop, skip it.
361 // Check that InVal is defined in the loop.
362 Instruction *Inst = cast<Instruction>(InVal);
363 if (!L->contains(Inst->getParent()))
366 // We require that this value either have a computable evolution or that
367 // the loop have a constant iteration count. In the case where the loop
368 // has a constant iteration count, we can sometimes force evaluation of
369 // the exit value through brute force.
370 SCEVHandle SH = SE->getSCEV(Inst);
371 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
372 continue; // Cannot get exit evolution for the loop value.
374 // Okay, this instruction has a user outside of the current loop
375 // and varies predictably *inside* the loop. Evaluate the value it
376 // contains when the loop exits, if possible.
377 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
378 if (isa<SCEVCouldNotCompute>(ExitValue) ||
379 !ExitValue->isLoopInvariant(L))
385 // See if we already computed the exit value for the instruction, if so,
387 Value *&ExitVal = ExitValues[Inst];
389 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
391 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
392 << " LoopVal = " << *Inst << "\n";
394 PN->setIncomingValue(i, ExitVal);
396 // If this instruction is dead now, schedule it to be removed.
397 if (Inst->use_empty())
398 InstructionsToDelete.insert(Inst);
400 // See if this is a single-entry LCSSA PHI node. If so, we can (and
402 // the PHI entirely. This is safe, because the NewVal won't be variant
403 // in the loop, so we don't need an LCSSA phi node anymore.
405 SE->deleteValueFromRecords(PN);
406 PN->replaceAllUsesWith(ExitVal);
407 PN->eraseFromParent();
414 DeleteTriviallyDeadInstructions(InstructionsToDelete);
417 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
418 // First step. Check to see if there are any trivial GEP pointer recurrences.
419 // If there are, change them into integer recurrences, permitting analysis by
420 // the SCEV routines.
422 BasicBlock *Header = L->getHeader();
423 BasicBlock *Preheader = L->getLoopPreheader();
425 SmallPtrSet<Instruction*, 16> DeadInsts;
426 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
427 PHINode *PN = cast<PHINode>(I);
428 if (isa<PointerType>(PN->getType()))
429 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
431 HandleFloatingPointIV(L, PN, DeadInsts);
434 // If the loop previously had a pointer or floating-point IV, ScalarEvolution
435 // may not have been able to compute a trip count. Now that we've done some
436 // re-writing, the trip count may be computable.
438 SE->forgetLoopIterationCount(L);
440 if (!DeadInsts.empty())
441 DeleteTriviallyDeadInstructions(DeadInsts);
444 /// getEffectiveIndvarType - Determine the widest type that the
445 /// induction-variable PHINode Phi is cast to.
447 static const Type *getEffectiveIndvarType(const PHINode *Phi) {
448 const Type *Ty = Phi->getType();
450 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
452 const Type *CandidateType = NULL;
453 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
454 CandidateType = ZI->getDestTy();
455 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
456 CandidateType = SI->getDestTy();
458 CandidateType->getPrimitiveSizeInBits() >
459 Ty->getPrimitiveSizeInBits())
466 /// TestOrigIVForWrap - Analyze the original induction variable
467 /// that controls the loop's iteration to determine whether it
468 /// would ever undergo signed or unsigned overflow. Also, check
469 /// whether an induction variable in the same type that starts
470 /// at 0 would undergo signed overflow.
472 /// In addition to setting the NoSignedWrap, and NoUnsignedWrap,
473 /// variables, return the PHI for this induction variable.
475 /// TODO: This duplicates a fair amount of ScalarEvolution logic.
476 /// Perhaps this can be merged with ScalarEvolution::getIterationCount
477 /// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
479 static const PHINode *TestOrigIVForWrap(const Loop *L,
480 const BranchInst *BI,
481 const Instruction *OrigCond,
483 bool &NoUnsignedWrap) {
484 // Verify that the loop is sane and find the exit condition.
485 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
488 const Value *CmpLHS = Cmp->getOperand(0);
489 const Value *CmpRHS = Cmp->getOperand(1);
490 const BasicBlock *TrueBB = BI->getSuccessor(0);
491 const BasicBlock *FalseBB = BI->getSuccessor(1);
492 ICmpInst::Predicate Pred = Cmp->getPredicate();
494 // Canonicalize a constant to the RHS.
495 if (isa<ConstantInt>(CmpLHS)) {
496 Pred = ICmpInst::getSwappedPredicate(Pred);
497 std::swap(CmpLHS, CmpRHS);
499 // Canonicalize SLE to SLT.
500 if (Pred == ICmpInst::ICMP_SLE)
501 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
502 if (!CI->getValue().isMaxSignedValue()) {
503 CmpRHS = ConstantInt::get(CI->getValue() + 1);
504 Pred = ICmpInst::ICMP_SLT;
506 // Canonicalize SGT to SGE.
507 if (Pred == ICmpInst::ICMP_SGT)
508 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
509 if (!CI->getValue().isMaxSignedValue()) {
510 CmpRHS = ConstantInt::get(CI->getValue() + 1);
511 Pred = ICmpInst::ICMP_SGE;
513 // Canonicalize SGE to SLT.
514 if (Pred == ICmpInst::ICMP_SGE) {
515 std::swap(TrueBB, FalseBB);
516 Pred = ICmpInst::ICMP_SLT;
518 // Canonicalize ULE to ULT.
519 if (Pred == ICmpInst::ICMP_ULE)
520 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
521 if (!CI->getValue().isMaxValue()) {
522 CmpRHS = ConstantInt::get(CI->getValue() + 1);
523 Pred = ICmpInst::ICMP_ULT;
525 // Canonicalize UGT to UGE.
526 if (Pred == ICmpInst::ICMP_UGT)
527 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
528 if (!CI->getValue().isMaxValue()) {
529 CmpRHS = ConstantInt::get(CI->getValue() + 1);
530 Pred = ICmpInst::ICMP_UGE;
532 // Canonicalize UGE to ULT.
533 if (Pred == ICmpInst::ICMP_UGE) {
534 std::swap(TrueBB, FalseBB);
535 Pred = ICmpInst::ICMP_ULT;
537 // For now, analyze only LT loops for signed overflow.
538 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
541 bool isSigned = Pred == ICmpInst::ICMP_SLT;
543 // Get the increment instruction. Look past casts if we will
544 // be able to prove that the original induction variable doesn't
545 // undergo signed or unsigned overflow, respectively.
546 const Value *IncrVal = CmpLHS;
548 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
549 if (!isa<ConstantInt>(CmpRHS) ||
550 !cast<ConstantInt>(CmpRHS)->getValue()
551 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
553 IncrVal = SI->getOperand(0);
556 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
557 if (!isa<ConstantInt>(CmpRHS) ||
558 !cast<ConstantInt>(CmpRHS)->getValue()
559 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
561 IncrVal = ZI->getOperand(0);
565 // For now, only analyze induction variables that have simple increments.
566 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
568 IncrOp->getOpcode() != Instruction::Add ||
569 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
570 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
573 // Make sure the PHI looks like a normal IV.
574 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
575 if (!PN || PN->getNumIncomingValues() != 2)
577 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
578 unsigned BackEdge = !IncomingEdge;
579 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
580 PN->getIncomingValue(BackEdge) != IncrOp)
582 if (!L->contains(TrueBB))
585 // For now, only analyze loops with a constant start value, so that
586 // we can easily determine if the start value is not a maximum value
587 // which would wrap on the first iteration.
588 const ConstantInt *InitialVal =
589 dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
593 // The original induction variable will start at some non-max value,
594 // it counts up by one, and the loop iterates only while it remans
595 // less than some value in the same type. As such, it will never wrap.
596 if (isSigned && !InitialVal->getValue().isMaxSignedValue()) {
598 } else if (!isSigned && !InitialVal->getValue().isMaxValue())
599 NoUnsignedWrap = true;
603 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
604 LI = &getAnalysis<LoopInfo>();
605 SE = &getAnalysis<ScalarEvolution>();
608 // If there are any floating-point or pointer recurrences, attempt to
609 // transform them to use integer recurrences.
610 RewriteNonIntegerIVs(L);
612 BasicBlock *Header = L->getHeader();
613 BasicBlock *ExitingBlock = L->getExitingBlock();
614 SmallPtrSet<Instruction*, 16> DeadInsts;
616 // Verify the input to the pass in already in LCSSA form.
617 assert(L->isLCSSAForm());
619 // Check to see if this loop has a computable loop-invariant execution count.
620 // If so, this means that we can compute the final value of any expressions
621 // that are recurrent in the loop, and substitute the exit values from the
622 // loop into any instructions outside of the loop that use the final values of
623 // the current expressions.
625 SCEVHandle IterationCount = SE->getIterationCount(L);
626 if (!isa<SCEVCouldNotCompute>(IterationCount))
627 RewriteLoopExitValues(L, IterationCount);
629 // Next, analyze all of the induction variables in the loop, canonicalizing
630 // auxillary induction variables.
631 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
633 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
634 PHINode *PN = cast<PHINode>(I);
635 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
636 SCEVHandle SCEV = SE->getSCEV(PN);
637 // FIXME: It is an extremely bad idea to indvar substitute anything more
638 // complex than affine induction variables. Doing so will put expensive
639 // polynomial evaluations inside of the loop, and the str reduction pass
640 // currently can only reduce affine polynomials. For now just disable
641 // indvar subst on anything more complex than an affine addrec.
642 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
643 if (AR->getLoop() == L && AR->isAffine())
644 IndVars.push_back(std::make_pair(PN, SCEV));
648 // Compute the type of the largest recurrence expression, and collect
649 // the set of the types of the other recurrence expressions.
650 const Type *LargestType = 0;
651 SmallSetVector<const Type *, 4> SizesToInsert;
652 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
653 LargestType = IterationCount->getType();
654 SizesToInsert.insert(IterationCount->getType());
656 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
657 const PHINode *PN = IndVars[i].first;
658 SizesToInsert.insert(PN->getType());
659 const Type *EffTy = getEffectiveIndvarType(PN);
660 SizesToInsert.insert(EffTy);
662 EffTy->getPrimitiveSizeInBits() >
663 LargestType->getPrimitiveSizeInBits())
667 // Create a rewriter object which we'll use to transform the code with.
668 SCEVExpander Rewriter(*SE, *LI);
670 // Now that we know the largest of of the induction variables in this loop,
671 // insert a canonical induction variable of the largest size.
673 if (!SizesToInsert.empty()) {
674 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
677 DOUT << "INDVARS: New CanIV: " << *IndVar;
680 // If we have a trip count expression, rewrite the loop's exit condition
681 // using it. We can currently only handle loops with a single exit.
682 bool NoSignedWrap = false;
683 bool NoUnsignedWrap = false;
684 const PHINode *OrigControllingPHI = 0;
685 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
686 // Can't rewrite non-branch yet.
687 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
688 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
689 // Determine if the OrigIV will ever undergo overflow.
691 TestOrigIVForWrap(L, BI, OrigCond,
692 NoSignedWrap, NoUnsignedWrap);
694 // We'll be replacing the original condition, so it'll be dead.
695 DeadInsts.insert(OrigCond);
698 LinearFunctionTestReplace(L, IterationCount, IndVar,
699 ExitingBlock, BI, Rewriter);
702 // Now that we have a canonical induction variable, we can rewrite any
703 // recurrences in terms of the induction variable. Start with the auxillary
704 // induction variables, and recursively rewrite any of their uses.
705 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
707 // If there were induction variables of other sizes, cast the primary
708 // induction variable to the right size for them, avoiding the need for the
709 // code evaluation methods to insert induction variables of different sizes.
710 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
711 const Type *Ty = SizesToInsert[i];
712 if (Ty != LargestType) {
713 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
714 Rewriter.addInsertedValue(New, SE->getSCEV(New));
715 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
720 // Rewrite all induction variables in terms of the canonical induction
722 while (!IndVars.empty()) {
723 PHINode *PN = IndVars.back().first;
724 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
725 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
726 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
727 << " into = " << *NewVal << "\n";
728 NewVal->takeName(PN);
730 /// If the new canonical induction variable is wider than the original,
731 /// and the original has uses that are casts to wider types, see if the
732 /// truncate and extend can be omitted.
733 if (PN == OrigControllingPHI && PN->getType() != LargestType)
734 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
736 if (isa<SExtInst>(UI) && NoSignedWrap) {
737 SCEVHandle ExtendedStart =
738 SE->getSignExtendExpr(AR->getStart(), LargestType);
739 SCEVHandle ExtendedStep =
740 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
741 SCEVHandle ExtendedAddRec =
742 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
743 if (LargestType != UI->getType())
744 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
745 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
746 UI->replaceAllUsesWith(TruncIndVar);
747 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
748 DeadInsts.insert(DeadUse);
750 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
751 SCEVHandle ExtendedStart =
752 SE->getZeroExtendExpr(AR->getStart(), LargestType);
753 SCEVHandle ExtendedStep =
754 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
755 SCEVHandle ExtendedAddRec =
756 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
757 if (LargestType != UI->getType())
758 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
759 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
760 UI->replaceAllUsesWith(TruncIndVar);
761 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
762 DeadInsts.insert(DeadUse);
766 // Replace the old PHI Node with the inserted computation.
767 PN->replaceAllUsesWith(NewVal);
768 DeadInsts.insert(PN);
774 DeleteTriviallyDeadInstructions(DeadInsts);
775 assert(L->isLCSSAForm());
779 /// Return true if it is OK to use SIToFPInst for an inducation variable
780 /// with given inital and exit values.
781 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
782 uint64_t intIV, uint64_t intEV) {
784 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
787 // If the iteration range can be handled by SIToFPInst then use it.
788 APInt Max = APInt::getSignedMaxValue(32);
789 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
795 /// convertToInt - Convert APF to an integer, if possible.
796 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
798 bool isExact = false;
799 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
801 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
802 APFloat::rmTowardZero, &isExact)
811 /// HandleFloatingPointIV - If the loop has floating induction variable
812 /// then insert corresponding integer induction variable if possible.
814 /// for(double i = 0; i < 10000; ++i)
816 /// is converted into
817 /// for(int i = 0; i < 10000; ++i)
820 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
821 SmallPtrSet<Instruction*, 16> &DeadInsts) {
823 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
824 unsigned BackEdge = IncomingEdge^1;
826 // Check incoming value.
827 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
828 if (!InitValue) return;
829 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
830 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
833 // Check IV increment. Reject this PH if increement operation is not
834 // an add or increment value can not be represented by an integer.
835 BinaryOperator *Incr =
836 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
838 if (Incr->getOpcode() != Instruction::Add) return;
839 ConstantFP *IncrValue = NULL;
840 unsigned IncrVIndex = 1;
841 if (Incr->getOperand(1) == PH)
843 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
844 if (!IncrValue) return;
845 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
846 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
849 // Check Incr uses. One user is PH and the other users is exit condition used
850 // by the conditional terminator.
851 Value::use_iterator IncrUse = Incr->use_begin();
852 Instruction *U1 = cast<Instruction>(IncrUse++);
853 if (IncrUse == Incr->use_end()) return;
854 Instruction *U2 = cast<Instruction>(IncrUse++);
855 if (IncrUse != Incr->use_end()) return;
857 // Find exit condition.
858 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
860 EC = dyn_cast<FCmpInst>(U2);
863 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
864 if (!BI->isConditional()) return;
865 if (BI->getCondition() != EC) return;
868 // Find exit value. If exit value can not be represented as an interger then
869 // do not handle this floating point PH.
870 ConstantFP *EV = NULL;
871 unsigned EVIndex = 1;
872 if (EC->getOperand(1) == Incr)
874 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
876 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
877 if (!convertToInt(EV->getValueAPF(), &intEV))
880 // Find new predicate for integer comparison.
881 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
882 switch (EC->getPredicate()) {
883 case CmpInst::FCMP_OEQ:
884 case CmpInst::FCMP_UEQ:
885 NewPred = CmpInst::ICMP_EQ;
887 case CmpInst::FCMP_OGT:
888 case CmpInst::FCMP_UGT:
889 NewPred = CmpInst::ICMP_UGT;
891 case CmpInst::FCMP_OGE:
892 case CmpInst::FCMP_UGE:
893 NewPred = CmpInst::ICMP_UGE;
895 case CmpInst::FCMP_OLT:
896 case CmpInst::FCMP_ULT:
897 NewPred = CmpInst::ICMP_ULT;
899 case CmpInst::FCMP_OLE:
900 case CmpInst::FCMP_ULE:
901 NewPred = CmpInst::ICMP_ULE;
906 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
908 // Insert new integer induction variable.
909 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
910 PH->getName()+".int", PH);
911 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
912 PH->getIncomingBlock(IncomingEdge));
914 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
915 ConstantInt::get(Type::Int32Ty,
917 Incr->getName()+".int", Incr);
918 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
920 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
921 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
922 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
923 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
924 EC->getParent()->getTerminator());
926 // Delete old, floating point, exit comparision instruction.
927 EC->replaceAllUsesWith(NewEC);
928 DeadInsts.insert(EC);
930 // Delete old, floating point, increment instruction.
931 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
932 DeadInsts.insert(Incr);
934 // Replace floating induction variable. Give SIToFPInst preference over
935 // UIToFPInst because it is faster on platforms that are widely used.
936 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
937 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
938 PH->getParent()->getFirstNonPHI());
939 PH->replaceAllUsesWith(Conv);
941 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
942 PH->getParent()->getFirstNonPHI());
943 PH->replaceAllUsesWith(Conv);
945 DeadInsts.insert(PH);