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. The canonical induction variable is guaranteed to be in a wide enough
21 // type so that IV expressions need not be (directly) zero-extended or
23 // 4. Any pointer arithmetic recurrences are raised to use array subscripts.
25 // If the trip count of a loop is computable, this pass also makes the following
27 // 1. The exit condition for the loop is canonicalized to compare the
28 // induction value against the exit value. This turns loops like:
29 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30 // 2. Any use outside of the loop of an expression derived from the indvar
31 // is changed to compute the derived value outside of the loop, eliminating
32 // the dependence on the exit value of the induction variable. If the only
33 // purpose of the loop is to compute the exit value of some derived
34 // expression, this transformation will make the loop dead.
36 // This transformation should be followed by strength reduction after all of the
37 // desired loop transformations have been performed.
39 //===----------------------------------------------------------------------===//
41 #define DEBUG_TYPE "indvars"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/BasicBlock.h"
44 #include "llvm/Constants.h"
45 #include "llvm/Instructions.h"
46 #include "llvm/LLVMContext.h"
47 #include "llvm/Type.h"
48 #include "llvm/Analysis/Dominators.h"
49 #include "llvm/Analysis/IVUsers.h"
50 #include "llvm/Analysis/ScalarEvolutionExpander.h"
51 #include "llvm/Analysis/LoopInfo.h"
52 #include "llvm/Analysis/LoopPass.h"
53 #include "llvm/Support/CFG.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/STLExtras.h"
64 STATISTIC(NumRemoved , "Number of aux indvars removed");
65 STATISTIC(NumInserted, "Number of canonical indvars added");
66 STATISTIC(NumReplaced, "Number of exit values replaced");
67 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
70 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
78 static char ID; // Pass identification, replacement for typeid
79 IndVarSimplify() : LoopPass(&ID) {}
81 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
83 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequired<DominatorTree>();
85 AU.addRequired<ScalarEvolution>();
86 AU.addRequiredID(LoopSimplifyID);
87 AU.addRequired<LoopInfo>();
88 AU.addRequired<IVUsers>();
89 AU.addRequiredID(LCSSAID);
90 AU.addPreserved<ScalarEvolution>();
91 AU.addPreservedID(LoopSimplifyID);
92 AU.addPreserved<IVUsers>();
93 AU.addPreservedID(LCSSAID);
99 void RewriteNonIntegerIVs(Loop *L);
101 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
103 BasicBlock *ExitingBlock,
105 SCEVExpander &Rewriter);
106 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount,
107 SCEVExpander &Rewriter);
109 void RewriteIVExpressions(Loop *L, const Type *LargestType,
110 SCEVExpander &Rewriter);
112 void SinkUnusedInvariants(Loop *L);
114 void HandleFloatingPointIV(Loop *L, PHINode *PH);
118 char IndVarSimplify::ID = 0;
119 static RegisterPass<IndVarSimplify>
120 X("indvars", "Canonicalize Induction Variables");
122 Pass *llvm::createIndVarSimplifyPass() {
123 return new IndVarSimplify();
126 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
127 /// loop to be a canonical != comparison against the incremented loop induction
128 /// variable. This pass is able to rewrite the exit tests of any loop where the
129 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
130 /// is actually a much broader range than just linear tests.
131 ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
132 const SCEV *BackedgeTakenCount,
134 BasicBlock *ExitingBlock,
136 SCEVExpander &Rewriter) {
137 // If the exiting block is not the same as the backedge block, we must compare
138 // against the preincremented value, otherwise we prefer to compare against
139 // the post-incremented value.
141 const SCEV *RHS = BackedgeTakenCount;
142 if (ExitingBlock == L->getLoopLatch()) {
143 // Add one to the "backedge-taken" count to get the trip count.
144 // If this addition may overflow, we have to be more pessimistic and
145 // cast the induction variable before doing the add.
146 const SCEV *Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
148 SE->getAddExpr(BackedgeTakenCount,
149 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
150 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
151 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
152 // No overflow. Cast the sum.
153 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
155 // Potential overflow. Cast before doing the add.
156 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
158 RHS = SE->getAddExpr(RHS,
159 SE->getIntegerSCEV(1, IndVar->getType()));
162 // The BackedgeTaken expression contains the number of times that the
163 // backedge branches to the loop header. This is one less than the
164 // number of times the loop executes, so use the incremented indvar.
165 CmpIndVar = L->getCanonicalInductionVariableIncrement();
167 // We have to use the preincremented value...
168 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
173 // Expand the code for the iteration count.
174 assert(RHS->isLoopInvariant(L) &&
175 "Computed iteration count is not loop invariant!");
176 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
178 // Insert a new icmp_ne or icmp_eq instruction before the branch.
179 ICmpInst::Predicate Opcode;
180 if (L->contains(BI->getSuccessor(0)))
181 Opcode = ICmpInst::ICMP_NE;
183 Opcode = ICmpInst::ICMP_EQ;
185 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
186 << " LHS:" << *CmpIndVar // includes a newline
188 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
189 << " RHS:\t" << *RHS << "\n";
191 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
193 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
194 // It's tempting to use replaceAllUsesWith here to fully replace the old
195 // comparison, but that's not immediately safe, since users of the old
196 // comparison may not be dominated by the new comparison. Instead, just
197 // update the branch to use the new comparison; in the common case this
198 // will make old comparison dead.
199 BI->setCondition(Cond);
200 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
207 /// RewriteLoopExitValues - Check to see if this loop has a computable
208 /// loop-invariant execution count. If so, this means that we can compute the
209 /// final value of any expressions that are recurrent in the loop, and
210 /// substitute the exit values from the loop into any instructions outside of
211 /// the loop that use the final values of the current expressions.
213 /// This is mostly redundant with the regular IndVarSimplify activities that
214 /// happen later, except that it's more powerful in some cases, because it's
215 /// able to brute-force evaluate arbitrary instructions as long as they have
216 /// constant operands at the beginning of the loop.
217 void IndVarSimplify::RewriteLoopExitValues(Loop *L,
218 const SCEV *BackedgeTakenCount,
219 SCEVExpander &Rewriter) {
220 // Verify the input to the pass in already in LCSSA form.
221 assert(L->isLCSSAForm());
223 SmallVector<BasicBlock*, 8> ExitBlocks;
224 L->getUniqueExitBlocks(ExitBlocks);
226 // Find all values that are computed inside the loop, but used outside of it.
227 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
228 // the exit blocks of the loop to find them.
229 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
230 BasicBlock *ExitBB = ExitBlocks[i];
232 // If there are no PHI nodes in this exit block, then no values defined
233 // inside the loop are used on this path, skip it.
234 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
237 unsigned NumPreds = PN->getNumIncomingValues();
239 // Iterate over all of the PHI nodes.
240 BasicBlock::iterator BBI = ExitBB->begin();
241 while ((PN = dyn_cast<PHINode>(BBI++))) {
243 continue; // dead use, don't replace it
244 // Iterate over all of the values in all the PHI nodes.
245 for (unsigned i = 0; i != NumPreds; ++i) {
246 // If the value being merged in is not integer or is not defined
247 // in the loop, skip it.
248 Value *InVal = PN->getIncomingValue(i);
249 if (!isa<Instruction>(InVal) ||
250 // SCEV only supports integer expressions for now.
251 (!isa<IntegerType>(InVal->getType()) &&
252 !isa<PointerType>(InVal->getType())))
255 // If this pred is for a subloop, not L itself, skip it.
256 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
257 continue; // The Block is in a subloop, skip it.
259 // Check that InVal is defined in the loop.
260 Instruction *Inst = cast<Instruction>(InVal);
261 if (!L->contains(Inst->getParent()))
264 // Okay, this instruction has a user outside of the current loop
265 // and varies predictably *inside* the loop. Evaluate the value it
266 // contains when the loop exits, if possible.
267 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
268 if (!ExitValue->isLoopInvariant(L))
274 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
276 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
277 << " LoopVal = " << *Inst << "\n";
279 PN->setIncomingValue(i, ExitVal);
281 // If this instruction is dead now, delete it.
282 RecursivelyDeleteTriviallyDeadInstructions(Inst);
284 // If we're inserting code into the exit block rather than the
285 // preheader, we can (and have to) remove the PHI entirely.
286 // This is safe, because the NewVal won't be variant
287 // in the loop, so we don't need an LCSSA phi node anymore.
288 if (ExitBlocks.size() == 1) {
289 PN->replaceAllUsesWith(ExitVal);
290 RecursivelyDeleteTriviallyDeadInstructions(PN);
294 if (ExitBlocks.size() != 1) {
295 // Clone the PHI and delete the original one. This lets IVUsers and
296 // any other maps purge the original user from their records.
297 PHINode *NewPN = PN->clone();
299 NewPN->insertBefore(PN);
300 PN->replaceAllUsesWith(NewPN);
301 PN->eraseFromParent();
307 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
308 // First step. Check to see if there are any floating-point recurrences.
309 // If there are, change them into integer recurrences, permitting analysis by
310 // the SCEV routines.
312 BasicBlock *Header = L->getHeader();
314 SmallVector<WeakVH, 8> PHIs;
315 for (BasicBlock::iterator I = Header->begin();
316 PHINode *PN = dyn_cast<PHINode>(I); ++I)
319 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
320 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
321 HandleFloatingPointIV(L, PN);
323 // If the loop previously had floating-point IV, ScalarEvolution
324 // may not have been able to compute a trip count. Now that we've done some
325 // re-writing, the trip count may be computable.
327 SE->forgetLoopBackedgeTakenCount(L);
330 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
331 IU = &getAnalysis<IVUsers>();
332 LI = &getAnalysis<LoopInfo>();
333 SE = &getAnalysis<ScalarEvolution>();
334 DT = &getAnalysis<DominatorTree>();
337 // If there are any floating-point recurrences, attempt to
338 // transform them to use integer recurrences.
339 RewriteNonIntegerIVs(L);
341 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
342 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
344 // Create a rewriter object which we'll use to transform the code with.
345 SCEVExpander Rewriter(*SE);
347 // Check to see if this loop has a computable loop-invariant execution count.
348 // If so, this means that we can compute the final value of any expressions
349 // that are recurrent in the loop, and substitute the exit values from the
350 // loop into any instructions outside of the loop that use the final values of
351 // the current expressions.
353 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
354 RewriteLoopExitValues(L, BackedgeTakenCount, Rewriter);
356 // Compute the type of the largest recurrence expression, and decide whether
357 // a canonical induction variable should be inserted.
358 const Type *LargestType = 0;
359 bool NeedCannIV = false;
360 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
361 LargestType = BackedgeTakenCount->getType();
362 LargestType = SE->getEffectiveSCEVType(LargestType);
363 // If we have a known trip count and a single exit block, we'll be
364 // rewriting the loop exit test condition below, which requires a
365 // canonical induction variable.
369 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
370 const SCEV *Stride = IU->StrideOrder[i];
371 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
373 SE->getTypeSizeInBits(Ty) >
374 SE->getTypeSizeInBits(LargestType))
377 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
378 IU->IVUsesByStride.find(IU->StrideOrder[i]);
379 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
381 if (!SI->second->Users.empty())
385 // Now that we know the largest of of the induction variable expressions
386 // in this loop, insert a canonical induction variable of the largest size.
389 // Check to see if the loop already has a canonical-looking induction
390 // variable. If one is present and it's wider than the planned canonical
391 // induction variable, temporarily remove it, so that the Rewriter
392 // doesn't attempt to reuse it.
393 PHINode *OldCannIV = L->getCanonicalInductionVariable();
395 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
396 SE->getTypeSizeInBits(LargestType))
397 OldCannIV->removeFromParent();
402 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
406 DOUT << "INDVARS: New CanIV: " << *IndVar;
408 // Now that the official induction variable is established, reinsert
409 // the old canonical-looking variable after it so that the IR remains
410 // consistent. It will be deleted as part of the dead-PHI deletion at
411 // the end of the pass.
413 OldCannIV->insertAfter(cast<Instruction>(IndVar));
416 // If we have a trip count expression, rewrite the loop's exit condition
417 // using it. We can currently only handle loops with a single exit.
418 ICmpInst *NewICmp = 0;
419 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
421 "LinearFunctionTestReplace requires a canonical induction variable");
422 // Can't rewrite non-branch yet.
423 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
424 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
425 ExitingBlock, BI, Rewriter);
428 // Rewrite IV-derived expressions. Clears the rewriter cache.
429 RewriteIVExpressions(L, LargestType, Rewriter);
431 // The Rewriter may not be used from this point on.
433 // Loop-invariant instructions in the preheader that aren't used in the
434 // loop may be sunk below the loop to reduce register pressure.
435 SinkUnusedInvariants(L);
437 // For completeness, inform IVUsers of the IV use in the newly-created
438 // loop exit test instruction.
440 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
442 // Clean up dead instructions.
443 DeleteDeadPHIs(L->getHeader());
444 // Check a post-condition.
445 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
449 void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
450 SCEVExpander &Rewriter) {
451 SmallVector<WeakVH, 16> DeadInsts;
453 // Rewrite all induction variable expressions in terms of the canonical
454 // induction variable.
456 // If there were induction variables of other sizes or offsets, manually
457 // add the offsets to the primary induction variable and cast, avoiding
458 // the need for the code evaluation methods to insert induction variables
459 // of different sizes.
460 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
461 const SCEV *Stride = IU->StrideOrder[i];
463 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
464 IU->IVUsesByStride.find(IU->StrideOrder[i]);
465 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
466 ilist<IVStrideUse> &List = SI->second->Users;
467 for (ilist<IVStrideUse>::iterator UI = List.begin(),
468 E = List.end(); UI != E; ++UI) {
469 Value *Op = UI->getOperandValToReplace();
470 const Type *UseTy = Op->getType();
471 Instruction *User = UI->getUser();
473 // Compute the final addrec to expand into code.
474 const SCEV *AR = IU->getReplacementExpr(*UI);
476 // FIXME: It is an extremely bad idea to indvar substitute anything more
477 // complex than affine induction variables. Doing so will put expensive
478 // polynomial evaluations inside of the loop, and the str reduction pass
479 // currently can only reduce affine polynomials. For now just disable
480 // indvar subst on anything more complex than an affine addrec, unless
481 // it can be expanded to a trivial value.
482 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
485 // Determine the insertion point for this user. By default, insert
486 // immediately before the user. The SCEVExpander class will automatically
487 // hoist loop invariants out of the loop. For PHI nodes, there may be
488 // multiple uses, so compute the nearest common dominator for the
490 Instruction *InsertPt = User;
491 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
492 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
493 if (PHI->getIncomingValue(i) == Op) {
494 if (InsertPt == User)
495 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
498 DT->findNearestCommonDominator(InsertPt->getParent(),
499 PHI->getIncomingBlock(i))
503 // Now expand it into actual Instructions and patch it into place.
504 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
506 // Patch the new value into place.
508 NewVal->takeName(Op);
509 User->replaceUsesOfWith(Op, NewVal);
510 UI->setOperandValToReplace(NewVal);
511 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
512 << " into = " << *NewVal << "\n";
516 // The old value may be dead now.
517 DeadInsts.push_back(Op);
521 // Clear the rewriter cache, because values that are in the rewriter's cache
522 // can be deleted in the loop below, causing the AssertingVH in the cache to
525 // Now that we're done iterating through lists, clean up any instructions
526 // which are now dead.
527 while (!DeadInsts.empty()) {
528 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
530 RecursivelyDeleteTriviallyDeadInstructions(Inst);
534 /// If there's a single exit block, sink any loop-invariant values that
535 /// were defined in the preheader but not used inside the loop into the
536 /// exit block to reduce register pressure in the loop.
537 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
538 BasicBlock *ExitBlock = L->getExitBlock();
539 if (!ExitBlock) return;
541 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
542 BasicBlock *Preheader = L->getLoopPreheader();
543 BasicBlock::iterator I = Preheader->getTerminator();
544 while (I != Preheader->begin()) {
546 // New instructions were inserted at the end of the preheader.
551 // Determine if there is a use in or before the loop (direct or
553 bool UsedInLoop = false;
554 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
556 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
557 if (PHINode *P = dyn_cast<PHINode>(UI)) {
559 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
560 UseBB = P->getIncomingBlock(i);
562 if (UseBB == Preheader || L->contains(UseBB)) {
567 // If there is, the def must remain in the preheader.
570 // Otherwise, sink it to the exit block.
571 Instruction *ToMove = I;
573 if (I != Preheader->begin())
577 ToMove->moveBefore(InsertPt);
584 /// Return true if it is OK to use SIToFPInst for an inducation variable
585 /// with given inital and exit values.
586 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
587 uint64_t intIV, uint64_t intEV) {
589 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
592 // If the iteration range can be handled by SIToFPInst then use it.
593 APInt Max = APInt::getSignedMaxValue(32);
594 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
600 /// convertToInt - Convert APF to an integer, if possible.
601 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
603 bool isExact = false;
604 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
606 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
607 APFloat::rmTowardZero, &isExact)
616 /// HandleFloatingPointIV - If the loop has floating induction variable
617 /// then insert corresponding integer induction variable if possible.
619 /// for(double i = 0; i < 10000; ++i)
621 /// is converted into
622 /// for(int i = 0; i < 10000; ++i)
625 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
627 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
628 unsigned BackEdge = IncomingEdge^1;
630 // Check incoming value.
631 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
632 if (!InitValue) return;
633 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
634 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
637 // Check IV increment. Reject this PH if increement operation is not
638 // an add or increment value can not be represented by an integer.
639 BinaryOperator *Incr =
640 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
642 if (Incr->getOpcode() != Instruction::FAdd) return;
643 ConstantFP *IncrValue = NULL;
644 unsigned IncrVIndex = 1;
645 if (Incr->getOperand(1) == PH)
647 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
648 if (!IncrValue) return;
649 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
650 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
653 // Check Incr uses. One user is PH and the other users is exit condition used
654 // by the conditional terminator.
655 Value::use_iterator IncrUse = Incr->use_begin();
656 Instruction *U1 = cast<Instruction>(IncrUse++);
657 if (IncrUse == Incr->use_end()) return;
658 Instruction *U2 = cast<Instruction>(IncrUse++);
659 if (IncrUse != Incr->use_end()) return;
661 // Find exit condition.
662 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
664 EC = dyn_cast<FCmpInst>(U2);
667 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
668 if (!BI->isConditional()) return;
669 if (BI->getCondition() != EC) return;
672 // Find exit value. If exit value can not be represented as an interger then
673 // do not handle this floating point PH.
674 ConstantFP *EV = NULL;
675 unsigned EVIndex = 1;
676 if (EC->getOperand(1) == Incr)
678 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
680 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
681 if (!convertToInt(EV->getValueAPF(), &intEV))
684 // Find new predicate for integer comparison.
685 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
686 switch (EC->getPredicate()) {
687 case CmpInst::FCMP_OEQ:
688 case CmpInst::FCMP_UEQ:
689 NewPred = CmpInst::ICMP_EQ;
691 case CmpInst::FCMP_OGT:
692 case CmpInst::FCMP_UGT:
693 NewPred = CmpInst::ICMP_UGT;
695 case CmpInst::FCMP_OGE:
696 case CmpInst::FCMP_UGE:
697 NewPred = CmpInst::ICMP_UGE;
699 case CmpInst::FCMP_OLT:
700 case CmpInst::FCMP_ULT:
701 NewPred = CmpInst::ICMP_ULT;
703 case CmpInst::FCMP_OLE:
704 case CmpInst::FCMP_ULE:
705 NewPred = CmpInst::ICMP_ULE;
710 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
712 // Insert new integer induction variable.
713 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
714 PH->getName()+".int", PH);
715 NewPHI->addIncoming(Context->getConstantInt(Type::Int32Ty, newInitValue),
716 PH->getIncomingBlock(IncomingEdge));
718 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
719 Context->getConstantInt(Type::Int32Ty,
721 Incr->getName()+".int", Incr);
722 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
724 // The back edge is edge 1 of newPHI, whatever it may have been in the
726 ConstantInt *NewEV = Context->getConstantInt(Type::Int32Ty, intEV);
727 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
728 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
729 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
730 EC->getParent()->getTerminator());
732 // In the following deltions, PH may become dead and may be deleted.
733 // Use a WeakVH to observe whether this happens.
736 // Delete old, floating point, exit comparision instruction.
738 EC->replaceAllUsesWith(NewEC);
739 RecursivelyDeleteTriviallyDeadInstructions(EC);
741 // Delete old, floating point, increment instruction.
742 Incr->replaceAllUsesWith(Context->getUndef(Incr->getType()));
743 RecursivelyDeleteTriviallyDeadInstructions(Incr);
745 // Replace floating induction variable, if it isn't already deleted.
746 // Give SIToFPInst preference over UIToFPInst because it is faster on
747 // platforms that are widely used.
748 if (WeakPH && !PH->use_empty()) {
749 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
750 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
751 PH->getParent()->getFirstNonPHI());
752 PH->replaceAllUsesWith(Conv);
754 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
755 PH->getParent()->getFirstNonPHI());
756 PH->replaceAllUsesWith(Conv);
758 RecursivelyDeleteTriviallyDeadInstructions(PH);
761 // Add a new IVUsers entry for the newly-created integer PHI.
762 IU->AddUsersIfInteresting(NewPHI);