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.
36 //===----------------------------------------------------------------------===//
38 #define DEBUG_TYPE "indvars"
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/BasicBlock.h"
41 #include "llvm/Constants.h"
42 #include "llvm/Instructions.h"
43 #include "llvm/Type.h"
44 #include "llvm/Analysis/Dominators.h"
45 #include "llvm/Analysis/IVUsers.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/Transforms/Utils/Local.h"
53 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
60 STATISTIC(NumRemoved , "Number of aux indvars removed");
61 STATISTIC(NumInserted, "Number of canonical indvars added");
62 STATISTIC(NumReplaced, "Number of exit values replaced");
63 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
66 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
73 static char ID; // Pass identification, replacement for typeid
74 IndVarSimplify() : LoopPass(&ID) {}
76 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
78 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
79 AU.addRequired<DominatorTree>();
80 AU.addRequired<ScalarEvolution>();
81 AU.addRequiredID(LCSSAID);
82 AU.addRequiredID(LoopSimplifyID);
83 AU.addRequired<LoopInfo>();
84 AU.addRequired<IVUsers>();
85 AU.addPreserved<ScalarEvolution>();
86 AU.addPreservedID(LoopSimplifyID);
87 AU.addPreserved<IVUsers>();
88 AU.addPreservedID(LCSSAID);
94 void RewriteNonIntegerIVs(Loop *L);
96 ICmpInst *LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
98 BasicBlock *ExitingBlock,
100 SCEVExpander &Rewriter);
101 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount);
103 void RewriteIVExpressions(Loop *L, const Type *LargestType,
104 SCEVExpander &Rewriter);
106 void SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter);
108 void FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter);
110 void HandleFloatingPointIV(Loop *L, PHINode *PH);
114 char IndVarSimplify::ID = 0;
115 static RegisterPass<IndVarSimplify>
116 X("indvars", "Canonicalize Induction Variables");
118 Pass *llvm::createIndVarSimplifyPass() {
119 return new IndVarSimplify();
122 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
123 /// loop to be a canonical != comparison against the incremented loop induction
124 /// variable. This pass is able to rewrite the exit tests of any loop where the
125 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
126 /// is actually a much broader range than just linear tests.
127 ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
128 SCEVHandle BackedgeTakenCount,
130 BasicBlock *ExitingBlock,
132 SCEVExpander &Rewriter) {
133 // If the exiting block is not the same as the backedge block, we must compare
134 // against the preincremented value, otherwise we prefer to compare against
135 // the post-incremented value.
137 SCEVHandle RHS = BackedgeTakenCount;
138 if (ExitingBlock == L->getLoopLatch()) {
139 // Add one to the "backedge-taken" count to get the trip count.
140 // If this addition may overflow, we have to be more pessimistic and
141 // cast the induction variable before doing the add.
142 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
144 SE->getAddExpr(BackedgeTakenCount,
145 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
146 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
147 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
148 // No overflow. Cast the sum.
149 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
151 // Potential overflow. Cast before doing the add.
152 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
154 RHS = SE->getAddExpr(RHS,
155 SE->getIntegerSCEV(1, IndVar->getType()));
158 // The BackedgeTaken expression contains the number of times that the
159 // backedge branches to the loop header. This is one less than the
160 // number of times the loop executes, so use the incremented indvar.
161 CmpIndVar = L->getCanonicalInductionVariableIncrement();
163 // We have to use the preincremented value...
164 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
169 // Expand the code for the iteration count into the preheader of the loop.
170 BasicBlock *Preheader = L->getLoopPreheader();
171 Value *ExitCnt = Rewriter.expandCodeFor(RHS, CmpIndVar->getType(),
172 Preheader->getTerminator());
174 // Insert a new icmp_ne or icmp_eq instruction before the branch.
175 ICmpInst::Predicate Opcode;
176 if (L->contains(BI->getSuccessor(0)))
177 Opcode = ICmpInst::ICMP_NE;
179 Opcode = ICmpInst::ICMP_EQ;
181 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
182 << " LHS:" << *CmpIndVar // includes a newline
184 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
185 << " RHS:\t" << *RHS << "\n";
187 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
189 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
190 // It's tempting to use replaceAllUsesWith here to fully replace the old
191 // comparison, but that's not immediately safe, since users of the old
192 // comparison may not be dominated by the new comparison. Instead, just
193 // update the branch to use the new comparison; in the common case this
194 // will make old comparison dead.
195 BI->setCondition(Cond);
196 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
203 /// RewriteLoopExitValues - Check to see if this loop has a computable
204 /// loop-invariant execution count. If so, this means that we can compute the
205 /// final value of any expressions that are recurrent in the loop, and
206 /// substitute the exit values from the loop into any instructions outside of
207 /// the loop that use the final values of the current expressions.
209 /// This is mostly redundant with the regular IndVarSimplify activities that
210 /// happen later, except that it's more powerful in some cases, because it's
211 /// able to brute-force evaluate arbitrary instructions as long as they have
212 /// constant operands at the beginning of the loop.
213 void IndVarSimplify::RewriteLoopExitValues(Loop *L,
214 const SCEV *BackedgeTakenCount) {
215 // Verify the input to the pass in already in LCSSA form.
216 assert(L->isLCSSAForm());
218 BasicBlock *Preheader = L->getLoopPreheader();
220 // Scan all of the instructions in the loop, looking at those that have
221 // extra-loop users and which are recurrences.
222 SCEVExpander Rewriter(*SE);
224 // We insert the code into the preheader of the loop if the loop contains
225 // multiple exit blocks, or in the exit block if there is exactly one.
226 BasicBlock *BlockToInsertInto;
227 SmallVector<BasicBlock*, 8> ExitBlocks;
228 L->getUniqueExitBlocks(ExitBlocks);
229 if (ExitBlocks.size() == 1)
230 BlockToInsertInto = ExitBlocks[0];
232 BlockToInsertInto = Preheader;
233 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
235 std::map<Instruction*, Value*> ExitValues;
237 // Find all values that are computed inside the loop, but used outside of it.
238 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
239 // the exit blocks of the loop to find them.
240 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
241 BasicBlock *ExitBB = ExitBlocks[i];
243 // If there are no PHI nodes in this exit block, then no values defined
244 // inside the loop are used on this path, skip it.
245 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
248 unsigned NumPreds = PN->getNumIncomingValues();
250 // Iterate over all of the PHI nodes.
251 BasicBlock::iterator BBI = ExitBB->begin();
252 while ((PN = dyn_cast<PHINode>(BBI++))) {
254 continue; // dead use, don't replace it
255 // Iterate over all of the values in all the PHI nodes.
256 for (unsigned i = 0; i != NumPreds; ++i) {
257 // If the value being merged in is not integer or is not defined
258 // in the loop, skip it.
259 Value *InVal = PN->getIncomingValue(i);
260 if (!isa<Instruction>(InVal) ||
261 // SCEV only supports integer expressions for now.
262 (!isa<IntegerType>(InVal->getType()) &&
263 !isa<PointerType>(InVal->getType())))
266 // If this pred is for a subloop, not L itself, skip it.
267 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
268 continue; // The Block is in a subloop, skip it.
270 // Check that InVal is defined in the loop.
271 Instruction *Inst = cast<Instruction>(InVal);
272 if (!L->contains(Inst->getParent()))
275 // Okay, this instruction has a user outside of the current loop
276 // and varies predictably *inside* the loop. Evaluate the value it
277 // contains when the loop exits, if possible.
278 SCEVHandle SH = SE->getSCEV(Inst);
279 SCEVHandle ExitValue = SE->getSCEVAtScope(SH, L->getParentLoop());
280 if (isa<SCEVCouldNotCompute>(ExitValue) ||
281 !ExitValue->isLoopInvariant(L))
287 // See if we already computed the exit value for the instruction, if so,
289 Value *&ExitVal = ExitValues[Inst];
291 ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
293 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
294 << " LoopVal = " << *Inst << "\n";
296 PN->setIncomingValue(i, ExitVal);
298 // If this instruction is dead now, delete it.
299 RecursivelyDeleteTriviallyDeadInstructions(Inst);
301 // See if this is a single-entry LCSSA PHI node. If so, we can (and
303 // the PHI entirely. This is safe, because the NewVal won't be variant
304 // in the loop, so we don't need an LCSSA phi node anymore.
306 PN->replaceAllUsesWith(ExitVal);
307 RecursivelyDeleteTriviallyDeadInstructions(PN);
315 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
316 // First step. Check to see if there are any floating-point recurrences.
317 // If there are, change them into integer recurrences, permitting analysis by
318 // the SCEV routines.
320 BasicBlock *Header = L->getHeader();
322 SmallVector<WeakVH, 8> PHIs;
323 for (BasicBlock::iterator I = Header->begin();
324 PHINode *PN = dyn_cast<PHINode>(I); ++I)
327 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
328 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
329 HandleFloatingPointIV(L, PN);
331 // If the loop previously had floating-point IV, ScalarEvolution
332 // may not have been able to compute a trip count. Now that we've done some
333 // re-writing, the trip count may be computable.
335 SE->forgetLoopBackedgeTakenCount(L);
338 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
339 IU = &getAnalysis<IVUsers>();
340 LI = &getAnalysis<LoopInfo>();
341 SE = &getAnalysis<ScalarEvolution>();
344 // If there are any floating-point recurrences, attempt to
345 // transform them to use integer recurrences.
346 RewriteNonIntegerIVs(L);
348 BasicBlock *Header = L->getHeader();
349 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
350 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
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, BackedgeTakenCount);
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 (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
375 SCEVHandle Stride = IU->StrideOrder[i];
376 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
378 SE->getTypeSizeInBits(Ty) >
379 SE->getTypeSizeInBits(LargestType))
382 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
383 IU->IVUsesByStride.find(IU->StrideOrder[i]);
384 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
386 if (!SI->second->Users.empty())
390 // Create a rewriter object which we'll use to transform the code with.
391 SCEVExpander Rewriter(*SE);
393 // Now that we know the largest of of the induction variable expressions
394 // in this loop, insert a canonical induction variable of the largest size.
397 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
400 DOUT << "INDVARS: New CanIV: " << *IndVar;
403 // If we have a trip count expression, rewrite the loop's exit condition
404 // using it. We can currently only handle loops with a single exit.
405 ICmpInst *NewICmp = 0;
406 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
408 "LinearFunctionTestReplace requires a canonical induction variable");
409 // Can't rewrite non-branch yet.
410 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
411 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
412 ExitingBlock, BI, Rewriter);
415 Rewriter.setInsertionPoint(Header->getFirstNonPHI());
417 // Rewrite IV-derived expressions.
418 RewriteIVExpressions(L, LargestType, Rewriter);
420 // Loop-invariant instructions in the preheader that aren't used in the
421 // loop may be sunk below the loop to reduce register pressure.
422 SinkUnusedInvariants(L, Rewriter);
424 // Reorder instructions to avoid use-before-def conditions.
425 FixUsesBeforeDefs(L, Rewriter);
428 // For completeness, inform IVUsers of the IV use in the newly-created
429 // loop exit test instruction.
431 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
433 // Clean up dead instructions.
434 DeleteDeadPHIs(L->getHeader());
435 // Check a post-condition.
436 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
440 void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
441 SCEVExpander &Rewriter) {
442 SmallVector<WeakVH, 16> DeadInsts;
444 // Rewrite all induction variable expressions in terms of the canonical
445 // induction variable.
447 // If there were induction variables of other sizes or offsets, manually
448 // add the offsets to the primary induction variable and cast, avoiding
449 // the need for the code evaluation methods to insert induction variables
450 // of different sizes.
451 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
452 SCEVHandle Stride = IU->StrideOrder[i];
454 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
455 IU->IVUsesByStride.find(IU->StrideOrder[i]);
456 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
457 ilist<IVStrideUse> &List = SI->second->Users;
458 for (ilist<IVStrideUse>::iterator UI = List.begin(),
459 E = List.end(); UI != E; ++UI) {
460 SCEVHandle Offset = UI->getOffset();
461 Value *Op = UI->getOperandValToReplace();
462 Instruction *User = UI->getUser();
463 bool isSigned = UI->isSigned();
465 // Compute the final addrec to expand into code.
466 SCEVHandle AR = IU->getReplacementExpr(*UI);
468 // FIXME: It is an extremely bad idea to indvar substitute anything more
469 // complex than affine induction variables. Doing so will put expensive
470 // polynomial evaluations inside of the loop, and the str reduction pass
471 // currently can only reduce affine polynomials. For now just disable
472 // indvar subst on anything more complex than an affine addrec, unless
473 // it can be expanded to a trivial value.
474 if (!Stride->isLoopInvariant(L) &&
475 !isa<SCEVConstant>(AR) &&
476 L->contains(User->getParent()))
480 if (AR->isLoopInvariant(L)) {
481 BasicBlock::iterator I = Rewriter.getInsertionPoint();
482 // Expand loop-invariant values in the loop preheader. They will
483 // be sunk to the exit block later, if possible.
485 Rewriter.expandCodeFor(AR, LargestType,
486 L->getLoopPreheader()->getTerminator());
487 Rewriter.setInsertionPoint(I);
490 const Type *IVTy = Offset->getType();
491 const Type *UseTy = Op->getType();
493 // Promote the Offset and Stride up to the canonical induction
494 // variable's bit width.
495 SCEVHandle PromotedOffset = Offset;
496 SCEVHandle PromotedStride = Stride;
497 if (SE->getTypeSizeInBits(IVTy) != SE->getTypeSizeInBits(LargestType)) {
498 // It doesn't matter for correctness whether zero or sign extension
499 // is used here, since the value is truncated away below, but if the
500 // value is signed, sign extension is more likely to be folded.
502 PromotedOffset = SE->getSignExtendExpr(PromotedOffset, LargestType);
503 PromotedStride = SE->getSignExtendExpr(PromotedStride, LargestType);
505 PromotedOffset = SE->getZeroExtendExpr(PromotedOffset, LargestType);
506 // If the stride is obviously negative, use sign extension to
507 // produce things like x-1 instead of x+255.
508 if (isa<SCEVConstant>(PromotedStride) &&
509 cast<SCEVConstant>(PromotedStride)
510 ->getValue()->getValue().isNegative())
511 PromotedStride = SE->getSignExtendExpr(PromotedStride,
514 PromotedStride = SE->getZeroExtendExpr(PromotedStride,
519 // Create the SCEV representing the offset from the canonical
520 // induction variable, still in the canonical induction variable's
521 // type, so that all expanded arithmetic is done in the same type.
522 SCEVHandle NewAR = SE->getAddRecExpr(SE->getIntegerSCEV(0, LargestType),
524 // Add the PromotedOffset as a separate step, because it may not be
526 NewAR = SE->getAddExpr(NewAR, PromotedOffset);
528 // Expand the addrec into instructions.
529 Value *V = Rewriter.expandCodeFor(NewAR);
531 // Insert an explicit cast if necessary to truncate the value
532 // down to the original stride type. This is done outside of
533 // SCEVExpander because in SCEV expressions, a truncate of an
534 // addrec is always folded.
535 if (LargestType != IVTy) {
536 if (SE->getTypeSizeInBits(IVTy) != SE->getTypeSizeInBits(LargestType))
537 NewAR = SE->getTruncateExpr(NewAR, IVTy);
538 if (Rewriter.isInsertedExpression(NewAR))
539 V = Rewriter.expandCodeFor(NewAR);
541 V = Rewriter.InsertCastOfTo(CastInst::getCastOpcode(V, false,
544 assert(!isa<SExtInst>(V) && !isa<ZExtInst>(V) &&
545 "LargestType wasn't actually the largest type!");
546 // Force the rewriter to use this trunc whenever this addrec
547 // appears so that it doesn't insert new phi nodes or
548 // arithmetic in a different type.
549 Rewriter.addInsertedValue(V, NewAR);
553 DOUT << "INDVARS: Made offset-and-trunc IV for offset "
554 << *IVTy << " " << *Offset << ": ";
555 DEBUG(WriteAsOperand(*DOUT, V, false));
558 // Now expand it into actual Instructions and patch it into place.
559 NewVal = Rewriter.expandCodeFor(AR, UseTy);
562 // Patch the new value into place.
564 NewVal->takeName(Op);
565 User->replaceUsesOfWith(Op, NewVal);
566 UI->setOperandValToReplace(NewVal);
567 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
568 << " into = " << *NewVal << "\n";
572 // The old value may be dead now.
573 DeadInsts.push_back(Op);
577 // Now that we're done iterating through lists, clean up any instructions
578 // which are now dead.
579 while (!DeadInsts.empty()) {
580 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
582 RecursivelyDeleteTriviallyDeadInstructions(Inst);
586 /// If there's a single exit block, sink any loop-invariant values that
587 /// were defined in the preheader but not used inside the loop into the
588 /// exit block to reduce register pressure in the loop.
589 void IndVarSimplify::SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter) {
590 BasicBlock *ExitBlock = L->getExitBlock();
591 if (!ExitBlock) return;
593 Instruction *NonPHI = ExitBlock->getFirstNonPHI();
594 BasicBlock *Preheader = L->getLoopPreheader();
595 BasicBlock::iterator I = Preheader->getTerminator();
596 while (I != Preheader->begin()) {
598 // New instructions were inserted at the end of the preheader. Only
599 // consider those new instructions.
600 if (!Rewriter.isInsertedInstruction(I))
602 // Determine if there is a use in or before the loop (direct or
604 bool UsedInLoop = false;
605 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
607 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
608 if (PHINode *P = dyn_cast<PHINode>(UI)) {
610 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
611 UseBB = P->getIncomingBlock(i);
613 if (UseBB == Preheader || L->contains(UseBB)) {
618 // If there is, the def must remain in the preheader.
621 // Otherwise, sink it to the exit block.
622 Instruction *ToMove = I;
624 if (I != Preheader->begin())
628 ToMove->moveBefore(NonPHI);
634 /// Re-schedule the inserted instructions to put defs before uses. This
635 /// fixes problems that arrise when SCEV expressions contain loop-variant
636 /// values unrelated to the induction variable which are defined inside the
637 /// loop. FIXME: It would be better to insert instructions in the right
638 /// place so that this step isn't needed.
639 void IndVarSimplify::FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter) {
640 // Visit all the blocks in the loop in pre-order dom-tree dfs order.
641 DominatorTree *DT = &getAnalysis<DominatorTree>();
642 std::map<Instruction *, unsigned> NumPredsLeft;
643 SmallVector<DomTreeNode *, 16> Worklist;
644 Worklist.push_back(DT->getNode(L->getHeader()));
646 DomTreeNode *Node = Worklist.pop_back_val();
647 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I)
648 if (L->contains((*I)->getBlock()))
649 Worklist.push_back(*I);
650 BasicBlock *BB = Node->getBlock();
651 // Visit all the instructions in the block top down.
652 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
653 // Count the number of operands that aren't properly dominating.
654 unsigned NumPreds = 0;
655 if (Rewriter.isInsertedInstruction(I) && !isa<PHINode>(I))
656 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
658 if (Instruction *Inst = dyn_cast<Instruction>(OI))
659 if (L->contains(Inst->getParent()) && !NumPredsLeft.count(Inst))
661 NumPredsLeft[I] = NumPreds;
662 // Notify uses of the position of this instruction, and move the
663 // users (and their dependents, recursively) into place after this
664 // instruction if it is their last outstanding operand.
665 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
667 Instruction *Inst = cast<Instruction>(UI);
668 std::map<Instruction *, unsigned>::iterator Z = NumPredsLeft.find(Inst);
669 if (Z != NumPredsLeft.end() && Z->second != 0 && --Z->second == 0) {
670 SmallVector<Instruction *, 4> UseWorkList;
671 UseWorkList.push_back(Inst);
672 BasicBlock::iterator InsertPt = I;
673 if (InvokeInst *II = dyn_cast<InvokeInst>(InsertPt))
674 InsertPt = II->getNormalDest()->begin();
677 while (isa<PHINode>(InsertPt)) ++InsertPt;
679 Instruction *Use = UseWorkList.pop_back_val();
680 Use->moveBefore(InsertPt);
681 NumPredsLeft.erase(Use);
682 for (Value::use_iterator IUI = Use->use_begin(),
683 IUE = Use->use_end(); IUI != IUE; ++IUI) {
684 Instruction *IUIInst = cast<Instruction>(IUI);
685 if (L->contains(IUIInst->getParent()) &&
686 Rewriter.isInsertedInstruction(IUIInst) &&
687 !isa<PHINode>(IUIInst))
688 UseWorkList.push_back(IUIInst);
690 } while (!UseWorkList.empty());
694 } while (!Worklist.empty());
697 /// Return true if it is OK to use SIToFPInst for an inducation variable
698 /// with given inital and exit values.
699 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
700 uint64_t intIV, uint64_t intEV) {
702 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
705 // If the iteration range can be handled by SIToFPInst then use it.
706 APInt Max = APInt::getSignedMaxValue(32);
707 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
713 /// convertToInt - Convert APF to an integer, if possible.
714 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
716 bool isExact = false;
717 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
719 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
720 APFloat::rmTowardZero, &isExact)
729 /// HandleFloatingPointIV - If the loop has floating induction variable
730 /// then insert corresponding integer induction variable if possible.
732 /// for(double i = 0; i < 10000; ++i)
734 /// is converted into
735 /// for(int i = 0; i < 10000; ++i)
738 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
740 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
741 unsigned BackEdge = IncomingEdge^1;
743 // Check incoming value.
744 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
745 if (!InitValue) return;
746 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
747 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
750 // Check IV increment. Reject this PH if increement operation is not
751 // an add or increment value can not be represented by an integer.
752 BinaryOperator *Incr =
753 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
755 if (Incr->getOpcode() != Instruction::Add) return;
756 ConstantFP *IncrValue = NULL;
757 unsigned IncrVIndex = 1;
758 if (Incr->getOperand(1) == PH)
760 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
761 if (!IncrValue) return;
762 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
763 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
766 // Check Incr uses. One user is PH and the other users is exit condition used
767 // by the conditional terminator.
768 Value::use_iterator IncrUse = Incr->use_begin();
769 Instruction *U1 = cast<Instruction>(IncrUse++);
770 if (IncrUse == Incr->use_end()) return;
771 Instruction *U2 = cast<Instruction>(IncrUse++);
772 if (IncrUse != Incr->use_end()) return;
774 // Find exit condition.
775 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
777 EC = dyn_cast<FCmpInst>(U2);
780 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
781 if (!BI->isConditional()) return;
782 if (BI->getCondition() != EC) return;
785 // Find exit value. If exit value can not be represented as an interger then
786 // do not handle this floating point PH.
787 ConstantFP *EV = NULL;
788 unsigned EVIndex = 1;
789 if (EC->getOperand(1) == Incr)
791 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
793 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
794 if (!convertToInt(EV->getValueAPF(), &intEV))
797 // Find new predicate for integer comparison.
798 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
799 switch (EC->getPredicate()) {
800 case CmpInst::FCMP_OEQ:
801 case CmpInst::FCMP_UEQ:
802 NewPred = CmpInst::ICMP_EQ;
804 case CmpInst::FCMP_OGT:
805 case CmpInst::FCMP_UGT:
806 NewPred = CmpInst::ICMP_UGT;
808 case CmpInst::FCMP_OGE:
809 case CmpInst::FCMP_UGE:
810 NewPred = CmpInst::ICMP_UGE;
812 case CmpInst::FCMP_OLT:
813 case CmpInst::FCMP_ULT:
814 NewPred = CmpInst::ICMP_ULT;
816 case CmpInst::FCMP_OLE:
817 case CmpInst::FCMP_ULE:
818 NewPred = CmpInst::ICMP_ULE;
823 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
825 // Insert new integer induction variable.
826 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
827 PH->getName()+".int", PH);
828 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
829 PH->getIncomingBlock(IncomingEdge));
831 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
832 ConstantInt::get(Type::Int32Ty,
834 Incr->getName()+".int", Incr);
835 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
837 // The back edge is edge 1 of newPHI, whatever it may have been in the
839 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
840 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
841 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
842 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
843 EC->getParent()->getTerminator());
845 // In the following deltions, PH may become dead and may be deleted.
846 // Use a WeakVH to observe whether this happens.
849 // Delete old, floating point, exit comparision instruction.
851 EC->replaceAllUsesWith(NewEC);
852 RecursivelyDeleteTriviallyDeadInstructions(EC);
854 // Delete old, floating point, increment instruction.
855 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
856 RecursivelyDeleteTriviallyDeadInstructions(Incr);
858 // Replace floating induction variable, if it isn't already deleted.
859 // Give SIToFPInst preference over UIToFPInst because it is faster on
860 // platforms that are widely used.
861 if (WeakPH && !PH->use_empty()) {
862 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
863 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
864 PH->getParent()->getFirstNonPHI());
865 PH->replaceAllUsesWith(Conv);
867 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
868 PH->getParent()->getFirstNonPHI());
869 PH->replaceAllUsesWith(Conv);
871 RecursivelyDeleteTriviallyDeadInstructions(PH);
874 // Add a new IVUsers entry for the newly-created integer PHI.
875 IU->AddUsersIfInteresting(NewPHI);