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/IntrinsicInst.h"
47 #include "llvm/LLVMContext.h"
48 #include "llvm/Type.h"
49 #include "llvm/Analysis/Dominators.h"
50 #include "llvm/Analysis/IVUsers.h"
51 #include "llvm/Analysis/ScalarEvolutionExpander.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopPass.h"
54 #include "llvm/Support/CFG.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Utils/Local.h"
59 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/Statistic.h"
62 #include "llvm/ADT/STLExtras.h"
65 STATISTIC(NumRemoved , "Number of aux indvars removed");
66 STATISTIC(NumInserted, "Number of canonical indvars added");
67 STATISTIC(NumReplaced, "Number of exit values replaced");
68 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
71 class IndVarSimplify : public LoopPass {
79 static char ID; // Pass identification, replacement for typeid
80 IndVarSimplify() : LoopPass(&ID) {}
82 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<DominatorTree>();
86 AU.addRequired<LoopInfo>();
87 AU.addRequired<ScalarEvolution>();
88 AU.addRequiredID(LoopSimplifyID);
89 AU.addRequiredID(LCSSAID);
90 AU.addRequired<IVUsers>();
91 AU.addPreserved<ScalarEvolution>();
92 AU.addPreservedID(LoopSimplifyID);
93 AU.addPreservedID(LCSSAID);
94 AU.addPreserved<IVUsers>();
100 void RewriteNonIntegerIVs(Loop *L);
102 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
104 BasicBlock *ExitingBlock,
106 SCEVExpander &Rewriter);
107 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
109 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
111 void SinkUnusedInvariants(Loop *L);
113 void HandleFloatingPointIV(Loop *L, PHINode *PH);
117 char IndVarSimplify::ID = 0;
118 static RegisterPass<IndVarSimplify>
119 X("indvars", "Canonicalize Induction Variables");
121 Pass *llvm::createIndVarSimplifyPass() {
122 return new IndVarSimplify();
125 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
126 /// loop to be a canonical != comparison against the incremented loop induction
127 /// variable. This pass is able to rewrite the exit tests of any loop where the
128 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
129 /// is actually a much broader range than just linear tests.
130 ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
131 const SCEV *BackedgeTakenCount,
133 BasicBlock *ExitingBlock,
135 SCEVExpander &Rewriter) {
136 // If the exiting block is not the same as the backedge block, we must compare
137 // against the preincremented value, otherwise we prefer to compare against
138 // the post-incremented value.
140 const SCEV *RHS = BackedgeTakenCount;
141 if (ExitingBlock == L->getLoopLatch()) {
142 // Add one to the "backedge-taken" count to get the trip count.
143 // If this addition may overflow, we have to be more pessimistic and
144 // cast the induction variable before doing the add.
145 const SCEV *Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
147 SE->getAddExpr(BackedgeTakenCount,
148 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
149 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
150 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
151 // No overflow. Cast the sum.
152 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
154 // Potential overflow. Cast before doing the add.
155 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
157 RHS = SE->getAddExpr(RHS,
158 SE->getIntegerSCEV(1, IndVar->getType()));
161 // The BackedgeTaken expression contains the number of times that the
162 // backedge branches to the loop header. This is one less than the
163 // number of times the loop executes, so use the incremented indvar.
164 CmpIndVar = L->getCanonicalInductionVariableIncrement();
166 // We have to use the preincremented value...
167 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
172 // Expand the code for the iteration count.
173 assert(RHS->isLoopInvariant(L) &&
174 "Computed iteration count is not loop invariant!");
175 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
177 // Insert a new icmp_ne or icmp_eq instruction before the branch.
178 ICmpInst::Predicate Opcode;
179 if (L->contains(BI->getSuccessor(0)))
180 Opcode = ICmpInst::ICMP_NE;
182 Opcode = ICmpInst::ICMP_EQ;
184 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
185 << " LHS:" << *CmpIndVar << '\n'
187 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
188 << " RHS:\t" << *RHS << "\n");
190 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
192 Value *OrigCond = BI->getCondition();
193 // It's tempting to use replaceAllUsesWith here to fully replace the old
194 // comparison, but that's not immediately safe, since users of the old
195 // comparison may not be dominated by the new comparison. Instead, just
196 // update the branch to use the new comparison; in the common case this
197 // will make old comparison dead.
198 BI->setCondition(Cond);
199 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
206 /// RewriteLoopExitValues - Check to see if this loop has a computable
207 /// loop-invariant execution count. If so, this means that we can compute the
208 /// final value of any expressions that are recurrent in the loop, and
209 /// substitute the exit values from the loop into any instructions outside of
210 /// the loop that use the final values of the current expressions.
212 /// This is mostly redundant with the regular IndVarSimplify activities that
213 /// happen later, except that it's more powerful in some cases, because it's
214 /// able to brute-force evaluate arbitrary instructions as long as they have
215 /// constant operands at the beginning of the loop.
216 void IndVarSimplify::RewriteLoopExitValues(Loop *L,
217 SCEVExpander &Rewriter) {
218 // Verify the input to the pass in already in LCSSA form.
219 assert(L->isLCSSAForm(*DT));
221 SmallVector<BasicBlock*, 8> ExitBlocks;
222 L->getUniqueExitBlocks(ExitBlocks);
224 // Find all values that are computed inside the loop, but used outside of it.
225 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
226 // the exit blocks of the loop to find them.
227 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
228 BasicBlock *ExitBB = ExitBlocks[i];
230 // If there are no PHI nodes in this exit block, then no values defined
231 // inside the loop are used on this path, skip it.
232 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
235 unsigned NumPreds = PN->getNumIncomingValues();
237 // Iterate over all of the PHI nodes.
238 BasicBlock::iterator BBI = ExitBB->begin();
239 while ((PN = dyn_cast<PHINode>(BBI++))) {
241 continue; // dead use, don't replace it
243 // SCEV only supports integer expressions for now.
244 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
247 // It's necessary to tell ScalarEvolution about this explicitly so that
248 // it can walk the def-use list and forget all SCEVs, as it may not be
249 // watching the PHI itself. Once the new exit value is in place, there
250 // may not be a def-use connection between the loop and every instruction
251 // which got a SCEVAddRecExpr for that loop.
254 // Iterate over all of the values in all the PHI nodes.
255 for (unsigned i = 0; i != NumPreds; ++i) {
256 // If the value being merged in is not integer or is not defined
257 // in the loop, skip it.
258 Value *InVal = PN->getIncomingValue(i);
259 if (!isa<Instruction>(InVal))
262 // If this pred is for a subloop, not L itself, skip it.
263 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
264 continue; // The Block is in a subloop, skip it.
266 // Check that InVal is defined in the loop.
267 Instruction *Inst = cast<Instruction>(InVal);
268 if (!L->contains(Inst))
271 // Okay, this instruction has a user outside of the current loop
272 // and varies predictably *inside* the loop. Evaluate the value it
273 // contains when the loop exits, if possible.
274 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
275 if (!ExitValue->isLoopInvariant(L))
281 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
283 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
284 << " LoopVal = " << *Inst << "\n");
286 PN->setIncomingValue(i, ExitVal);
288 // If this instruction is dead now, delete it.
289 RecursivelyDeleteTriviallyDeadInstructions(Inst);
292 // Completely replace a single-pred PHI. This is safe, because the
293 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
295 PN->replaceAllUsesWith(ExitVal);
296 RecursivelyDeleteTriviallyDeadInstructions(PN);
300 // Clone the PHI and delete the original one. This lets IVUsers and
301 // any other maps purge the original user from their records.
302 PHINode *NewPN = cast<PHINode>(PN->clone());
304 NewPN->insertBefore(PN);
305 PN->replaceAllUsesWith(NewPN);
306 PN->eraseFromParent();
312 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
313 // First step. Check to see if there are any floating-point recurrences.
314 // If there are, change them into integer recurrences, permitting analysis by
315 // the SCEV routines.
317 BasicBlock *Header = L->getHeader();
319 SmallVector<WeakVH, 8> PHIs;
320 for (BasicBlock::iterator I = Header->begin();
321 PHINode *PN = dyn_cast<PHINode>(I); ++I)
324 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
325 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
326 HandleFloatingPointIV(L, PN);
328 // If the loop previously had floating-point IV, ScalarEvolution
329 // may not have been able to compute a trip count. Now that we've done some
330 // re-writing, the trip count may be computable.
335 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
336 IU = &getAnalysis<IVUsers>();
337 LI = &getAnalysis<LoopInfo>();
338 SE = &getAnalysis<ScalarEvolution>();
339 DT = &getAnalysis<DominatorTree>();
342 // If there are any floating-point recurrences, attempt to
343 // transform them to use integer recurrences.
344 RewriteNonIntegerIVs(L);
346 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
347 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
349 // Create a rewriter object which we'll use to transform the code with.
350 SCEVExpander Rewriter(*SE);
352 // Check to see if this loop has a computable loop-invariant execution count.
353 // If so, this means that we can compute the final value of any expressions
354 // that are recurrent in the loop, and substitute the exit values from the
355 // loop into any instructions outside of the loop that use the final values of
356 // the current expressions.
358 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
359 RewriteLoopExitValues(L, Rewriter);
361 // Compute the type of the largest recurrence expression, and decide whether
362 // a canonical induction variable should be inserted.
363 const Type *LargestType = 0;
364 bool NeedCannIV = false;
365 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
366 LargestType = BackedgeTakenCount->getType();
367 LargestType = SE->getEffectiveSCEVType(LargestType);
368 // If we have a known trip count and a single exit block, we'll be
369 // rewriting the loop exit test condition below, which requires a
370 // canonical induction variable.
374 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
376 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
378 SE->getTypeSizeInBits(Ty) >
379 SE->getTypeSizeInBits(LargestType))
384 // Now that we know the largest of the induction variable expressions
385 // in this loop, insert a canonical induction variable of the largest size.
388 // Check to see if the loop already has any canonical-looking induction
389 // variables. If any are present and wider than the planned canonical
390 // induction variable, temporarily remove them, so that the Rewriter
391 // doesn't attempt to reuse them.
392 SmallVector<PHINode *, 2> OldCannIVs;
393 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
394 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
395 SE->getTypeSizeInBits(LargestType))
396 OldCannIV->removeFromParent();
399 OldCannIVs.push_back(OldCannIV);
402 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
406 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
408 // Now that the official induction variable is established, reinsert
409 // any old canonical-looking variables after it so that the IR remains
410 // consistent. They will be deleted as part of the dead-PHI deletion at
411 // the end of the pass.
412 while (!OldCannIVs.empty()) {
413 PHINode *OldCannIV = OldCannIVs.pop_back_val();
414 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
418 // If we have a trip count expression, rewrite the loop's exit condition
419 // using it. We can currently only handle loops with a single exit.
420 ICmpInst *NewICmp = 0;
421 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
422 !BackedgeTakenCount->isZero() &&
425 "LinearFunctionTestReplace requires a canonical induction variable");
426 // Can't rewrite non-branch yet.
427 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
428 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
429 ExitingBlock, BI, Rewriter);
432 // Rewrite IV-derived expressions. Clears the rewriter cache.
433 RewriteIVExpressions(L, Rewriter);
435 // The Rewriter may not be used from this point on.
437 // Loop-invariant instructions in the preheader that aren't used in the
438 // loop may be sunk below the loop to reduce register pressure.
439 SinkUnusedInvariants(L);
441 // For completeness, inform IVUsers of the IV use in the newly-created
442 // loop exit test instruction.
444 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
446 // Clean up dead instructions.
447 Changed |= DeleteDeadPHIs(L->getHeader());
448 // Check a post-condition.
449 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
453 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
454 SmallVector<WeakVH, 16> DeadInsts;
456 // Rewrite all induction variable expressions in terms of the canonical
457 // induction variable.
459 // If there were induction variables of other sizes or offsets, manually
460 // add the offsets to the primary induction variable and cast, avoiding
461 // the need for the code evaluation methods to insert induction variables
462 // of different sizes.
463 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
464 const SCEV *Stride = UI->getStride();
465 Value *Op = UI->getOperandValToReplace();
466 const Type *UseTy = Op->getType();
467 Instruction *User = UI->getUser();
469 // Compute the final addrec to expand into code.
470 const SCEV *AR = IU->getReplacementExpr(*UI);
472 // Evaluate the expression out of the loop, if possible.
473 if (!L->contains(UI->getUser())) {
474 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
475 if (ExitVal->isLoopInvariant(L))
479 // FIXME: It is an extremely bad idea to indvar substitute anything more
480 // complex than affine induction variables. Doing so will put expensive
481 // polynomial evaluations inside of the loop, and the str reduction pass
482 // currently can only reduce affine polynomials. For now just disable
483 // indvar subst on anything more complex than an affine addrec, unless
484 // it can be expanded to a trivial value.
485 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
488 // Determine the insertion point for this user. By default, insert
489 // immediately before the user. The SCEVExpander class will automatically
490 // hoist loop invariants out of the loop. For PHI nodes, there may be
491 // multiple uses, so compute the nearest common dominator for the
493 Instruction *InsertPt = User;
494 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
495 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
496 if (PHI->getIncomingValue(i) == Op) {
497 if (InsertPt == User)
498 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
501 DT->findNearestCommonDominator(InsertPt->getParent(),
502 PHI->getIncomingBlock(i))
506 // Now expand it into actual Instructions and patch it into place.
507 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
509 // Patch the new value into place.
511 NewVal->takeName(Op);
512 User->replaceUsesOfWith(Op, NewVal);
513 UI->setOperandValToReplace(NewVal);
514 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
515 << " into = " << *NewVal << "\n");
519 // The old value may be dead now.
520 DeadInsts.push_back(Op);
523 // Clear the rewriter cache, because values that are in the rewriter's cache
524 // can be deleted in the loop below, causing the AssertingVH in the cache to
527 // Now that we're done iterating through lists, clean up any instructions
528 // which are now dead.
529 while (!DeadInsts.empty())
530 if (Instruction *Inst =
531 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
532 RecursivelyDeleteTriviallyDeadInstructions(Inst);
535 /// If there's a single exit block, sink any loop-invariant values that
536 /// were defined in the preheader but not used inside the loop into the
537 /// exit block to reduce register pressure in the loop.
538 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
539 BasicBlock *ExitBlock = L->getExitBlock();
540 if (!ExitBlock) return;
542 BasicBlock *Preheader = L->getLoopPreheader();
543 if (!Preheader) return;
545 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
546 BasicBlock::iterator I = Preheader->getTerminator();
547 while (I != Preheader->begin()) {
549 // New instructions were inserted at the end of the preheader.
552 // Don't move instructions which might have side effects, since the side
553 // effects need to complete before instructions inside the loop. Also
554 // don't move instructions which might read memory, since the loop may
555 // modify memory. Note that it's okay if the instruction might have
556 // undefined behavior: LoopSimplify guarantees that the preheader
557 // dominates the exit block.
558 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
560 // Skip debug info intrinsics.
561 if (isa<DbgInfoIntrinsic>(I))
563 // Don't sink static AllocaInsts out of the entry block, which would
564 // turn them into dynamic allocas!
565 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
566 if (AI->isStaticAlloca())
568 // Determine if there is a use in or before the loop (direct or
570 bool UsedInLoop = false;
571 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
573 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
574 if (PHINode *P = dyn_cast<PHINode>(UI)) {
576 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
577 UseBB = P->getIncomingBlock(i);
579 if (UseBB == Preheader || L->contains(UseBB)) {
584 // If there is, the def must remain in the preheader.
587 // Otherwise, sink it to the exit block.
588 Instruction *ToMove = I;
590 if (I != Preheader->begin())
594 ToMove->moveBefore(InsertPt);
601 /// Return true if it is OK to use SIToFPInst for an induction variable
602 /// with given initial and exit values.
603 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
604 uint64_t intIV, uint64_t intEV) {
606 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
609 // If the iteration range can be handled by SIToFPInst then use it.
610 APInt Max = APInt::getSignedMaxValue(32);
611 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
617 /// convertToInt - Convert APF to an integer, if possible.
618 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
620 bool isExact = false;
621 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
623 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
624 APFloat::rmTowardZero, &isExact)
633 /// HandleFloatingPointIV - If the loop has floating induction variable
634 /// then insert corresponding integer induction variable if possible.
636 /// for(double i = 0; i < 10000; ++i)
638 /// is converted into
639 /// for(int i = 0; i < 10000; ++i)
642 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
644 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
645 unsigned BackEdge = IncomingEdge^1;
647 // Check incoming value.
648 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
649 if (!InitValue) return;
650 uint64_t newInitValue =
651 Type::getInt32Ty(PH->getContext())->getPrimitiveSizeInBits();
652 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
655 // Check IV increment. Reject this PH if increment operation is not
656 // an add or increment value can not be represented by an integer.
657 BinaryOperator *Incr =
658 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
660 if (Incr->getOpcode() != Instruction::FAdd) return;
661 ConstantFP *IncrValue = NULL;
662 unsigned IncrVIndex = 1;
663 if (Incr->getOperand(1) == PH)
665 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
666 if (!IncrValue) return;
667 uint64_t newIncrValue =
668 Type::getInt32Ty(PH->getContext())->getPrimitiveSizeInBits();
669 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
672 // Check Incr uses. One user is PH and the other users is exit condition used
673 // by the conditional terminator.
674 Value::use_iterator IncrUse = Incr->use_begin();
675 Instruction *U1 = cast<Instruction>(IncrUse++);
676 if (IncrUse == Incr->use_end()) return;
677 Instruction *U2 = cast<Instruction>(IncrUse++);
678 if (IncrUse != Incr->use_end()) return;
680 // Find exit condition.
681 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
683 EC = dyn_cast<FCmpInst>(U2);
686 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
687 if (!BI->isConditional()) return;
688 if (BI->getCondition() != EC) return;
691 // Find exit value. If exit value can not be represented as an integer then
692 // do not handle this floating point PH.
693 ConstantFP *EV = NULL;
694 unsigned EVIndex = 1;
695 if (EC->getOperand(1) == Incr)
697 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
699 uint64_t intEV = Type::getInt32Ty(PH->getContext())->getPrimitiveSizeInBits();
700 if (!convertToInt(EV->getValueAPF(), &intEV))
703 // Find new predicate for integer comparison.
704 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
705 switch (EC->getPredicate()) {
706 case CmpInst::FCMP_OEQ:
707 case CmpInst::FCMP_UEQ:
708 NewPred = CmpInst::ICMP_EQ;
710 case CmpInst::FCMP_OGT:
711 case CmpInst::FCMP_UGT:
712 NewPred = CmpInst::ICMP_UGT;
714 case CmpInst::FCMP_OGE:
715 case CmpInst::FCMP_UGE:
716 NewPred = CmpInst::ICMP_UGE;
718 case CmpInst::FCMP_OLT:
719 case CmpInst::FCMP_ULT:
720 NewPred = CmpInst::ICMP_ULT;
722 case CmpInst::FCMP_OLE:
723 case CmpInst::FCMP_ULE:
724 NewPred = CmpInst::ICMP_ULE;
729 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
731 // Insert new integer induction variable.
732 PHINode *NewPHI = PHINode::Create(Type::getInt32Ty(PH->getContext()),
733 PH->getName()+".int", PH);
734 NewPHI->addIncoming(ConstantInt::get(Type::getInt32Ty(PH->getContext()),
736 PH->getIncomingBlock(IncomingEdge));
738 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
739 ConstantInt::get(Type::getInt32Ty(PH->getContext()),
741 Incr->getName()+".int", Incr);
742 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
744 // The back edge is edge 1 of newPHI, whatever it may have been in the
746 ConstantInt *NewEV = ConstantInt::get(Type::getInt32Ty(PH->getContext()),
748 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
749 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
750 ICmpInst *NewEC = new ICmpInst(EC->getParent()->getTerminator(),
751 NewPred, LHS, RHS, EC->getName());
753 // In the following deletions, PH may become dead and may be deleted.
754 // Use a WeakVH to observe whether this happens.
757 // Delete old, floating point, exit comparison instruction.
759 EC->replaceAllUsesWith(NewEC);
760 RecursivelyDeleteTriviallyDeadInstructions(EC);
762 // Delete old, floating point, increment instruction.
763 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
764 RecursivelyDeleteTriviallyDeadInstructions(Incr);
766 // Replace floating induction variable, if it isn't already deleted.
767 // Give SIToFPInst preference over UIToFPInst because it is faster on
768 // platforms that are widely used.
769 if (WeakPH && !PH->use_empty()) {
770 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
771 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
772 PH->getParent()->getFirstNonPHI());
773 PH->replaceAllUsesWith(Conv);
775 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
776 PH->getParent()->getFirstNonPHI());
777 PH->replaceAllUsesWith(Conv);
779 RecursivelyDeleteTriviallyDeadInstructions(PH);
782 // Add a new IVUsers entry for the newly-created integer PHI.
783 IU->AddUsersIfInteresting(NewPHI);