1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
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 forms suitable for efficient execution
14 // This pass performs a strength reduction on array references inside loops that
15 // have as one or more of their components the loop induction variable, it
16 // rewrites expressions to take advantage of scaled-index addressing modes
17 // available on the target, and it performs a variety of other optimizations
18 // related to loop induction variables.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "loop-reduce"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Type.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/IVUsers.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/LoopPass.h"
33 #include "llvm/Analysis/ScalarEvolutionExpander.h"
34 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetLowering.h"
47 STATISTIC(NumReduced , "Number of IV uses strength reduced");
48 STATISTIC(NumInserted, "Number of PHIs inserted");
49 STATISTIC(NumVariable, "Number of PHIs with variable strides");
50 STATISTIC(NumEliminated, "Number of strides eliminated");
51 STATISTIC(NumShadow, "Number of Shadow IVs optimized");
52 STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
53 STATISTIC(NumLoopCond, "Number of loop terminating conds optimized");
55 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
63 /// IVInfo - This structure keeps track of one IV expression inserted during
64 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
65 /// well as the PHI node and increment value created for rewrite.
71 IVExpr(const SCEV *const stride, const SCEV *const base, PHINode *phi)
72 : Stride(stride), Base(base), PHI(phi) {}
75 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
76 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
77 struct IVsOfOneStride {
78 std::vector<IVExpr> IVs;
80 void addIV(const SCEV *const Stride, const SCEV *const Base, PHINode *PHI) {
81 IVs.push_back(IVExpr(Stride, Base, PHI));
85 class LoopStrengthReduce : public LoopPass {
92 /// IVsByStride - Keep track of all IVs that have been inserted for a
93 /// particular stride.
94 std::map<const SCEV *, IVsOfOneStride> IVsByStride;
96 /// StrideNoReuse - Keep track of all the strides whose ivs cannot be
97 /// reused (nor should they be rewritten to reuse other strides).
98 SmallSet<const SCEV *, 4> StrideNoReuse;
100 /// DeadInsts - Keep track of instructions we may have made dead, so that
101 /// we can remove them after we are done working.
102 SmallVector<WeakVH, 16> DeadInsts;
104 /// TLI - Keep a pointer of a TargetLowering to consult for determining
105 /// transformation profitability.
106 const TargetLowering *TLI;
109 static char ID; // Pass ID, replacement for typeid
110 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
111 LoopPass(&ID), TLI(tli) {
114 bool runOnLoop(Loop *L, LPPassManager &LPM);
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 // We split critical edges, so we change the CFG. However, we do update
118 // many analyses if they are around.
119 AU.addPreservedID(LoopSimplifyID);
120 AU.addPreserved<LoopInfo>();
121 AU.addPreserved<DominanceFrontier>();
122 AU.addPreserved<DominatorTree>();
124 AU.addRequiredID(LoopSimplifyID);
125 AU.addRequired<LoopInfo>();
126 AU.addRequired<DominatorTree>();
127 AU.addRequired<ScalarEvolution>();
128 AU.addPreserved<ScalarEvolution>();
129 AU.addRequired<IVUsers>();
130 AU.addPreserved<IVUsers>();
134 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
135 IVStrideUse* &CondUse,
136 const SCEV *const * &CondStride);
138 void OptimizeIndvars(Loop *L);
139 void OptimizeLoopCountIV(Loop *L);
140 void OptimizeLoopTermCond(Loop *L);
142 /// OptimizeShadowIV - If IV is used in a int-to-float cast
143 /// inside the loop then try to eliminate the cast opeation.
144 void OptimizeShadowIV(Loop *L);
146 /// OptimizeMax - Rewrite the loop's terminating condition
147 /// if it uses a max computation.
148 ICmpInst *OptimizeMax(Loop *L, ICmpInst *Cond,
149 IVStrideUse* &CondUse);
151 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
152 const SCEV *const * &CondStride);
153 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
154 const SCEV *CheckForIVReuse(bool, bool, bool, const SCEV *const&,
155 IVExpr&, const Type*,
156 const std::vector<BasedUser>& UsersToProcess);
157 bool ValidScale(bool, int64_t,
158 const std::vector<BasedUser>& UsersToProcess);
159 bool ValidOffset(bool, int64_t, int64_t,
160 const std::vector<BasedUser>& UsersToProcess);
161 const SCEV *CollectIVUsers(const SCEV *const &Stride,
162 IVUsersOfOneStride &Uses,
164 bool &AllUsesAreAddresses,
165 bool &AllUsesAreOutsideLoop,
166 std::vector<BasedUser> &UsersToProcess);
167 bool ShouldUseFullStrengthReductionMode(
168 const std::vector<BasedUser> &UsersToProcess,
170 bool AllUsesAreAddresses,
172 void PrepareToStrengthReduceFully(
173 std::vector<BasedUser> &UsersToProcess,
175 const SCEV *CommonExprs,
177 SCEVExpander &PreheaderRewriter);
178 void PrepareToStrengthReduceFromSmallerStride(
179 std::vector<BasedUser> &UsersToProcess,
181 const IVExpr &ReuseIV,
182 Instruction *PreInsertPt);
183 void PrepareToStrengthReduceWithNewPhi(
184 std::vector<BasedUser> &UsersToProcess,
186 const SCEV *CommonExprs,
188 Instruction *IVIncInsertPt,
190 SCEVExpander &PreheaderRewriter);
191 void StrengthReduceStridedIVUsers(const SCEV *const &Stride,
192 IVUsersOfOneStride &Uses,
194 void DeleteTriviallyDeadInstructions();
198 char LoopStrengthReduce::ID = 0;
199 static RegisterPass<LoopStrengthReduce>
200 X("loop-reduce", "Loop Strength Reduction");
202 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
203 return new LoopStrengthReduce(TLI);
206 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
207 /// specified set are trivially dead, delete them and see if this makes any of
208 /// their operands subsequently dead.
209 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
210 if (DeadInsts.empty()) return;
212 while (!DeadInsts.empty()) {
213 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.back());
214 DeadInsts.pop_back();
216 if (I == 0 || !isInstructionTriviallyDead(I))
219 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
220 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
223 DeadInsts.push_back(U);
227 I->eraseFromParent();
232 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
233 /// subexpression that is an AddRec from a loop other than L. An outer loop
234 /// of L is OK, but not an inner loop nor a disjoint loop.
235 static bool containsAddRecFromDifferentLoop(const SCEV *S, Loop *L) {
236 // This is very common, put it first.
237 if (isa<SCEVConstant>(S))
239 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
240 for (unsigned int i=0; i< AE->getNumOperands(); i++)
241 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
245 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
246 if (const Loop *newLoop = AE->getLoop()) {
249 // if newLoop is an outer loop of L, this is OK.
250 if (!LoopInfo::isNotAlreadyContainedIn(L, newLoop))
255 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
256 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
257 containsAddRecFromDifferentLoop(DE->getRHS(), L);
259 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
260 // need this when it is.
261 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
262 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
263 containsAddRecFromDifferentLoop(DE->getRHS(), L);
265 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
266 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
270 /// isAddressUse - Returns true if the specified instruction is using the
271 /// specified value as an address.
272 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
273 bool isAddress = isa<LoadInst>(Inst);
274 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
275 if (SI->getOperand(1) == OperandVal)
277 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
278 // Addressing modes can also be folded into prefetches and a variety
280 switch (II->getIntrinsicID()) {
282 case Intrinsic::prefetch:
283 case Intrinsic::x86_sse2_loadu_dq:
284 case Intrinsic::x86_sse2_loadu_pd:
285 case Intrinsic::x86_sse_loadu_ps:
286 case Intrinsic::x86_sse_storeu_ps:
287 case Intrinsic::x86_sse2_storeu_pd:
288 case Intrinsic::x86_sse2_storeu_dq:
289 case Intrinsic::x86_sse2_storel_dq:
290 if (II->getOperand(1) == OperandVal)
298 /// getAccessType - Return the type of the memory being accessed.
299 static const Type *getAccessType(const Instruction *Inst) {
300 const Type *AccessTy = Inst->getType();
301 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
302 AccessTy = SI->getOperand(0)->getType();
303 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
304 // Addressing modes can also be folded into prefetches and a variety
306 switch (II->getIntrinsicID()) {
308 case Intrinsic::x86_sse_storeu_ps:
309 case Intrinsic::x86_sse2_storeu_pd:
310 case Intrinsic::x86_sse2_storeu_dq:
311 case Intrinsic::x86_sse2_storel_dq:
312 AccessTy = II->getOperand(1)->getType();
320 /// BasedUser - For a particular base value, keep information about how we've
321 /// partitioned the expression so far.
323 /// SE - The current ScalarEvolution object.
326 /// Base - The Base value for the PHI node that needs to be inserted for
327 /// this use. As the use is processed, information gets moved from this
328 /// field to the Imm field (below). BasedUser values are sorted by this
332 /// Inst - The instruction using the induction variable.
335 /// OperandValToReplace - The operand value of Inst to replace with the
337 Value *OperandValToReplace;
339 /// Imm - The immediate value that should be added to the base immediately
340 /// before Inst, because it will be folded into the imm field of the
341 /// instruction. This is also sometimes used for loop-variant values that
342 /// must be added inside the loop.
345 /// Phi - The induction variable that performs the striding that
346 /// should be used for this user.
349 // isUseOfPostIncrementedValue - True if this should use the
350 // post-incremented version of this IV, not the preincremented version.
351 // This can only be set in special cases, such as the terminating setcc
352 // instruction for a loop and uses outside the loop that are dominated by
354 bool isUseOfPostIncrementedValue;
356 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
357 : SE(se), Base(IVSU.getOffset()), Inst(IVSU.getUser()),
358 OperandValToReplace(IVSU.getOperandValToReplace()),
359 Imm(SE->getIntegerSCEV(0, Base->getType())),
360 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue()) {}
362 // Once we rewrite the code to insert the new IVs we want, update the
363 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
365 void RewriteInstructionToUseNewBase(const SCEV *const &NewBase,
366 Instruction *InsertPt,
367 SCEVExpander &Rewriter, Loop *L, Pass *P,
369 SmallVectorImpl<WeakVH> &DeadInsts);
371 Value *InsertCodeForBaseAtPosition(const SCEV *const &NewBase,
373 SCEVExpander &Rewriter,
374 Instruction *IP, Loop *L,
380 void BasedUser::dump() const {
381 errs() << " Base=" << *Base;
382 errs() << " Imm=" << *Imm;
383 errs() << " Inst: " << *Inst;
386 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEV *const &NewBase,
388 SCEVExpander &Rewriter,
389 Instruction *IP, Loop *L,
391 // Figure out where we *really* want to insert this code. In particular, if
392 // the user is inside of a loop that is nested inside of L, we really don't
393 // want to insert this expression before the user, we'd rather pull it out as
394 // many loops as possible.
395 Instruction *BaseInsertPt = IP;
397 // Figure out the most-nested loop that IP is in.
398 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
400 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
401 // the preheader of the outer-most loop where NewBase is not loop invariant.
402 if (L->contains(IP->getParent()))
403 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
404 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
405 InsertLoop = InsertLoop->getParentLoop();
408 Value *Base = Rewriter.expandCodeFor(NewBase, 0, BaseInsertPt);
410 const SCEV *NewValSCEV = SE->getUnknown(Base);
412 // Always emit the immediate into the same block as the user.
413 NewValSCEV = SE->getAddExpr(NewValSCEV, Imm);
415 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
419 // Once we rewrite the code to insert the new IVs we want, update the
420 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
421 // to it. NewBasePt is the last instruction which contributes to the
422 // value of NewBase in the case that it's a diffferent instruction from
423 // the PHI that NewBase is computed from, or null otherwise.
425 void BasedUser::RewriteInstructionToUseNewBase(const SCEV *const &NewBase,
426 Instruction *NewBasePt,
427 SCEVExpander &Rewriter, Loop *L, Pass *P,
429 SmallVectorImpl<WeakVH> &DeadInsts) {
430 if (!isa<PHINode>(Inst)) {
431 // By default, insert code at the user instruction.
432 BasicBlock::iterator InsertPt = Inst;
434 // However, if the Operand is itself an instruction, the (potentially
435 // complex) inserted code may be shared by many users. Because of this, we
436 // want to emit code for the computation of the operand right before its old
437 // computation. This is usually safe, because we obviously used to use the
438 // computation when it was computed in its current block. However, in some
439 // cases (e.g. use of a post-incremented induction variable) the NewBase
440 // value will be pinned to live somewhere after the original computation.
441 // In this case, we have to back off.
443 // If this is a use outside the loop (which means after, since it is based
444 // on a loop indvar) we use the post-incremented value, so that we don't
445 // artificially make the preinc value live out the bottom of the loop.
446 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
447 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
448 InsertPt = NewBasePt;
450 } else if (Instruction *OpInst
451 = dyn_cast<Instruction>(OperandValToReplace)) {
453 while (isa<PHINode>(InsertPt)) ++InsertPt;
456 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
457 OperandValToReplace->getType(),
458 Rewriter, InsertPt, L, LI);
459 // Replace the use of the operand Value with the new Phi we just created.
460 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
462 DEBUG(errs() << " Replacing with ");
463 DEBUG(WriteAsOperand(errs(), NewVal, /*PrintType=*/false));
464 DEBUG(errs() << ", which has value " << *NewBase << " plus IMM "
469 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
470 // expression into each operand block that uses it. Note that PHI nodes can
471 // have multiple entries for the same predecessor. We use a map to make sure
472 // that a PHI node only has a single Value* for each predecessor (which also
473 // prevents us from inserting duplicate code in some blocks).
474 DenseMap<BasicBlock*, Value*> InsertedCode;
475 PHINode *PN = cast<PHINode>(Inst);
476 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
477 if (PN->getIncomingValue(i) == OperandValToReplace) {
478 // If the original expression is outside the loop, put the replacement
479 // code in the same place as the original expression,
480 // which need not be an immediate predecessor of this PHI. This way we
481 // need only one copy of it even if it is referenced multiple times in
482 // the PHI. We don't do this when the original expression is inside the
483 // loop because multiple copies sometimes do useful sinking of code in
485 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
486 BasicBlock *PHIPred = PN->getIncomingBlock(i);
487 if (L->contains(OldLoc->getParent())) {
488 // If this is a critical edge, split the edge so that we do not insert
489 // the code on all predecessor/successor paths. We do this unless this
490 // is the canonical backedge for this loop, as this can make some
491 // inserted code be in an illegal position.
492 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
493 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
495 // First step, split the critical edge.
496 BasicBlock *NewBB = SplitCriticalEdge(PHIPred, PN->getParent(),
499 // Next step: move the basic block. In particular, if the PHI node
500 // is outside of the loop, and PredTI is in the loop, we want to
501 // move the block to be immediately before the PHI block, not
502 // immediately after PredTI.
503 if (L->contains(PHIPred) && !L->contains(PN->getParent()))
504 NewBB->moveBefore(PN->getParent());
506 // Splitting the edge can reduce the number of PHI entries we have.
507 e = PN->getNumIncomingValues();
509 i = PN->getBasicBlockIndex(PHIPred);
512 Value *&Code = InsertedCode[PHIPred];
514 // Insert the code into the end of the predecessor block.
515 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
516 PHIPred->getTerminator() :
517 OldLoc->getParent()->getTerminator();
518 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
519 Rewriter, InsertPt, L, LI);
521 DEBUG(errs() << " Changing PHI use to ");
522 DEBUG(WriteAsOperand(errs(), Code, /*PrintType=*/false));
523 DEBUG(errs() << ", which has value " << *NewBase << " plus IMM "
527 // Replace the use of the operand Value with the new Phi we just created.
528 PN->setIncomingValue(i, Code);
533 // PHI node might have become a constant value after SplitCriticalEdge.
534 DeadInsts.push_back(Inst);
538 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
539 /// mode, and does not need to be put in a register first.
540 static bool fitsInAddressMode(const SCEV *const &V, const Type *AccessTy,
541 const TargetLowering *TLI, bool HasBaseReg) {
542 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
543 int64_t VC = SC->getValue()->getSExtValue();
545 TargetLowering::AddrMode AM;
547 AM.HasBaseReg = HasBaseReg;
548 return TLI->isLegalAddressingMode(AM, AccessTy);
550 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
551 return (VC > -(1 << 16) && VC < (1 << 16)-1);
555 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
556 if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
558 TargetLowering::AddrMode AM;
560 AM.HasBaseReg = HasBaseReg;
561 return TLI->isLegalAddressingMode(AM, AccessTy);
563 // Default: assume global addresses are not legal.
570 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
571 /// loop varying to the Imm operand.
572 static void MoveLoopVariantsToImmediateField(const SCEV *&Val, const SCEV *&Imm,
573 Loop *L, ScalarEvolution *SE) {
574 if (Val->isLoopInvariant(L)) return; // Nothing to do.
576 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
577 SmallVector<const SCEV *, 4> NewOps;
578 NewOps.reserve(SAE->getNumOperands());
580 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
581 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
582 // If this is a loop-variant expression, it must stay in the immediate
583 // field of the expression.
584 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
586 NewOps.push_back(SAE->getOperand(i));
590 Val = SE->getIntegerSCEV(0, Val->getType());
592 Val = SE->getAddExpr(NewOps);
593 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
594 // Try to pull immediates out of the start value of nested addrec's.
595 const SCEV *Start = SARE->getStart();
596 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
598 SmallVector<const SCEV *, 4> Ops(SARE->op_begin(), SARE->op_end());
600 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
602 // Otherwise, all of Val is variant, move the whole thing over.
603 Imm = SE->getAddExpr(Imm, Val);
604 Val = SE->getIntegerSCEV(0, Val->getType());
609 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
610 /// that can fit into the immediate field of instructions in the target.
611 /// Accumulate these immediate values into the Imm value.
612 static void MoveImmediateValues(const TargetLowering *TLI,
613 const Type *AccessTy,
614 const SCEV *&Val, const SCEV *&Imm,
615 bool isAddress, Loop *L,
616 ScalarEvolution *SE) {
617 if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
618 SmallVector<const SCEV *, 4> NewOps;
619 NewOps.reserve(SAE->getNumOperands());
621 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
622 const SCEV *NewOp = SAE->getOperand(i);
623 MoveImmediateValues(TLI, AccessTy, NewOp, Imm, isAddress, L, SE);
625 if (!NewOp->isLoopInvariant(L)) {
626 // If this is a loop-variant expression, it must stay in the immediate
627 // field of the expression.
628 Imm = SE->getAddExpr(Imm, NewOp);
630 NewOps.push_back(NewOp);
635 Val = SE->getIntegerSCEV(0, Val->getType());
637 Val = SE->getAddExpr(NewOps);
639 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
640 // Try to pull immediates out of the start value of nested addrec's.
641 const SCEV *Start = SARE->getStart();
642 MoveImmediateValues(TLI, AccessTy, Start, Imm, isAddress, L, SE);
644 if (Start != SARE->getStart()) {
645 SmallVector<const SCEV *, 4> Ops(SARE->op_begin(), SARE->op_end());
647 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
650 } else if (const SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
651 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
653 fitsInAddressMode(SME->getOperand(0), AccessTy, TLI, false) &&
654 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
656 const SCEV *SubImm = SE->getIntegerSCEV(0, Val->getType());
657 const SCEV *NewOp = SME->getOperand(1);
658 MoveImmediateValues(TLI, AccessTy, NewOp, SubImm, isAddress, L, SE);
660 // If we extracted something out of the subexpressions, see if we can
662 if (NewOp != SME->getOperand(1)) {
663 // Scale SubImm up by "8". If the result is a target constant, we are
665 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
666 if (fitsInAddressMode(SubImm, AccessTy, TLI, false)) {
667 // Accumulate the immediate.
668 Imm = SE->getAddExpr(Imm, SubImm);
670 // Update what is left of 'Val'.
671 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
678 // Loop-variant expressions must stay in the immediate field of the
680 if ((isAddress && fitsInAddressMode(Val, AccessTy, TLI, false)) ||
681 !Val->isLoopInvariant(L)) {
682 Imm = SE->getAddExpr(Imm, Val);
683 Val = SE->getIntegerSCEV(0, Val->getType());
687 // Otherwise, no immediates to move.
690 static void MoveImmediateValues(const TargetLowering *TLI,
692 const SCEV *&Val, const SCEV *&Imm,
693 bool isAddress, Loop *L,
694 ScalarEvolution *SE) {
695 const Type *AccessTy = getAccessType(User);
696 MoveImmediateValues(TLI, AccessTy, Val, Imm, isAddress, L, SE);
699 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
700 /// added together. This is used to reassociate common addition subexprs
701 /// together for maximal sharing when rewriting bases.
702 static void SeparateSubExprs(SmallVector<const SCEV *, 16> &SubExprs,
704 ScalarEvolution *SE) {
705 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
706 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
707 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
708 } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
709 const SCEV *Zero = SE->getIntegerSCEV(0, Expr->getType());
710 if (SARE->getOperand(0) == Zero) {
711 SubExprs.push_back(Expr);
713 // Compute the addrec with zero as its base.
714 SmallVector<const SCEV *, 4> Ops(SARE->op_begin(), SARE->op_end());
715 Ops[0] = Zero; // Start with zero base.
716 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
719 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
721 } else if (!Expr->isZero()) {
723 SubExprs.push_back(Expr);
727 // This is logically local to the following function, but C++ says we have
728 // to make it file scope.
729 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
731 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
732 /// the Uses, removing any common subexpressions, except that if all such
733 /// subexpressions can be folded into an addressing mode for all uses inside
734 /// the loop (this case is referred to as "free" in comments herein) we do
735 /// not remove anything. This looks for things like (a+b+c) and
736 /// (a+c+d) and computes the common (a+c) subexpression. The common expression
737 /// is *removed* from the Bases and returned.
739 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
740 ScalarEvolution *SE, Loop *L,
741 const TargetLowering *TLI) {
742 unsigned NumUses = Uses.size();
744 // Only one use? This is a very common case, so we handle it specially and
746 const SCEV *Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
747 const SCEV *Result = Zero;
748 const SCEV *FreeResult = Zero;
750 // If the use is inside the loop, use its base, regardless of what it is:
751 // it is clearly shared across all the IV's. If the use is outside the loop
752 // (which means after it) we don't want to factor anything *into* the loop,
753 // so just use 0 as the base.
754 if (L->contains(Uses[0].Inst->getParent()))
755 std::swap(Result, Uses[0].Base);
759 // To find common subexpressions, count how many of Uses use each expression.
760 // If any subexpressions are used Uses.size() times, they are common.
761 // Also track whether all uses of each expression can be moved into an
762 // an addressing mode "for free"; such expressions are left within the loop.
763 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
764 std::map<const SCEV *, SubExprUseData> SubExpressionUseData;
766 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
767 // order we see them.
768 SmallVector<const SCEV *, 16> UniqueSubExprs;
770 SmallVector<const SCEV *, 16> SubExprs;
771 unsigned NumUsesInsideLoop = 0;
772 for (unsigned i = 0; i != NumUses; ++i) {
773 // If the user is outside the loop, just ignore it for base computation.
774 // Since the user is outside the loop, it must be *after* the loop (if it
775 // were before, it could not be based on the loop IV). We don't want users
776 // after the loop to affect base computation of values *inside* the loop,
777 // because we can always add their offsets to the result IV after the loop
778 // is done, ensuring we get good code inside the loop.
779 if (!L->contains(Uses[i].Inst->getParent()))
783 // If the base is zero (which is common), return zero now, there are no
785 if (Uses[i].Base == Zero) return Zero;
787 // If this use is as an address we may be able to put CSEs in the addressing
788 // mode rather than hoisting them.
789 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
790 // We may need the AccessTy below, but only when isAddrUse, so compute it
791 // only in that case.
792 const Type *AccessTy = 0;
794 AccessTy = getAccessType(Uses[i].Inst);
796 // Split the expression into subexprs.
797 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
798 // Add one to SubExpressionUseData.Count for each subexpr present, and
799 // if the subexpr is not a valid immediate within an addressing mode use,
800 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
801 // hoist these out of the loop (if they are common to all uses).
802 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
803 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
804 UniqueSubExprs.push_back(SubExprs[j]);
805 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], AccessTy, TLI, false))
806 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
811 // Now that we know how many times each is used, build Result. Iterate over
812 // UniqueSubexprs so that we have a stable ordering.
813 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
814 std::map<const SCEV *, SubExprUseData>::iterator I =
815 SubExpressionUseData.find(UniqueSubExprs[i]);
816 assert(I != SubExpressionUseData.end() && "Entry not found?");
817 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
818 if (I->second.notAllUsesAreFree)
819 Result = SE->getAddExpr(Result, I->first);
821 FreeResult = SE->getAddExpr(FreeResult, I->first);
823 // Remove non-cse's from SubExpressionUseData.
824 SubExpressionUseData.erase(I);
827 if (FreeResult != Zero) {
828 // We have some subexpressions that can be subsumed into addressing
829 // modes in every use inside the loop. However, it's possible that
830 // there are so many of them that the combined FreeResult cannot
831 // be subsumed, or that the target cannot handle both a FreeResult
832 // and a Result in the same instruction (for example because it would
833 // require too many registers). Check this.
834 for (unsigned i=0; i<NumUses; ++i) {
835 if (!L->contains(Uses[i].Inst->getParent()))
837 // We know this is an addressing mode use; if there are any uses that
838 // are not, FreeResult would be Zero.
839 const Type *AccessTy = getAccessType(Uses[i].Inst);
840 if (!fitsInAddressMode(FreeResult, AccessTy, TLI, Result!=Zero)) {
841 // FIXME: could split up FreeResult into pieces here, some hoisted
842 // and some not. There is no obvious advantage to this.
843 Result = SE->getAddExpr(Result, FreeResult);
850 // If we found no CSE's, return now.
851 if (Result == Zero) return Result;
853 // If we still have a FreeResult, remove its subexpressions from
854 // SubExpressionUseData. This means they will remain in the use Bases.
855 if (FreeResult != Zero) {
856 SeparateSubExprs(SubExprs, FreeResult, SE);
857 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
858 std::map<const SCEV *, SubExprUseData>::iterator I =
859 SubExpressionUseData.find(SubExprs[j]);
860 SubExpressionUseData.erase(I);
865 // Otherwise, remove all of the CSE's we found from each of the base values.
866 for (unsigned i = 0; i != NumUses; ++i) {
867 // Uses outside the loop don't necessarily include the common base, but
868 // the final IV value coming into those uses does. Instead of trying to
869 // remove the pieces of the common base, which might not be there,
870 // subtract off the base to compensate for this.
871 if (!L->contains(Uses[i].Inst->getParent())) {
872 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
876 // Split the expression into subexprs.
877 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
879 // Remove any common subexpressions.
880 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
881 if (SubExpressionUseData.count(SubExprs[j])) {
882 SubExprs.erase(SubExprs.begin()+j);
886 // Finally, add the non-shared expressions together.
887 if (SubExprs.empty())
890 Uses[i].Base = SE->getAddExpr(SubExprs);
897 /// ValidScale - Check whether the given Scale is valid for all loads and
898 /// stores in UsersToProcess.
900 bool LoopStrengthReduce::ValidScale(bool HasBaseReg, int64_t Scale,
901 const std::vector<BasedUser>& UsersToProcess) {
905 for (unsigned i = 0, e = UsersToProcess.size(); i!=e; ++i) {
906 // If this is a load or other access, pass the type of the access in.
907 const Type *AccessTy =
908 Type::getVoidTy(UsersToProcess[i].Inst->getContext());
909 if (isAddressUse(UsersToProcess[i].Inst,
910 UsersToProcess[i].OperandValToReplace))
911 AccessTy = getAccessType(UsersToProcess[i].Inst);
912 else if (isa<PHINode>(UsersToProcess[i].Inst))
915 TargetLowering::AddrMode AM;
916 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
917 AM.BaseOffs = SC->getValue()->getSExtValue();
918 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
921 // If load[imm+r*scale] is illegal, bail out.
922 if (!TLI->isLegalAddressingMode(AM, AccessTy))
928 /// ValidOffset - Check whether the given Offset is valid for all loads and
929 /// stores in UsersToProcess.
931 bool LoopStrengthReduce::ValidOffset(bool HasBaseReg,
934 const std::vector<BasedUser>& UsersToProcess) {
938 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
939 // If this is a load or other access, pass the type of the access in.
940 const Type *AccessTy =
941 Type::getVoidTy(UsersToProcess[i].Inst->getContext());
942 if (isAddressUse(UsersToProcess[i].Inst,
943 UsersToProcess[i].OperandValToReplace))
944 AccessTy = getAccessType(UsersToProcess[i].Inst);
945 else if (isa<PHINode>(UsersToProcess[i].Inst))
948 TargetLowering::AddrMode AM;
949 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
950 AM.BaseOffs = SC->getValue()->getSExtValue();
951 AM.BaseOffs = (uint64_t)AM.BaseOffs + (uint64_t)Offset;
952 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
955 // If load[imm+r*scale] is illegal, bail out.
956 if (!TLI->isLegalAddressingMode(AM, AccessTy))
962 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
964 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
968 Ty1 = SE->getEffectiveSCEVType(Ty1);
969 Ty2 = SE->getEffectiveSCEVType(Ty2);
972 if (Ty1->canLosslesslyBitCastTo(Ty2))
974 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
979 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
980 /// of a previous stride and it is a legal value for the target addressing
981 /// mode scale component and optional base reg. This allows the users of
982 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
983 /// reuse is possible. Factors can be negative on same targets, e.g. ARM.
985 /// If all uses are outside the loop, we don't require that all multiplies
986 /// be folded into the addressing mode, nor even that the factor be constant;
987 /// a multiply (executed once) outside the loop is better than another IV
988 /// within. Well, usually.
989 const SCEV *LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
990 bool AllUsesAreAddresses,
991 bool AllUsesAreOutsideLoop,
992 const SCEV *const &Stride,
993 IVExpr &IV, const Type *Ty,
994 const std::vector<BasedUser>& UsersToProcess) {
995 if (StrideNoReuse.count(Stride))
996 return SE->getIntegerSCEV(0, Stride->getType());
998 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
999 int64_t SInt = SC->getValue()->getSExtValue();
1000 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1001 NewStride != e; ++NewStride) {
1002 std::map<const SCEV *, IVsOfOneStride>::iterator SI =
1003 IVsByStride.find(IU->StrideOrder[NewStride]);
1004 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first) ||
1005 StrideNoReuse.count(SI->first))
1007 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1008 if (SI->first != Stride &&
1009 (unsigned(abs64(SInt)) < SSInt || (SInt % SSInt) != 0))
1011 int64_t Scale = SInt / SSInt;
1012 // Check that this stride is valid for all the types used for loads and
1013 // stores; if it can be used for some and not others, we might as well use
1014 // the original stride everywhere, since we have to create the IV for it
1015 // anyway. If the scale is 1, then we don't need to worry about folding
1018 (AllUsesAreAddresses &&
1019 ValidScale(HasBaseReg, Scale, UsersToProcess))) {
1020 // Prefer to reuse an IV with a base of zero.
1021 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1022 IE = SI->second.IVs.end(); II != IE; ++II)
1023 // Only reuse previous IV if it would not require a type conversion
1024 // and if the base difference can be folded.
1025 if (II->Base->isZero() &&
1026 !RequiresTypeConversion(II->Base->getType(), Ty)) {
1028 return SE->getIntegerSCEV(Scale, Stride->getType());
1030 // Otherwise, settle for an IV with a foldable base.
1031 if (AllUsesAreAddresses)
1032 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1033 IE = SI->second.IVs.end(); II != IE; ++II)
1034 // Only reuse previous IV if it would not require a type conversion
1035 // and if the base difference can be folded.
1036 if (SE->getEffectiveSCEVType(II->Base->getType()) ==
1037 SE->getEffectiveSCEVType(Ty) &&
1038 isa<SCEVConstant>(II->Base)) {
1040 cast<SCEVConstant>(II->Base)->getValue()->getSExtValue();
1041 if (Base > INT32_MIN && Base <= INT32_MAX &&
1042 ValidOffset(HasBaseReg, -Base * Scale,
1043 Scale, UsersToProcess)) {
1045 return SE->getIntegerSCEV(Scale, Stride->getType());
1050 } else if (AllUsesAreOutsideLoop) {
1051 // Accept nonconstant strides here; it is really really right to substitute
1052 // an existing IV if we can.
1053 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1054 NewStride != e; ++NewStride) {
1055 std::map<const SCEV *, IVsOfOneStride>::iterator SI =
1056 IVsByStride.find(IU->StrideOrder[NewStride]);
1057 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1059 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1060 if (SI->first != Stride && SSInt != 1)
1062 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1063 IE = SI->second.IVs.end(); II != IE; ++II)
1064 // Accept nonzero base here.
1065 // Only reuse previous IV if it would not require a type conversion.
1066 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1071 // Special case, old IV is -1*x and this one is x. Can treat this one as
1073 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1074 NewStride != e; ++NewStride) {
1075 std::map<const SCEV *, IVsOfOneStride>::iterator SI =
1076 IVsByStride.find(IU->StrideOrder[NewStride]);
1077 if (SI == IVsByStride.end())
1079 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1080 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1081 if (Stride == ME->getOperand(1) &&
1082 SC->getValue()->getSExtValue() == -1LL)
1083 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1084 IE = SI->second.IVs.end(); II != IE; ++II)
1085 // Accept nonzero base here.
1086 // Only reuse previous IV if it would not require type conversion.
1087 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1089 return SE->getIntegerSCEV(-1LL, Stride->getType());
1093 return SE->getIntegerSCEV(0, Stride->getType());
1096 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1097 /// returns true if Val's isUseOfPostIncrementedValue is true.
1098 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1099 return Val.isUseOfPostIncrementedValue;
1102 /// isNonConstantNegative - Return true if the specified scev is negated, but
1104 static bool isNonConstantNegative(const SCEV *const &Expr) {
1105 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1106 if (!Mul) return false;
1108 // If there is a constant factor, it will be first.
1109 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1110 if (!SC) return false;
1112 // Return true if the value is negative, this matches things like (-42 * V).
1113 return SC->getValue()->getValue().isNegative();
1116 /// CollectIVUsers - Transform our list of users and offsets to a bit more
1117 /// complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1118 /// of the strided accesses, as well as the old information from Uses. We
1119 /// progressively move information from the Base field to the Imm field, until
1120 /// we eventually have the full access expression to rewrite the use.
1121 const SCEV *LoopStrengthReduce::CollectIVUsers(const SCEV *const &Stride,
1122 IVUsersOfOneStride &Uses,
1124 bool &AllUsesAreAddresses,
1125 bool &AllUsesAreOutsideLoop,
1126 std::vector<BasedUser> &UsersToProcess) {
1127 // FIXME: Generalize to non-affine IV's.
1128 if (!Stride->isLoopInvariant(L))
1129 return SE->getIntegerSCEV(0, Stride->getType());
1131 UsersToProcess.reserve(Uses.Users.size());
1132 for (ilist<IVStrideUse>::iterator I = Uses.Users.begin(),
1133 E = Uses.Users.end(); I != E; ++I) {
1134 UsersToProcess.push_back(BasedUser(*I, SE));
1136 // Move any loop variant operands from the offset field to the immediate
1137 // field of the use, so that we don't try to use something before it is
1139 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1140 UsersToProcess.back().Imm, L, SE);
1141 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1142 "Base value is not loop invariant!");
1145 // We now have a whole bunch of uses of like-strided induction variables, but
1146 // they might all have different bases. We want to emit one PHI node for this
1147 // stride which we fold as many common expressions (between the IVs) into as
1148 // possible. Start by identifying the common expressions in the base values
1149 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1150 // "A+B"), emit it to the preheader, then remove the expression from the
1151 // UsersToProcess base values.
1152 const SCEV *CommonExprs =
1153 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1155 // Next, figure out what we can represent in the immediate fields of
1156 // instructions. If we can represent anything there, move it to the imm
1157 // fields of the BasedUsers. We do this so that it increases the commonality
1158 // of the remaining uses.
1159 unsigned NumPHI = 0;
1160 bool HasAddress = false;
1161 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1162 // If the user is not in the current loop, this means it is using the exit
1163 // value of the IV. Do not put anything in the base, make sure it's all in
1164 // the immediate field to allow as much factoring as possible.
1165 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1166 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1167 UsersToProcess[i].Base);
1168 UsersToProcess[i].Base =
1169 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1171 // Not all uses are outside the loop.
1172 AllUsesAreOutsideLoop = false;
1174 // Addressing modes can be folded into loads and stores. Be careful that
1175 // the store is through the expression, not of the expression though.
1177 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1178 UsersToProcess[i].OperandValToReplace);
1179 if (isa<PHINode>(UsersToProcess[i].Inst)) {
1187 // If this use isn't an address, then not all uses are addresses.
1188 if (!isAddress && !isPHI)
1189 AllUsesAreAddresses = false;
1191 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1192 UsersToProcess[i].Imm, isAddress, L, SE);
1196 // If one of the use is a PHI node and all other uses are addresses, still
1197 // allow iv reuse. Essentially we are trading one constant multiplication
1198 // for one fewer iv.
1200 AllUsesAreAddresses = false;
1202 // There are no in-loop address uses.
1203 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1204 AllUsesAreAddresses = false;
1209 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1210 /// is valid and profitable for the given set of users of a stride. In
1211 /// full strength-reduction mode, all addresses at the current stride are
1212 /// strength-reduced all the way down to pointer arithmetic.
1214 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1215 const std::vector<BasedUser> &UsersToProcess,
1217 bool AllUsesAreAddresses,
1218 const SCEV *Stride) {
1219 if (!EnableFullLSRMode)
1222 // The heuristics below aim to avoid increasing register pressure, but
1223 // fully strength-reducing all the addresses increases the number of
1224 // add instructions, so don't do this when optimizing for size.
1225 // TODO: If the loop is large, the savings due to simpler addresses
1226 // may oughtweight the costs of the extra increment instructions.
1227 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1230 // TODO: For now, don't do full strength reduction if there could
1231 // potentially be greater-stride multiples of the current stride
1232 // which could reuse the current stride IV.
1233 if (IU->StrideOrder.back() != Stride)
1236 // Iterate through the uses to find conditions that automatically rule out
1238 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1239 const SCEV *Base = UsersToProcess[i].Base;
1240 const SCEV *Imm = UsersToProcess[i].Imm;
1241 // If any users have a loop-variant component, they can't be fully
1242 // strength-reduced.
1243 if (Imm && !Imm->isLoopInvariant(L))
1245 // If there are to users with the same base and the difference between
1246 // the two Imm values can't be folded into the address, full
1247 // strength reduction would increase register pressure.
1249 const SCEV *CurImm = UsersToProcess[i].Imm;
1250 if ((CurImm || Imm) && CurImm != Imm) {
1251 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1252 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1253 const Instruction *Inst = UsersToProcess[i].Inst;
1254 const Type *AccessTy = getAccessType(Inst);
1255 const SCEV *Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1256 if (!Diff->isZero() &&
1257 (!AllUsesAreAddresses ||
1258 !fitsInAddressMode(Diff, AccessTy, TLI, /*HasBaseReg=*/true)))
1261 } while (++i != e && Base == UsersToProcess[i].Base);
1264 // If there's exactly one user in this stride, fully strength-reducing it
1265 // won't increase register pressure. If it's starting from a non-zero base,
1266 // it'll be simpler this way.
1267 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1270 // Otherwise, if there are any users in this stride that don't require
1271 // a register for their base, full strength-reduction will increase
1272 // register pressure.
1273 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1274 if (UsersToProcess[i].Base->isZero())
1277 // Otherwise, go for it.
1281 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1282 /// with the specified start and step values in the specified loop.
1284 /// If NegateStride is true, the stride should be negated by using a
1285 /// subtract instead of an add.
1287 /// Return the created phi node.
1289 static PHINode *InsertAffinePhi(const SCEV *Start, const SCEV *Step,
1290 Instruction *IVIncInsertPt,
1292 SCEVExpander &Rewriter) {
1293 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1294 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1296 BasicBlock *Header = L->getHeader();
1297 BasicBlock *Preheader = L->getLoopPreheader();
1298 BasicBlock *LatchBlock = L->getLoopLatch();
1299 const Type *Ty = Start->getType();
1300 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1302 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1303 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1306 // If the stride is negative, insert a sub instead of an add for the
1308 bool isNegative = isNonConstantNegative(Step);
1309 const SCEV *IncAmount = Step;
1311 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1313 // Insert an add instruction right before the terminator corresponding
1314 // to the back-edge or just before the only use. The location is determined
1315 // by the caller and passed in as IVIncInsertPt.
1316 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1317 Preheader->getTerminator());
1320 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1323 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1326 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1328 PN->addIncoming(IncV, LatchBlock);
1334 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1335 // We want to emit code for users inside the loop first. To do this, we
1336 // rearrange BasedUser so that the entries at the end have
1337 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1338 // vector (so we handle them first).
1339 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1340 PartitionByIsUseOfPostIncrementedValue);
1342 // Sort this by base, so that things with the same base are handled
1343 // together. By partitioning first and stable-sorting later, we are
1344 // guaranteed that within each base we will pop off users from within the
1345 // loop before users outside of the loop with a particular base.
1347 // We would like to use stable_sort here, but we can't. The problem is that
1348 // const SCEV *'s don't have a deterministic ordering w.r.t to each other, so
1349 // we don't have anything to do a '<' comparison on. Because we think the
1350 // number of uses is small, do a horrible bubble sort which just relies on
1352 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1353 // Get a base value.
1354 const SCEV *Base = UsersToProcess[i].Base;
1356 // Compact everything with this base to be consecutive with this one.
1357 for (unsigned j = i+1; j != e; ++j) {
1358 if (UsersToProcess[j].Base == Base) {
1359 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1366 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1367 /// UsersToProcess, meaning lowering addresses all the way down to direct
1368 /// pointer arithmetic.
1371 LoopStrengthReduce::PrepareToStrengthReduceFully(
1372 std::vector<BasedUser> &UsersToProcess,
1374 const SCEV *CommonExprs,
1376 SCEVExpander &PreheaderRewriter) {
1377 DEBUG(errs() << " Fully reducing all users\n");
1379 // Rewrite the UsersToProcess records, creating a separate PHI for each
1380 // unique Base value.
1381 Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
1382 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1383 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1384 // pick the first Imm value here to start with, and adjust it for the
1386 const SCEV *Imm = UsersToProcess[i].Imm;
1387 const SCEV *Base = UsersToProcess[i].Base;
1388 const SCEV *Start = SE->getAddExpr(CommonExprs, Base, Imm);
1389 PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
1391 // Loop over all the users with the same base.
1393 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1394 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1395 UsersToProcess[i].Phi = Phi;
1396 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1397 "ShouldUseFullStrengthReductionMode should reject this!");
1398 } while (++i != e && Base == UsersToProcess[i].Base);
1402 /// FindIVIncInsertPt - Return the location to insert the increment instruction.
1403 /// If the only use if a use of postinc value, (must be the loop termination
1404 /// condition), then insert it just before the use.
1405 static Instruction *FindIVIncInsertPt(std::vector<BasedUser> &UsersToProcess,
1407 if (UsersToProcess.size() == 1 &&
1408 UsersToProcess[0].isUseOfPostIncrementedValue &&
1409 L->contains(UsersToProcess[0].Inst->getParent()))
1410 return UsersToProcess[0].Inst;
1411 return L->getLoopLatch()->getTerminator();
1414 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1415 /// given users to share.
1418 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1419 std::vector<BasedUser> &UsersToProcess,
1421 const SCEV *CommonExprs,
1423 Instruction *IVIncInsertPt,
1425 SCEVExpander &PreheaderRewriter) {
1426 DEBUG(errs() << " Inserting new PHI:\n");
1428 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1429 Stride, IVIncInsertPt, L,
1432 // Remember this in case a later stride is multiple of this.
1433 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1435 // All the users will share this new IV.
1436 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1437 UsersToProcess[i].Phi = Phi;
1439 DEBUG(errs() << " IV=");
1440 DEBUG(WriteAsOperand(errs(), Phi, /*PrintType=*/false));
1441 DEBUG(errs() << "\n");
1444 /// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1445 /// reuse an induction variable with a stride that is a factor of the current
1446 /// induction variable.
1449 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1450 std::vector<BasedUser> &UsersToProcess,
1452 const IVExpr &ReuseIV,
1453 Instruction *PreInsertPt) {
1454 DEBUG(errs() << " Rewriting in terms of existing IV of STRIDE "
1455 << *ReuseIV.Stride << " and BASE " << *ReuseIV.Base << "\n");
1457 // All the users will share the reused IV.
1458 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1459 UsersToProcess[i].Phi = ReuseIV.PHI;
1461 Constant *C = dyn_cast<Constant>(CommonBaseV);
1463 (!C->isNullValue() &&
1464 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1466 // We want the common base emitted into the preheader! This is just
1467 // using cast as a copy so BitCast (no-op cast) is appropriate
1468 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1469 "commonbase", PreInsertPt);
1472 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1473 const Type *AccessTy,
1474 std::vector<BasedUser> &UsersToProcess,
1475 const TargetLowering *TLI) {
1476 SmallVector<Instruction*, 16> AddrModeInsts;
1477 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1478 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1480 ExtAddrMode AddrMode =
1481 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1482 AccessTy, UsersToProcess[i].Inst,
1483 AddrModeInsts, *TLI);
1484 if (GV && GV != AddrMode.BaseGV)
1486 if (Offset && !AddrMode.BaseOffs)
1487 // FIXME: How to accurate check it's immediate offset is folded.
1489 AddrModeInsts.clear();
1494 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1495 /// stride of IV. All of the users may have different starting values, and this
1496 /// may not be the only stride.
1497 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEV *const &Stride,
1498 IVUsersOfOneStride &Uses,
1500 // If all the users are moved to another stride, then there is nothing to do.
1501 if (Uses.Users.empty())
1504 // Keep track if every use in UsersToProcess is an address. If they all are,
1505 // we may be able to rewrite the entire collection of them in terms of a
1506 // smaller-stride IV.
1507 bool AllUsesAreAddresses = true;
1509 // Keep track if every use of a single stride is outside the loop. If so,
1510 // we want to be more aggressive about reusing a smaller-stride IV; a
1511 // multiply outside the loop is better than another IV inside. Well, usually.
1512 bool AllUsesAreOutsideLoop = true;
1514 // Transform our list of users and offsets to a bit more complex table. In
1515 // this new vector, each 'BasedUser' contains 'Base' the base of the
1516 // strided accessas well as the old information from Uses. We progressively
1517 // move information from the Base field to the Imm field, until we eventually
1518 // have the full access expression to rewrite the use.
1519 std::vector<BasedUser> UsersToProcess;
1520 const SCEV *CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1521 AllUsesAreOutsideLoop,
1524 // Sort the UsersToProcess array so that users with common bases are
1525 // next to each other.
1526 SortUsersToProcess(UsersToProcess);
1528 // If we managed to find some expressions in common, we'll need to carry
1529 // their value in a register and add it in for each use. This will take up
1530 // a register operand, which potentially restricts what stride values are
1532 bool HaveCommonExprs = !CommonExprs->isZero();
1533 const Type *ReplacedTy = CommonExprs->getType();
1535 // If all uses are addresses, consider sinking the immediate part of the
1536 // common expression back into uses if they can fit in the immediate fields.
1537 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1538 const SCEV *NewCommon = CommonExprs;
1539 const SCEV *Imm = SE->getIntegerSCEV(0, ReplacedTy);
1540 MoveImmediateValues(TLI, Type::getVoidTy(
1541 L->getLoopPreheader()->getContext()),
1542 NewCommon, Imm, true, L, SE);
1543 if (!Imm->isZero()) {
1546 // If the immediate part of the common expression is a GV, check if it's
1547 // possible to fold it into the target addressing mode.
1548 GlobalValue *GV = 0;
1549 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1550 GV = dyn_cast<GlobalValue>(SU->getValue());
1552 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1553 Offset = SC->getValue()->getSExtValue();
1555 // Pass VoidTy as the AccessTy to be conservative, because
1556 // there could be multiple access types among all the uses.
1557 DoSink = IsImmFoldedIntoAddrMode(GV, Offset,
1558 Type::getVoidTy(L->getLoopPreheader()->getContext()),
1559 UsersToProcess, TLI);
1562 DEBUG(errs() << " Sinking " << *Imm << " back down into uses\n");
1563 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1564 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1565 CommonExprs = NewCommon;
1566 HaveCommonExprs = !CommonExprs->isZero();
1572 // Now that we know what we need to do, insert the PHI node itself.
1574 DEBUG(errs() << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1576 << " Common base: " << *CommonExprs << "\n");
1578 SCEVExpander Rewriter(*SE);
1579 SCEVExpander PreheaderRewriter(*SE);
1581 BasicBlock *Preheader = L->getLoopPreheader();
1582 Instruction *PreInsertPt = Preheader->getTerminator();
1583 BasicBlock *LatchBlock = L->getLoopLatch();
1584 Instruction *IVIncInsertPt = LatchBlock->getTerminator();
1586 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1588 const SCEV *RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1589 IVExpr ReuseIV(SE->getIntegerSCEV(0,
1590 Type::getInt32Ty(Preheader->getContext())),
1591 SE->getIntegerSCEV(0,
1592 Type::getInt32Ty(Preheader->getContext())),
1595 /// Choose a strength-reduction strategy and prepare for it by creating
1596 /// the necessary PHIs and adjusting the bookkeeping.
1597 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1598 AllUsesAreAddresses, Stride)) {
1599 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1602 // Emit the initial base value into the loop preheader.
1603 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1606 // If all uses are addresses, check if it is possible to reuse an IV. The
1607 // new IV must have a stride that is a multiple of the old stride; the
1608 // multiple must be a number that can be encoded in the scale field of the
1609 // target addressing mode; and we must have a valid instruction after this
1610 // substitution, including the immediate field, if any.
1611 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1612 AllUsesAreOutsideLoop,
1613 Stride, ReuseIV, ReplacedTy,
1615 if (!RewriteFactor->isZero())
1616 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1617 ReuseIV, PreInsertPt);
1619 IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1620 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1621 CommonBaseV, IVIncInsertPt,
1622 L, PreheaderRewriter);
1626 // Process all the users now, replacing their strided uses with
1627 // strength-reduced forms. This outer loop handles all bases, the inner
1628 // loop handles all users of a particular base.
1629 while (!UsersToProcess.empty()) {
1630 const SCEV *Base = UsersToProcess.back().Base;
1631 Instruction *Inst = UsersToProcess.back().Inst;
1633 // Emit the code for Base into the preheader.
1635 if (!Base->isZero()) {
1636 BaseV = PreheaderRewriter.expandCodeFor(Base, 0, PreInsertPt);
1638 DEBUG(errs() << " INSERTING code for BASE = " << *Base << ":");
1639 if (BaseV->hasName())
1640 DEBUG(errs() << " Result value name = %" << BaseV->getName());
1641 DEBUG(errs() << "\n");
1643 // If BaseV is a non-zero constant, make sure that it gets inserted into
1644 // the preheader, instead of being forward substituted into the uses. We
1645 // do this by forcing a BitCast (noop cast) to be inserted into the
1646 // preheader in this case.
1647 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false) &&
1648 isa<Constant>(BaseV)) {
1649 // We want this constant emitted into the preheader! This is just
1650 // using cast as a copy so BitCast (no-op cast) is appropriate
1651 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1656 // Emit the code to add the immediate offset to the Phi value, just before
1657 // the instructions that we identified as using this stride and base.
1659 // FIXME: Use emitted users to emit other users.
1660 BasedUser &User = UsersToProcess.back();
1662 DEBUG(errs() << " Examining ");
1663 if (User.isUseOfPostIncrementedValue)
1664 DEBUG(errs() << "postinc");
1666 DEBUG(errs() << "preinc");
1667 DEBUG(errs() << " use ");
1668 DEBUG(WriteAsOperand(errs(), UsersToProcess.back().OperandValToReplace,
1669 /*PrintType=*/false));
1670 DEBUG(errs() << " in Inst: " << *User.Inst);
1672 // If this instruction wants to use the post-incremented value, move it
1673 // after the post-inc and use its value instead of the PHI.
1674 Value *RewriteOp = User.Phi;
1675 if (User.isUseOfPostIncrementedValue) {
1676 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1677 // If this user is in the loop, make sure it is the last thing in the
1678 // loop to ensure it is dominated by the increment. In case it's the
1679 // only use of the iv, the increment instruction is already before the
1681 if (L->contains(User.Inst->getParent()) && User.Inst != IVIncInsertPt)
1682 User.Inst->moveBefore(IVIncInsertPt);
1685 const SCEV *RewriteExpr = SE->getUnknown(RewriteOp);
1687 if (SE->getEffectiveSCEVType(RewriteOp->getType()) !=
1688 SE->getEffectiveSCEVType(ReplacedTy)) {
1689 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1690 SE->getTypeSizeInBits(ReplacedTy) &&
1691 "Unexpected widening cast!");
1692 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1695 // If we had to insert new instructions for RewriteOp, we have to
1696 // consider that they may not have been able to end up immediately
1697 // next to RewriteOp, because non-PHI instructions may never precede
1698 // PHI instructions in a block. In this case, remember where the last
1699 // instruction was inserted so that if we're replacing a different
1700 // PHI node, we can use the later point to expand the final
1702 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1703 if (RewriteOp == User.Phi) NewBasePt = 0;
1705 // Clear the SCEVExpander's expression map so that we are guaranteed
1706 // to have the code emitted where we expect it.
1709 // If we are reusing the iv, then it must be multiplied by a constant
1710 // factor to take advantage of the addressing mode scale component.
1711 if (!RewriteFactor->isZero()) {
1712 // If we're reusing an IV with a nonzero base (currently this happens
1713 // only when all reuses are outside the loop) subtract that base here.
1714 // The base has been used to initialize the PHI node but we don't want
1716 if (!ReuseIV.Base->isZero()) {
1717 const SCEV *typedBase = ReuseIV.Base;
1718 if (SE->getEffectiveSCEVType(RewriteExpr->getType()) !=
1719 SE->getEffectiveSCEVType(ReuseIV.Base->getType())) {
1720 // It's possible the original IV is a larger type than the new IV,
1721 // in which case we have to truncate the Base. We checked in
1722 // RequiresTypeConversion that this is valid.
1723 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1724 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1725 "Unexpected lengthening conversion!");
1726 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1727 RewriteExpr->getType());
1729 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1732 // Multiply old variable, with base removed, by new scale factor.
1733 RewriteExpr = SE->getMulExpr(RewriteFactor,
1736 // The common base is emitted in the loop preheader. But since we
1737 // are reusing an IV, it has not been used to initialize the PHI node.
1738 // Add it to the expression used to rewrite the uses.
1739 // When this use is outside the loop, we earlier subtracted the
1740 // common base, and are adding it back here. Use the same expression
1741 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1742 if (!CommonExprs->isZero()) {
1743 if (L->contains(User.Inst->getParent()))
1744 RewriteExpr = SE->getAddExpr(RewriteExpr,
1745 SE->getUnknown(CommonBaseV));
1747 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1751 // Now that we know what we need to do, insert code before User for the
1752 // immediate and any loop-variant expressions.
1754 // Add BaseV to the PHI value if needed.
1755 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1757 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1758 Rewriter, L, this, *LI,
1761 // Mark old value we replaced as possibly dead, so that it is eliminated
1762 // if we just replaced the last use of that value.
1763 DeadInsts.push_back(User.OperandValToReplace);
1765 UsersToProcess.pop_back();
1768 // If there are any more users to process with the same base, process them
1769 // now. We sorted by base above, so we just have to check the last elt.
1770 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1771 // TODO: Next, find out which base index is the most common, pull it out.
1774 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1775 // different starting values, into different PHIs.
1778 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1779 /// set the IV user and stride information and return true, otherwise return
1781 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1782 const SCEV *const * &CondStride) {
1783 for (unsigned Stride = 0, e = IU->StrideOrder.size();
1784 Stride != e && !CondUse; ++Stride) {
1785 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
1786 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1787 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1789 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1790 E = SI->second->Users.end(); UI != E; ++UI)
1791 if (UI->getUser() == Cond) {
1792 // NOTE: we could handle setcc instructions with multiple uses here, but
1793 // InstCombine does it as well for simple uses, it's not clear that it
1794 // occurs enough in real life to handle.
1796 CondStride = &SI->first;
1804 // Constant strides come first which in turns are sorted by their absolute
1805 // values. If absolute values are the same, then positive strides comes first.
1807 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1808 struct StrideCompare {
1809 const ScalarEvolution *SE;
1810 explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
1812 bool operator()(const SCEV *const &LHS, const SCEV *const &RHS) {
1813 const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1814 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1816 int64_t LV = LHSC->getValue()->getSExtValue();
1817 int64_t RV = RHSC->getValue()->getSExtValue();
1818 uint64_t ALV = (LV < 0) ? -LV : LV;
1819 uint64_t ARV = (RV < 0) ? -RV : RV;
1827 // If it's the same value but different type, sort by bit width so
1828 // that we emit larger induction variables before smaller
1829 // ones, letting the smaller be re-written in terms of larger ones.
1830 return SE->getTypeSizeInBits(RHS->getType()) <
1831 SE->getTypeSizeInBits(LHS->getType());
1833 return LHSC && !RHSC;
1838 /// ChangeCompareStride - If a loop termination compare instruction is the
1839 /// only use of its stride, and the compaison is against a constant value,
1840 /// try eliminate the stride by moving the compare instruction to another
1841 /// stride and change its constant operand accordingly. e.g.
1847 /// if (v2 < 10) goto loop
1852 /// if (v1 < 30) goto loop
1853 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1854 IVStrideUse* &CondUse,
1855 const SCEV *const* &CondStride) {
1856 // If there's only one stride in the loop, there's nothing to do here.
1857 if (IU->StrideOrder.size() < 2)
1859 // If there are other users of the condition's stride, don't bother
1860 // trying to change the condition because the stride will still
1862 std::map<const SCEV *, IVUsersOfOneStride *>::iterator I =
1863 IU->IVUsesByStride.find(*CondStride);
1864 if (I == IU->IVUsesByStride.end() ||
1865 I->second->Users.size() != 1)
1867 // Only handle constant strides for now.
1868 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1869 if (!SC) return Cond;
1871 ICmpInst::Predicate Predicate = Cond->getPredicate();
1872 int64_t CmpSSInt = SC->getValue()->getSExtValue();
1873 unsigned BitWidth = SE->getTypeSizeInBits((*CondStride)->getType());
1874 uint64_t SignBit = 1ULL << (BitWidth-1);
1875 const Type *CmpTy = Cond->getOperand(0)->getType();
1876 const Type *NewCmpTy = NULL;
1877 unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
1878 unsigned NewTyBits = 0;
1879 const SCEV **NewStride = NULL;
1880 Value *NewCmpLHS = NULL;
1881 Value *NewCmpRHS = NULL;
1883 const SCEV *NewOffset = SE->getIntegerSCEV(0, CmpTy);
1885 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
1886 int64_t CmpVal = C->getValue().getSExtValue();
1888 // Check stride constant and the comparision constant signs to detect
1890 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
1893 // Look for a suitable stride / iv as replacement.
1894 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
1895 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
1896 IU->IVUsesByStride.find(IU->StrideOrder[i]);
1897 if (!isa<SCEVConstant>(SI->first))
1899 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1900 if (SSInt == CmpSSInt ||
1901 abs64(SSInt) < abs64(CmpSSInt) ||
1902 (SSInt % CmpSSInt) != 0)
1905 Scale = SSInt / CmpSSInt;
1906 int64_t NewCmpVal = CmpVal * Scale;
1907 APInt Mul = APInt(BitWidth*2, CmpVal, true);
1908 Mul = Mul * APInt(BitWidth*2, Scale, true);
1909 // Check for overflow.
1910 if (!Mul.isSignedIntN(BitWidth))
1912 // Check for overflow in the stride's type too.
1913 if (!Mul.isSignedIntN(SE->getTypeSizeInBits(SI->first->getType())))
1916 // Watch out for overflow.
1917 if (ICmpInst::isSigned(Predicate) &&
1918 (CmpVal & SignBit) != (NewCmpVal & SignBit))
1921 if (NewCmpVal == CmpVal)
1923 // Pick the best iv to use trying to avoid a cast.
1925 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
1926 E = SI->second->Users.end(); UI != E; ++UI) {
1927 Value *Op = UI->getOperandValToReplace();
1929 // If the IVStrideUse implies a cast, check for an actual cast which
1930 // can be used to find the original IV expression.
1931 if (SE->getEffectiveSCEVType(Op->getType()) !=
1932 SE->getEffectiveSCEVType(SI->first->getType())) {
1933 CastInst *CI = dyn_cast<CastInst>(Op);
1934 // If it's not a simple cast, it's complicated.
1937 // If it's a cast from a type other than the stride type,
1938 // it's complicated.
1939 if (CI->getOperand(0)->getType() != SI->first->getType())
1941 // Ok, we found the IV expression in the stride's type.
1942 Op = CI->getOperand(0);
1946 if (NewCmpLHS->getType() == CmpTy)
1952 NewCmpTy = NewCmpLHS->getType();
1953 NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
1954 const Type *NewCmpIntTy = IntegerType::get(Cond->getContext(), NewTyBits);
1955 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
1956 // Check if it is possible to rewrite it using
1957 // an iv / stride of a smaller integer type.
1958 unsigned Bits = NewTyBits;
1959 if (ICmpInst::isSigned(Predicate))
1961 uint64_t Mask = (1ULL << Bits) - 1;
1962 if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
1966 // Don't rewrite if use offset is non-constant and the new type is
1967 // of a different type.
1968 // FIXME: too conservative?
1969 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->getOffset()))
1972 bool AllUsesAreAddresses = true;
1973 bool AllUsesAreOutsideLoop = true;
1974 std::vector<BasedUser> UsersToProcess;
1975 const SCEV *CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
1976 AllUsesAreAddresses,
1977 AllUsesAreOutsideLoop,
1979 // Avoid rewriting the compare instruction with an iv of new stride
1980 // if it's likely the new stride uses will be rewritten using the
1981 // stride of the compare instruction.
1982 if (AllUsesAreAddresses &&
1983 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
1986 // Avoid rewriting the compare instruction with an iv which has
1987 // implicit extension or truncation built into it.
1988 // TODO: This is over-conservative.
1989 if (SE->getTypeSizeInBits(CondUse->getOffset()->getType()) != TyBits)
1992 // If scale is negative, use swapped predicate unless it's testing
1994 if (Scale < 0 && !Cond->isEquality())
1995 Predicate = ICmpInst::getSwappedPredicate(Predicate);
1997 NewStride = &IU->StrideOrder[i];
1998 if (!isa<PointerType>(NewCmpTy))
1999 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
2001 Constant *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
2002 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2004 NewOffset = TyBits == NewTyBits
2005 ? SE->getMulExpr(CondUse->getOffset(),
2006 SE->getConstant(CmpTy, Scale))
2007 : SE->getConstant(NewCmpIntTy,
2008 cast<SCEVConstant>(CondUse->getOffset())->getValue()
2009 ->getSExtValue()*Scale);
2014 // Forgo this transformation if it the increment happens to be
2015 // unfortunately positioned after the condition, and the condition
2016 // has multiple uses which prevent it from being moved immediately
2017 // before the branch. See
2018 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2019 // for an example of this situation.
2020 if (!Cond->hasOneUse()) {
2021 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2028 // Create a new compare instruction using new stride / iv.
2029 ICmpInst *OldCond = Cond;
2030 // Insert new compare instruction.
2031 Cond = new ICmpInst(OldCond, Predicate, NewCmpLHS, NewCmpRHS,
2032 L->getHeader()->getName() + ".termcond");
2034 // Remove the old compare instruction. The old indvar is probably dead too.
2035 DeadInsts.push_back(CondUse->getOperandValToReplace());
2036 OldCond->replaceAllUsesWith(Cond);
2037 OldCond->eraseFromParent();
2039 IU->IVUsesByStride[*NewStride]->addUser(NewOffset, Cond, NewCmpLHS);
2040 CondUse = &IU->IVUsesByStride[*NewStride]->Users.back();
2041 CondStride = NewStride;
2049 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
2050 /// a max computation.
2052 /// This is a narrow solution to a specific, but acute, problem. For loops
2058 /// } while (++i < n);
2060 /// the trip count isn't just 'n', because 'n' might not be positive. And
2061 /// unfortunately this can come up even for loops where the user didn't use
2062 /// a C do-while loop. For example, seemingly well-behaved top-test loops
2063 /// will commonly be lowered like this:
2069 /// } while (++i < n);
2072 /// and then it's possible for subsequent optimization to obscure the if
2073 /// test in such a way that indvars can't find it.
2075 /// When indvars can't find the if test in loops like this, it creates a
2076 /// max expression, which allows it to give the loop a canonical
2077 /// induction variable:
2080 /// max = n < 1 ? 1 : n;
2083 /// } while (++i != max);
2085 /// Canonical induction variables are necessary because the loop passes
2086 /// are designed around them. The most obvious example of this is the
2087 /// LoopInfo analysis, which doesn't remember trip count values. It
2088 /// expects to be able to rediscover the trip count each time it is
2089 /// needed, and it does this using a simple analyis that only succeeds if
2090 /// the loop has a canonical induction variable.
2092 /// However, when it comes time to generate code, the maximum operation
2093 /// can be quite costly, especially if it's inside of an outer loop.
2095 /// This function solves this problem by detecting this type of loop and
2096 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2097 /// the instructions for the maximum computation.
2099 ICmpInst *LoopStrengthReduce::OptimizeMax(Loop *L, ICmpInst *Cond,
2100 IVStrideUse* &CondUse) {
2101 // Check that the loop matches the pattern we're looking for.
2102 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2103 Cond->getPredicate() != CmpInst::ICMP_NE)
2106 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2107 if (!Sel || !Sel->hasOneUse()) return Cond;
2109 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2110 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2112 const SCEV *One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2114 // Add one to the backedge-taken count to get the trip count.
2115 const SCEV *IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2117 // Check for a max calculation that matches the pattern.
2118 if (!isa<SCEVSMaxExpr>(IterationCount) && !isa<SCEVUMaxExpr>(IterationCount))
2120 const SCEVNAryExpr *Max = cast<SCEVNAryExpr>(IterationCount);
2121 if (Max != SE->getSCEV(Sel)) return Cond;
2123 // To handle a max with more than two operands, this optimization would
2124 // require additional checking and setup.
2125 if (Max->getNumOperands() != 2)
2128 const SCEV *MaxLHS = Max->getOperand(0);
2129 const SCEV *MaxRHS = Max->getOperand(1);
2130 if (!MaxLHS || MaxLHS != One) return Cond;
2132 // Check the relevant induction variable for conformance to
2134 const SCEV *IV = SE->getSCEV(Cond->getOperand(0));
2135 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2136 if (!AR || !AR->isAffine() ||
2137 AR->getStart() != One ||
2138 AR->getStepRecurrence(*SE) != One)
2141 assert(AR->getLoop() == L &&
2142 "Loop condition operand is an addrec in a different loop!");
2144 // Check the right operand of the select, and remember it, as it will
2145 // be used in the new comparison instruction.
2147 if (SE->getSCEV(Sel->getOperand(1)) == MaxRHS)
2148 NewRHS = Sel->getOperand(1);
2149 else if (SE->getSCEV(Sel->getOperand(2)) == MaxRHS)
2150 NewRHS = Sel->getOperand(2);
2151 if (!NewRHS) return Cond;
2153 // Determine the new comparison opcode. It may be signed or unsigned,
2154 // and the original comparison may be either equality or inequality.
2155 CmpInst::Predicate Pred =
2156 isa<SCEVSMaxExpr>(Max) ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
2157 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2158 Pred = CmpInst::getInversePredicate(Pred);
2160 // Ok, everything looks ok to change the condition into an SLT or SGE and
2161 // delete the max calculation.
2163 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2165 // Delete the max calculation instructions.
2166 Cond->replaceAllUsesWith(NewCond);
2167 CondUse->setUser(NewCond);
2168 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2169 Cond->eraseFromParent();
2170 Sel->eraseFromParent();
2171 if (Cmp->use_empty())
2172 Cmp->eraseFromParent();
2176 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2177 /// inside the loop then try to eliminate the cast opeation.
2178 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2180 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2181 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2184 for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e;
2186 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
2187 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2188 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2189 if (!isa<SCEVConstant>(SI->first))
2192 for (ilist<IVStrideUse>::iterator UI = SI->second->Users.begin(),
2193 E = SI->second->Users.end(); UI != E; /* empty */) {
2194 ilist<IVStrideUse>::iterator CandidateUI = UI;
2196 Instruction *ShadowUse = CandidateUI->getUser();
2197 const Type *DestTy = NULL;
2199 /* If shadow use is a int->float cast then insert a second IV
2200 to eliminate this cast.
2202 for (unsigned i = 0; i < n; ++i)
2208 for (unsigned i = 0; i < n; ++i, ++d)
2211 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
2212 DestTy = UCast->getDestTy();
2213 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
2214 DestTy = SCast->getDestTy();
2215 if (!DestTy) continue;
2218 // If target does not support DestTy natively then do not apply
2219 // this transformation.
2220 EVT DVT = TLI->getValueType(DestTy);
2221 if (!TLI->isTypeLegal(DVT)) continue;
2224 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2226 if (PH->getNumIncomingValues() != 2) continue;
2228 const Type *SrcTy = PH->getType();
2229 int Mantissa = DestTy->getFPMantissaWidth();
2230 if (Mantissa == -1) continue;
2231 if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
2234 unsigned Entry, Latch;
2235 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2243 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2244 if (!Init) continue;
2245 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2247 BinaryOperator *Incr =
2248 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2249 if (!Incr) continue;
2250 if (Incr->getOpcode() != Instruction::Add
2251 && Incr->getOpcode() != Instruction::Sub)
2254 /* Initialize new IV, double d = 0.0 in above example. */
2255 ConstantInt *C = NULL;
2256 if (Incr->getOperand(0) == PH)
2257 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2258 else if (Incr->getOperand(1) == PH)
2259 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2265 // Ignore negative constants, as the code below doesn't handle them
2266 // correctly. TODO: Remove this restriction.
2267 if (!C->getValue().isStrictlyPositive()) continue;
2269 /* Add new PHINode. */
2270 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2272 /* create new increment. '++d' in above example. */
2273 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2274 BinaryOperator *NewIncr =
2275 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
2276 Instruction::FAdd : Instruction::FSub,
2277 NewPH, CFP, "IV.S.next.", Incr);
2279 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2280 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2282 /* Remove cast operation */
2283 ShadowUse->replaceAllUsesWith(NewPH);
2284 ShadowUse->eraseFromParent();
2291 /// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2292 /// uses in the loop, look to see if we can eliminate some, in favor of using
2293 /// common indvars for the different uses.
2294 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2295 // TODO: implement optzns here.
2297 OptimizeShadowIV(L);
2300 /// OptimizeLoopTermCond - Change loop terminating condition to use the
2301 /// postinc iv when possible.
2302 void LoopStrengthReduce::OptimizeLoopTermCond(Loop *L) {
2303 // Finally, get the terminating condition for the loop if possible. If we
2304 // can, we want to change it to use a post-incremented version of its
2305 // induction variable, to allow coalescing the live ranges for the IV into
2306 // one register value.
2307 BasicBlock *LatchBlock = L->getLoopLatch();
2308 BasicBlock *ExitingBlock = L->getExitingBlock();
2311 // Multiple exits, just look at the exit in the latch block if there is one.
2312 ExitingBlock = LatchBlock;
2313 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2316 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2319 // Search IVUsesByStride to find Cond's IVUse if there is one.
2320 IVStrideUse *CondUse = 0;
2321 const SCEV *const *CondStride = 0;
2322 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2323 if (!FindIVUserForCond(Cond, CondUse, CondStride))
2324 return; // setcc doesn't use the IV.
2326 if (ExitingBlock != LatchBlock) {
2327 if (!Cond->hasOneUse())
2328 // See below, we don't want the condition to be cloned.
2331 // If exiting block is the latch block, we know it's safe and profitable to
2332 // transform the icmp to use post-inc iv. Otherwise do so only if it would
2333 // not reuse another iv and its iv would be reused by other uses. We are
2334 // optimizing for the case where the icmp is the only use of the iv.
2335 IVUsersOfOneStride &StrideUses = *IU->IVUsesByStride[*CondStride];
2336 for (ilist<IVStrideUse>::iterator I = StrideUses.Users.begin(),
2337 E = StrideUses.Users.end(); I != E; ++I) {
2338 if (I->getUser() == Cond)
2340 if (!I->isUseOfPostIncrementedValue())
2344 // FIXME: This is expensive, and worse still ChangeCompareStride does a
2345 // similar check. Can we perform all the icmp related transformations after
2346 // StrengthReduceStridedIVUsers?
2347 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride)) {
2348 int64_t SInt = SC->getValue()->getSExtValue();
2349 for (unsigned NewStride = 0, ee = IU->StrideOrder.size(); NewStride != ee;
2351 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
2352 IU->IVUsesByStride.find(IU->StrideOrder[NewStride]);
2353 if (!isa<SCEVConstant>(SI->first) || SI->first == *CondStride)
2356 cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2358 return; // This can definitely be reused.
2359 if (unsigned(abs64(SSInt)) < SInt || (SSInt % SInt) != 0)
2361 int64_t Scale = SSInt / SInt;
2362 bool AllUsesAreAddresses = true;
2363 bool AllUsesAreOutsideLoop = true;
2364 std::vector<BasedUser> UsersToProcess;
2365 const SCEV *CommonExprs = CollectIVUsers(SI->first, *SI->second, L,
2366 AllUsesAreAddresses,
2367 AllUsesAreOutsideLoop,
2369 // Avoid rewriting the compare instruction with an iv of new stride
2370 // if it's likely the new stride uses will be rewritten using the
2371 // stride of the compare instruction.
2372 if (AllUsesAreAddresses &&
2373 ValidScale(!CommonExprs->isZero(), Scale, UsersToProcess))
2378 StrideNoReuse.insert(*CondStride);
2381 // If the trip count is computed in terms of a max (due to ScalarEvolution
2382 // being unable to find a sufficient guard, for example), change the loop
2383 // comparison to use SLT or ULT instead of NE.
2384 Cond = OptimizeMax(L, Cond, CondUse);
2386 // If possible, change stride and operands of the compare instruction to
2387 // eliminate one stride.
2388 if (ExitingBlock == LatchBlock)
2389 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2391 // It's possible for the setcc instruction to be anywhere in the loop, and
2392 // possible for it to have multiple users. If it is not immediately before
2393 // the latch block branch, move it.
2394 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2395 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2396 Cond->moveBefore(TermBr);
2398 // Otherwise, clone the terminating condition and insert into the loopend.
2399 Cond = cast<ICmpInst>(Cond->clone());
2400 Cond->setName(L->getHeader()->getName() + ".termcond");
2401 LatchBlock->getInstList().insert(TermBr, Cond);
2403 // Clone the IVUse, as the old use still exists!
2404 IU->IVUsesByStride[*CondStride]->addUser(CondUse->getOffset(), Cond,
2405 CondUse->getOperandValToReplace());
2406 CondUse = &IU->IVUsesByStride[*CondStride]->Users.back();
2410 // If we get to here, we know that we can transform the setcc instruction to
2411 // use the post-incremented version of the IV, allowing us to coalesce the
2412 // live ranges for the IV correctly.
2413 CondUse->setOffset(SE->getMinusSCEV(CondUse->getOffset(), *CondStride));
2414 CondUse->setIsUseOfPostIncrementedValue(true);
2420 /// OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for deciding
2421 /// when to exit the loop is used only for that purpose, try to rearrange things
2422 /// so it counts down to a test against zero.
2423 void LoopStrengthReduce::OptimizeLoopCountIV(Loop *L) {
2425 // If the number of times the loop is executed isn't computable, give up.
2426 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2427 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2430 // Get the terminating condition for the loop if possible (this isn't
2431 // necessarily in the latch, or a block that's a predecessor of the header).
2432 if (!L->getExitBlock())
2433 return; // More than one loop exit blocks.
2435 // Okay, there is one exit block. Try to find the condition that causes the
2436 // loop to be exited.
2437 BasicBlock *ExitingBlock = L->getExitingBlock();
2439 return; // More than one block exiting!
2441 // Okay, we've computed the exiting block. See what condition causes us to
2444 // FIXME: we should be able to handle switch instructions (with a single exit)
2445 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2446 if (TermBr == 0) return;
2447 assert(TermBr->isConditional() && "If unconditional, it can't be in loop!");
2448 if (!isa<ICmpInst>(TermBr->getCondition()))
2450 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2452 // Handle only tests for equality for the moment, and only stride 1.
2453 if (Cond->getPredicate() != CmpInst::ICMP_EQ)
2455 const SCEV *IV = SE->getSCEV(Cond->getOperand(0));
2456 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2457 const SCEV *One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2458 if (!AR || !AR->isAffine() || AR->getStepRecurrence(*SE) != One)
2460 // If the RHS of the comparison is defined inside the loop, the rewrite
2462 if (Instruction *CR = dyn_cast<Instruction>(Cond->getOperand(1)))
2463 if (L->contains(CR->getParent()))
2466 // Make sure the IV is only used for counting. Value may be preinc or
2467 // postinc; 2 uses in either case.
2468 if (!Cond->getOperand(0)->hasNUses(2))
2470 PHINode *phi = dyn_cast<PHINode>(Cond->getOperand(0));
2472 if (phi && phi->getParent()==L->getHeader()) {
2473 // value tested is preinc. Find the increment.
2474 // A CmpInst is not a BinaryOperator; we depend on this.
2475 Instruction::use_iterator UI = phi->use_begin();
2476 incr = dyn_cast<BinaryOperator>(UI);
2478 incr = dyn_cast<BinaryOperator>(++UI);
2479 // 1 use for postinc value, the phi. Unnecessarily conservative?
2480 if (!incr || !incr->hasOneUse() || incr->getOpcode()!=Instruction::Add)
2483 // Value tested is postinc. Find the phi node.
2484 incr = dyn_cast<BinaryOperator>(Cond->getOperand(0));
2485 if (!incr || incr->getOpcode()!=Instruction::Add)
2488 Instruction::use_iterator UI = Cond->getOperand(0)->use_begin();
2489 phi = dyn_cast<PHINode>(UI);
2491 phi = dyn_cast<PHINode>(++UI);
2492 // 1 use for preinc value, the increment.
2493 if (!phi || phi->getParent()!=L->getHeader() || !phi->hasOneUse())
2497 // Replace the increment with a decrement.
2498 BinaryOperator *decr =
2499 BinaryOperator::Create(Instruction::Sub, incr->getOperand(0),
2500 incr->getOperand(1), "tmp", incr);
2501 incr->replaceAllUsesWith(decr);
2502 incr->eraseFromParent();
2504 // Substitute endval-startval for the original startval, and 0 for the
2505 // original endval. Since we're only testing for equality this is OK even
2506 // if the computation wraps around.
2507 BasicBlock *Preheader = L->getLoopPreheader();
2508 Instruction *PreInsertPt = Preheader->getTerminator();
2509 int inBlock = L->contains(phi->getIncomingBlock(0)) ? 1 : 0;
2510 Value *startVal = phi->getIncomingValue(inBlock);
2511 Value *endVal = Cond->getOperand(1);
2512 // FIXME check for case where both are constant
2513 Constant* Zero = ConstantInt::get(Cond->getOperand(1)->getType(), 0);
2514 BinaryOperator *NewStartVal =
2515 BinaryOperator::Create(Instruction::Sub, endVal, startVal,
2516 "tmp", PreInsertPt);
2517 phi->setIncomingValue(inBlock, NewStartVal);
2518 Cond->setOperand(1, Zero);
2523 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2525 IU = &getAnalysis<IVUsers>();
2526 LI = &getAnalysis<LoopInfo>();
2527 DT = &getAnalysis<DominatorTree>();
2528 SE = &getAnalysis<ScalarEvolution>();
2531 // If LoopSimplify form is not available, stay out of trouble.
2532 if (!L->getLoopPreheader() || !L->getLoopLatch())
2535 if (!IU->IVUsesByStride.empty()) {
2536 DEBUG(errs() << "\nLSR on \"" << L->getHeader()->getParent()->getName()
2540 // Sort the StrideOrder so we process larger strides first.
2541 std::stable_sort(IU->StrideOrder.begin(), IU->StrideOrder.end(),
2544 // Optimize induction variables. Some indvar uses can be transformed to use
2545 // strides that will be needed for other purposes. A common example of this
2546 // is the exit test for the loop, which can often be rewritten to use the
2547 // computation of some other indvar to decide when to terminate the loop.
2550 // Change loop terminating condition to use the postinc iv when possible
2551 // and optimize loop terminating compare. FIXME: Move this after
2552 // StrengthReduceStridedIVUsers?
2553 OptimizeLoopTermCond(L);
2555 // FIXME: We can shrink overlarge IV's here. e.g. if the code has
2556 // computation in i64 values and the target doesn't support i64, demote
2557 // the computation to 32-bit if safe.
2559 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2560 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2561 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2562 // Need to be careful that IV's are all the same type. Only works for
2563 // intptr_t indvars.
2565 // IVsByStride keeps IVs for one particular loop.
2566 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2568 // Note: this processes each stride/type pair individually. All users
2569 // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2570 // Also, note that we iterate over IVUsesByStride indirectly by using
2571 // StrideOrder. This extra layer of indirection makes the ordering of
2572 // strides deterministic - not dependent on map order.
2573 for (unsigned Stride = 0, e = IU->StrideOrder.size();
2574 Stride != e; ++Stride) {
2575 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
2576 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
2577 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
2578 // FIXME: Generalize to non-affine IV's.
2579 if (!SI->first->isLoopInvariant(L))
2581 StrengthReduceStridedIVUsers(SI->first, *SI->second, L);
2585 // After all sharing is done, see if we can adjust the loop to test against
2586 // zero instead of counting up to a maximum. This is usually faster.
2587 OptimizeLoopCountIV(L);
2589 // We're done analyzing this loop; release all the state we built up for it.
2590 IVsByStride.clear();
2591 StrideNoReuse.clear();
2593 // Clean up after ourselves
2594 if (!DeadInsts.empty())
2595 DeleteTriviallyDeadInstructions();
2597 // At this point, it is worth checking to see if any recurrence PHIs are also
2598 // dead, so that we can remove them as well.
2599 DeleteDeadPHIs(L->getHeader());