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 pass performs a strength reduction on array references inside loops that
11 // have as one or more of their components the loop induction variable.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "loop-reduce"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Type.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/Analysis/ScalarEvolutionExpander.h"
26 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Target/TargetLowering.h"
41 STATISTIC(NumReduced , "Number of GEPs strength reduced");
42 STATISTIC(NumInserted, "Number of PHIs inserted");
43 STATISTIC(NumVariable, "Number of PHIs with variable strides");
44 STATISTIC(NumEliminated, "Number of strides eliminated");
45 STATISTIC(NumShadow, "Number of Shadow IVs optimized");
46 STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
48 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
56 /// IVStrideUse - Keep track of one use of a strided induction variable, where
57 /// the stride is stored externally. The Offset member keeps track of the
58 /// offset from the IV, User is the actual user of the operand, and
59 /// 'OperandValToReplace' is the operand of the User that is the use.
60 struct VISIBILITY_HIDDEN IVStrideUse {
63 Value *OperandValToReplace;
65 // isUseOfPostIncrementedValue - True if this should use the
66 // post-incremented version of this IV, not the preincremented version.
67 // This can only be set in special cases, such as the terminating setcc
68 // instruction for a loop or uses dominated by the loop.
69 bool isUseOfPostIncrementedValue;
71 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
72 : Offset(Offs), User(U), OperandValToReplace(O),
73 isUseOfPostIncrementedValue(false) {}
76 /// IVUsersOfOneStride - This structure keeps track of all instructions that
77 /// have an operand that is based on the trip count multiplied by some stride.
78 /// The stride for all of these users is common and kept external to this
80 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
81 /// Users - Keep track of all of the users of this stride as well as the
82 /// initial value and the operand that uses the IV.
83 std::vector<IVStrideUse> Users;
85 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
86 Users.push_back(IVStrideUse(Offset, User, Operand));
90 /// IVInfo - This structure keeps track of one IV expression inserted during
91 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
92 /// well as the PHI node and increment value created for rewrite.
93 struct VISIBILITY_HIDDEN IVExpr {
98 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
99 : Stride(stride), Base(base), PHI(phi) {}
102 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
103 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
104 struct VISIBILITY_HIDDEN IVsOfOneStride {
105 std::vector<IVExpr> IVs;
107 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
108 IVs.push_back(IVExpr(Stride, Base, PHI));
112 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
116 const TargetData *TD;
117 const Type *UIntPtrTy;
120 /// IVUsesByStride - Keep track of all uses of induction variables that we
121 /// are interested in. The key of the map is the stride of the access.
122 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
124 /// IVsByStride - Keep track of all IVs that have been inserted for a
125 /// particular stride.
126 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
128 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
129 /// We use this to iterate over the IVUsesByStride collection without being
130 /// dependent on random ordering of pointers in the process.
131 SmallVector<SCEVHandle, 16> StrideOrder;
133 /// DeadInsts - Keep track of instructions we may have made dead, so that
134 /// we can remove them after we are done working.
135 SmallVector<Instruction*, 16> DeadInsts;
137 /// TLI - Keep a pointer of a TargetLowering to consult for determining
138 /// transformation profitability.
139 const TargetLowering *TLI;
142 static char ID; // Pass ID, replacement for typeid
143 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
144 LoopPass(&ID), TLI(tli) {
147 bool runOnLoop(Loop *L, LPPassManager &LPM);
149 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
150 // We split critical edges, so we change the CFG. However, we do update
151 // many analyses if they are around.
152 AU.addPreservedID(LoopSimplifyID);
153 AU.addPreserved<LoopInfo>();
154 AU.addPreserved<DominanceFrontier>();
155 AU.addPreserved<DominatorTree>();
157 AU.addRequiredID(LoopSimplifyID);
158 AU.addRequired<LoopInfo>();
159 AU.addRequired<DominatorTree>();
160 AU.addRequired<TargetData>();
161 AU.addRequired<ScalarEvolution>();
162 AU.addPreserved<ScalarEvolution>();
166 bool AddUsersIfInteresting(Instruction *I, Loop *L,
167 SmallPtrSet<Instruction*,16> &Processed);
168 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
169 IVStrideUse* &CondUse,
170 const SCEVHandle* &CondStride);
171 void OptimizeIndvars(Loop *L);
173 /// OptimizeShadowIV - If IV is used in a int-to-float cast
174 /// inside the loop then try to eliminate the cast opeation.
175 void OptimizeShadowIV(Loop *L);
177 /// OptimizeSMax - Rewrite the loop's terminating condition
178 /// if it uses an smax computation.
179 ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
180 IVStrideUse* &CondUse);
182 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
183 const SCEVHandle *&CondStride);
184 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
185 SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
186 IVExpr&, const Type*,
187 const std::vector<BasedUser>& UsersToProcess);
188 bool ValidStride(bool, int64_t,
189 const std::vector<BasedUser>& UsersToProcess);
190 SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
191 IVUsersOfOneStride &Uses,
193 bool &AllUsesAreAddresses,
194 bool &AllUsesAreOutsideLoop,
195 std::vector<BasedUser> &UsersToProcess);
196 bool ShouldUseFullStrengthReductionMode(
197 const std::vector<BasedUser> &UsersToProcess,
199 bool AllUsesAreAddresses,
201 void PrepareToStrengthReduceFully(
202 std::vector<BasedUser> &UsersToProcess,
204 SCEVHandle CommonExprs,
206 SCEVExpander &PreheaderRewriter);
207 void PrepareToStrengthReduceFromSmallerStride(
208 std::vector<BasedUser> &UsersToProcess,
210 const IVExpr &ReuseIV,
211 Instruction *PreInsertPt);
212 void PrepareToStrengthReduceWithNewPhi(
213 std::vector<BasedUser> &UsersToProcess,
215 SCEVHandle CommonExprs,
218 SCEVExpander &PreheaderRewriter);
219 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
220 IVUsersOfOneStride &Uses,
222 void DeleteTriviallyDeadInstructions();
226 char LoopStrengthReduce::ID = 0;
227 static RegisterPass<LoopStrengthReduce>
228 X("loop-reduce", "Loop Strength Reduction");
230 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
231 return new LoopStrengthReduce(TLI);
234 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
235 /// specified set are trivially dead, delete them and see if this makes any of
236 /// their operands subsequently dead.
237 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
238 if (DeadInsts.empty()) return;
240 // Sort the deadinsts list so that we can trivially eliminate duplicates as we
241 // go. The code below never adds a non-dead instruction to the worklist, but
242 // callers may not be so careful.
243 array_pod_sort(DeadInsts.begin(), DeadInsts.end());
245 // Drop duplicate instructions and those with uses.
246 for (unsigned i = 0, e = DeadInsts.size()-1; i < e; ++i) {
247 Instruction *I = DeadInsts[i];
248 if (!I->use_empty()) DeadInsts[i] = 0;
249 while (i != e && DeadInsts[i+1] == I)
253 while (!DeadInsts.empty()) {
254 Instruction *I = DeadInsts.back();
255 DeadInsts.pop_back();
257 if (I == 0 || !isInstructionTriviallyDead(I))
260 SE->deleteValueFromRecords(I);
262 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
263 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
266 DeadInsts.push_back(U);
270 I->eraseFromParent();
275 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
276 /// subexpression that is an AddRec from a loop other than L. An outer loop
277 /// of L is OK, but not an inner loop nor a disjoint loop.
278 static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
279 // This is very common, put it first.
280 if (isa<SCEVConstant>(S))
282 if (SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
283 for (unsigned int i=0; i< AE->getNumOperands(); i++)
284 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
288 if (SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
289 if (const Loop *newLoop = AE->getLoop()) {
292 // if newLoop is an outer loop of L, this is OK.
293 if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
298 if (SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
299 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
300 containsAddRecFromDifferentLoop(DE->getRHS(), L);
302 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
303 // need this when it is.
304 if (SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
305 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
306 containsAddRecFromDifferentLoop(DE->getRHS(), L);
308 if (SCEVTruncateExpr *TE = dyn_cast<SCEVTruncateExpr>(S))
309 return containsAddRecFromDifferentLoop(TE->getOperand(), L);
310 if (SCEVZeroExtendExpr *ZE = dyn_cast<SCEVZeroExtendExpr>(S))
311 return containsAddRecFromDifferentLoop(ZE->getOperand(), L);
312 if (SCEVSignExtendExpr *SE = dyn_cast<SCEVSignExtendExpr>(S))
313 return containsAddRecFromDifferentLoop(SE->getOperand(), L);
317 /// getSCEVStartAndStride - Compute the start and stride of this expression,
318 /// returning false if the expression is not a start/stride pair, or true if it
319 /// is. The stride must be a loop invariant expression, but the start may be
320 /// a mix of loop invariant and loop variant expressions. The start cannot,
321 /// however, contain an AddRec from a different loop, unless that loop is an
322 /// outer loop of the current loop.
323 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
324 SCEVHandle &Start, SCEVHandle &Stride,
325 ScalarEvolution *SE, DominatorTree *DT) {
326 SCEVHandle TheAddRec = Start; // Initialize to zero.
328 // If the outer level is an AddExpr, the operands are all start values except
329 // for a nested AddRecExpr.
330 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
331 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
332 if (SCEVAddRecExpr *AddRec =
333 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
334 if (AddRec->getLoop() == L)
335 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
337 return false; // Nested IV of some sort?
339 Start = SE->getAddExpr(Start, AE->getOperand(i));
342 } else if (isa<SCEVAddRecExpr>(SH)) {
345 return false; // not analyzable.
348 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
349 if (!AddRec || AddRec->getLoop() != L) return false;
351 // FIXME: Generalize to non-affine IV's.
352 if (!AddRec->isAffine()) return false;
354 // If Start contains an SCEVAddRecExpr from a different loop, other than an
355 // outer loop of the current loop, reject it. SCEV has no concept of
356 // operating on more than one loop at a time so don't confuse it with such
358 if (containsAddRecFromDifferentLoop(AddRec->getOperand(0), L))
361 Start = SE->getAddExpr(Start, AddRec->getOperand(0));
363 if (!isa<SCEVConstant>(AddRec->getOperand(1))) {
364 // If stride is an instruction, make sure it dominates the loop preheader.
365 // Otherwise we could end up with a use before def situation.
366 BasicBlock *Preheader = L->getLoopPreheader();
367 if (!AddRec->getOperand(1)->dominates(Preheader, DT))
370 DOUT << "[" << L->getHeader()->getName()
371 << "] Variable stride: " << *AddRec << "\n";
374 Stride = AddRec->getOperand(1);
378 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
379 /// and now we need to decide whether the user should use the preinc or post-inc
380 /// value. If this user should use the post-inc version of the IV, return true.
382 /// Choosing wrong here can break dominance properties (if we choose to use the
383 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
384 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
385 /// should use the post-inc value).
386 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
387 Loop *L, DominatorTree *DT, Pass *P,
388 SmallVectorImpl<Instruction*> &DeadInsts){
389 // If the user is in the loop, use the preinc value.
390 if (L->contains(User->getParent())) return false;
392 BasicBlock *LatchBlock = L->getLoopLatch();
394 // Ok, the user is outside of the loop. If it is dominated by the latch
395 // block, use the post-inc value.
396 if (DT->dominates(LatchBlock, User->getParent()))
399 // There is one case we have to be careful of: PHI nodes. These little guys
400 // can live in blocks that do not dominate the latch block, but (since their
401 // uses occur in the predecessor block, not the block the PHI lives in) should
402 // still use the post-inc value. Check for this case now.
403 PHINode *PN = dyn_cast<PHINode>(User);
404 if (!PN) return false; // not a phi, not dominated by latch block.
406 // Look at all of the uses of IV by the PHI node. If any use corresponds to
407 // a block that is not dominated by the latch block, give up and use the
408 // preincremented value.
409 unsigned NumUses = 0;
410 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
411 if (PN->getIncomingValue(i) == IV) {
413 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
417 // Okay, all uses of IV by PN are in predecessor blocks that really are
418 // dominated by the latch block. Split the critical edges and use the
419 // post-incremented value.
420 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
421 if (PN->getIncomingValue(i) == IV) {
422 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P, false);
423 // Splitting the critical edge can reduce the number of entries in this
425 e = PN->getNumIncomingValues();
426 if (--NumUses == 0) break;
429 // PHI node might have become a constant value after SplitCriticalEdge.
430 DeadInsts.push_back(User);
435 /// isAddressUse - Returns true if the specified instruction is using the
436 /// specified value as an address.
437 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
438 bool isAddress = isa<LoadInst>(Inst);
439 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
440 if (SI->getOperand(1) == OperandVal)
442 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
443 // Addressing modes can also be folded into prefetches and a variety
445 switch (II->getIntrinsicID()) {
447 case Intrinsic::prefetch:
448 case Intrinsic::x86_sse2_loadu_dq:
449 case Intrinsic::x86_sse2_loadu_pd:
450 case Intrinsic::x86_sse_loadu_ps:
451 case Intrinsic::x86_sse_storeu_ps:
452 case Intrinsic::x86_sse2_storeu_pd:
453 case Intrinsic::x86_sse2_storeu_dq:
454 case Intrinsic::x86_sse2_storel_dq:
455 if (II->getOperand(1) == OperandVal)
463 /// getAccessType - Return the type of the memory being accessed.
464 static const Type *getAccessType(const Instruction *Inst) {
465 const Type *UseTy = Inst->getType();
466 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
467 UseTy = SI->getOperand(0)->getType();
468 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
469 // Addressing modes can also be folded into prefetches and a variety
471 switch (II->getIntrinsicID()) {
473 case Intrinsic::x86_sse_storeu_ps:
474 case Intrinsic::x86_sse2_storeu_pd:
475 case Intrinsic::x86_sse2_storeu_dq:
476 case Intrinsic::x86_sse2_storel_dq:
477 UseTy = II->getOperand(1)->getType();
484 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
485 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
486 /// return true. Otherwise, return false.
487 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
488 SmallPtrSet<Instruction*,16> &Processed) {
489 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
490 return false; // Void and FP expressions cannot be reduced.
492 // LSR is not APInt clean, do not touch integers bigger than 64-bits.
493 if (I->getType()->isInteger() &&
494 I->getType()->getPrimitiveSizeInBits() > 64)
497 if (!Processed.insert(I))
498 return true; // Instruction already handled.
500 // Get the symbolic expression for this instruction.
501 SCEVHandle ISE = SE->getSCEV(I);
502 if (isa<SCEVCouldNotCompute>(ISE)) return false;
504 // Get the start and stride for this expression.
505 SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
506 SCEVHandle Stride = Start;
507 if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE, DT))
508 return false; // Non-reducible symbolic expression, bail out.
510 std::vector<Instruction *> IUsers;
511 // Collect all I uses now because IVUseShouldUsePostIncValue may
512 // invalidate use_iterator.
513 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
514 IUsers.push_back(cast<Instruction>(*UI));
516 for (unsigned iused_index = 0, iused_size = IUsers.size();
517 iused_index != iused_size; ++iused_index) {
519 Instruction *User = IUsers[iused_index];
521 // Do not infinitely recurse on PHI nodes.
522 if (isa<PHINode>(User) && Processed.count(User))
525 // Descend recursively, but not into PHI nodes outside the current loop.
526 // It's important to see the entire expression outside the loop to get
527 // choices that depend on addressing mode use right, although we won't
528 // consider references ouside the loop in all cases.
529 // If User is already in Processed, we don't want to recurse into it again,
530 // but do want to record a second reference in the same instruction.
531 bool AddUserToIVUsers = false;
532 if (LI->getLoopFor(User->getParent()) != L) {
533 if (isa<PHINode>(User) || Processed.count(User) ||
534 !AddUsersIfInteresting(User, L, Processed)) {
535 DOUT << "FOUND USER in other loop: " << *User
536 << " OF SCEV: " << *ISE << "\n";
537 AddUserToIVUsers = true;
539 } else if (Processed.count(User) ||
540 !AddUsersIfInteresting(User, L, Processed)) {
541 DOUT << "FOUND USER: " << *User
542 << " OF SCEV: " << *ISE << "\n";
543 AddUserToIVUsers = true;
546 if (AddUserToIVUsers) {
547 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
548 if (StrideUses.Users.empty()) // First occurrence of this stride?
549 StrideOrder.push_back(Stride);
551 // Okay, we found a user that we cannot reduce. Analyze the instruction
552 // and decide what to do with it. If we are a use inside of the loop, use
553 // the value before incrementation, otherwise use it after incrementation.
554 if (IVUseShouldUsePostIncValue(User, I, L, DT, this, DeadInsts)) {
555 // The value used will be incremented by the stride more than we are
556 // expecting, so subtract this off.
557 SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
558 StrideUses.addUser(NewStart, User, I);
559 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
560 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
562 StrideUses.addUser(Start, User, I);
570 /// BasedUser - For a particular base value, keep information about how we've
571 /// partitioned the expression so far.
573 /// SE - The current ScalarEvolution object.
576 /// Base - The Base value for the PHI node that needs to be inserted for
577 /// this use. As the use is processed, information gets moved from this
578 /// field to the Imm field (below). BasedUser values are sorted by this
582 /// Inst - The instruction using the induction variable.
585 /// OperandValToReplace - The operand value of Inst to replace with the
587 Value *OperandValToReplace;
589 /// Imm - The immediate value that should be added to the base immediately
590 /// before Inst, because it will be folded into the imm field of the
591 /// instruction. This is also sometimes used for loop-variant values that
592 /// must be added inside the loop.
595 /// Phi - The induction variable that performs the striding that
596 /// should be used for this user.
599 // isUseOfPostIncrementedValue - True if this should use the
600 // post-incremented version of this IV, not the preincremented version.
601 // This can only be set in special cases, such as the terminating setcc
602 // instruction for a loop and uses outside the loop that are dominated by
604 bool isUseOfPostIncrementedValue;
606 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
607 : SE(se), Base(IVSU.Offset), Inst(IVSU.User),
608 OperandValToReplace(IVSU.OperandValToReplace),
609 Imm(SE->getIntegerSCEV(0, Base->getType())),
610 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
612 // Once we rewrite the code to insert the new IVs we want, update the
613 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
615 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
616 Instruction *InsertPt,
617 SCEVExpander &Rewriter, Loop *L, Pass *P,
618 SmallVectorImpl<Instruction*> &DeadInsts);
620 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
622 SCEVExpander &Rewriter,
623 Instruction *IP, Loop *L);
628 void BasedUser::dump() const {
629 cerr << " Base=" << *Base;
630 cerr << " Imm=" << *Imm;
631 cerr << " Inst: " << *Inst;
634 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
636 SCEVExpander &Rewriter,
637 Instruction *IP, Loop *L) {
638 // Figure out where we *really* want to insert this code. In particular, if
639 // the user is inside of a loop that is nested inside of L, we really don't
640 // want to insert this expression before the user, we'd rather pull it out as
641 // many loops as possible.
642 LoopInfo &LI = Rewriter.getLoopInfo();
643 Instruction *BaseInsertPt = IP;
645 // Figure out the most-nested loop that IP is in.
646 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
648 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
649 // the preheader of the outer-most loop where NewBase is not loop invariant.
650 if (L->contains(IP->getParent()))
651 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
652 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
653 InsertLoop = InsertLoop->getParentLoop();
656 Value *Base = Rewriter.expandCodeFor(NewBase, Ty, BaseInsertPt);
658 // If there is no immediate value, skip the next part.
662 // If we are inserting the base and imm values in the same block, make sure to
663 // adjust the IP position if insertion reused a result.
664 if (IP == BaseInsertPt)
665 IP = Rewriter.getInsertionPoint();
667 // Always emit the immediate (if non-zero) into the same block as the user.
668 SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
669 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
673 // Once we rewrite the code to insert the new IVs we want, update the
674 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
675 // to it. NewBasePt is the last instruction which contributes to the
676 // value of NewBase in the case that it's a diffferent instruction from
677 // the PHI that NewBase is computed from, or null otherwise.
679 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
680 Instruction *NewBasePt,
681 SCEVExpander &Rewriter, Loop *L, Pass *P,
682 SmallVectorImpl<Instruction*> &DeadInsts){
683 if (!isa<PHINode>(Inst)) {
684 // By default, insert code at the user instruction.
685 BasicBlock::iterator InsertPt = Inst;
687 // However, if the Operand is itself an instruction, the (potentially
688 // complex) inserted code may be shared by many users. Because of this, we
689 // want to emit code for the computation of the operand right before its old
690 // computation. This is usually safe, because we obviously used to use the
691 // computation when it was computed in its current block. However, in some
692 // cases (e.g. use of a post-incremented induction variable) the NewBase
693 // value will be pinned to live somewhere after the original computation.
694 // In this case, we have to back off.
696 // If this is a use outside the loop (which means after, since it is based
697 // on a loop indvar) we use the post-incremented value, so that we don't
698 // artificially make the preinc value live out the bottom of the loop.
699 if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
700 if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
701 InsertPt = NewBasePt;
703 } else if (Instruction *OpInst
704 = dyn_cast<Instruction>(OperandValToReplace)) {
706 while (isa<PHINode>(InsertPt)) ++InsertPt;
709 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
710 OperandValToReplace->getType(),
711 Rewriter, InsertPt, L);
712 // Replace the use of the operand Value with the new Phi we just created.
713 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
715 DOUT << " Replacing with ";
716 DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
717 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
721 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
722 // expression into each operand block that uses it. Note that PHI nodes can
723 // have multiple entries for the same predecessor. We use a map to make sure
724 // that a PHI node only has a single Value* for each predecessor (which also
725 // prevents us from inserting duplicate code in some blocks).
726 DenseMap<BasicBlock*, Value*> InsertedCode;
727 PHINode *PN = cast<PHINode>(Inst);
728 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
729 if (PN->getIncomingValue(i) == OperandValToReplace) {
730 // If the original expression is outside the loop, put the replacement
731 // code in the same place as the original expression,
732 // which need not be an immediate predecessor of this PHI. This way we
733 // need only one copy of it even if it is referenced multiple times in
734 // the PHI. We don't do this when the original expression is inside the
735 // loop because multiple copies sometimes do useful sinking of code in
737 Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
738 if (L->contains(OldLoc->getParent())) {
739 // If this is a critical edge, split the edge so that we do not insert
740 // the code on all predecessor/successor paths. We do this unless this
741 // is the canonical backedge for this loop, as this can make some
742 // inserted code be in an illegal position.
743 BasicBlock *PHIPred = PN->getIncomingBlock(i);
744 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
745 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
747 // First step, split the critical edge.
748 SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
750 // Next step: move the basic block. In particular, if the PHI node
751 // is outside of the loop, and PredTI is in the loop, we want to
752 // move the block to be immediately before the PHI block, not
753 // immediately after PredTI.
754 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
755 BasicBlock *NewBB = PN->getIncomingBlock(i);
756 NewBB->moveBefore(PN->getParent());
759 // Splitting the edge can reduce the number of PHI entries we have.
760 e = PN->getNumIncomingValues();
763 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
765 // Insert the code into the end of the predecessor block.
766 Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
767 PN->getIncomingBlock(i)->getTerminator() :
768 OldLoc->getParent()->getTerminator();
769 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
770 Rewriter, InsertPt, L);
772 DOUT << " Changing PHI use to ";
773 DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
774 DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
777 // Replace the use of the operand Value with the new Phi we just created.
778 PN->setIncomingValue(i, Code);
783 // PHI node might have become a constant value after SplitCriticalEdge.
784 DeadInsts.push_back(Inst);
788 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
789 /// mode, and does not need to be put in a register first.
790 static bool fitsInAddressMode(const SCEVHandle &V, const Type *UseTy,
791 const TargetLowering *TLI, bool HasBaseReg) {
792 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
793 int64_t VC = SC->getValue()->getSExtValue();
795 TargetLowering::AddrMode AM;
797 AM.HasBaseReg = HasBaseReg;
798 return TLI->isLegalAddressingMode(AM, UseTy);
800 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
801 return (VC > -(1 << 16) && VC < (1 << 16)-1);
805 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
806 if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
807 TargetLowering::AddrMode AM;
809 AM.HasBaseReg = HasBaseReg;
810 return TLI->isLegalAddressingMode(AM, UseTy);
816 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
817 /// loop varying to the Imm operand.
818 static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
819 Loop *L, ScalarEvolution *SE) {
820 if (Val->isLoopInvariant(L)) return; // Nothing to do.
822 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
823 std::vector<SCEVHandle> NewOps;
824 NewOps.reserve(SAE->getNumOperands());
826 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
827 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
828 // If this is a loop-variant expression, it must stay in the immediate
829 // field of the expression.
830 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
832 NewOps.push_back(SAE->getOperand(i));
836 Val = SE->getIntegerSCEV(0, Val->getType());
838 Val = SE->getAddExpr(NewOps);
839 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
840 // Try to pull immediates out of the start value of nested addrec's.
841 SCEVHandle Start = SARE->getStart();
842 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
844 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
846 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
848 // Otherwise, all of Val is variant, move the whole thing over.
849 Imm = SE->getAddExpr(Imm, Val);
850 Val = SE->getIntegerSCEV(0, Val->getType());
855 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
856 /// that can fit into the immediate field of instructions in the target.
857 /// Accumulate these immediate values into the Imm value.
858 static void MoveImmediateValues(const TargetLowering *TLI,
860 SCEVHandle &Val, SCEVHandle &Imm,
861 bool isAddress, Loop *L,
862 ScalarEvolution *SE) {
863 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
864 std::vector<SCEVHandle> NewOps;
865 NewOps.reserve(SAE->getNumOperands());
867 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
868 SCEVHandle NewOp = SAE->getOperand(i);
869 MoveImmediateValues(TLI, UseTy, NewOp, Imm, isAddress, L, SE);
871 if (!NewOp->isLoopInvariant(L)) {
872 // If this is a loop-variant expression, it must stay in the immediate
873 // field of the expression.
874 Imm = SE->getAddExpr(Imm, NewOp);
876 NewOps.push_back(NewOp);
881 Val = SE->getIntegerSCEV(0, Val->getType());
883 Val = SE->getAddExpr(NewOps);
885 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
886 // Try to pull immediates out of the start value of nested addrec's.
887 SCEVHandle Start = SARE->getStart();
888 MoveImmediateValues(TLI, UseTy, Start, Imm, isAddress, L, SE);
890 if (Start != SARE->getStart()) {
891 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
893 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
896 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
897 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
898 if (isAddress && fitsInAddressMode(SME->getOperand(0), UseTy, TLI, false) &&
899 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
901 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
902 SCEVHandle NewOp = SME->getOperand(1);
903 MoveImmediateValues(TLI, UseTy, NewOp, SubImm, isAddress, L, SE);
905 // If we extracted something out of the subexpressions, see if we can
907 if (NewOp != SME->getOperand(1)) {
908 // Scale SubImm up by "8". If the result is a target constant, we are
910 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
911 if (fitsInAddressMode(SubImm, UseTy, TLI, false)) {
912 // Accumulate the immediate.
913 Imm = SE->getAddExpr(Imm, SubImm);
915 // Update what is left of 'Val'.
916 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
923 // Loop-variant expressions must stay in the immediate field of the
925 if ((isAddress && fitsInAddressMode(Val, UseTy, TLI, false)) ||
926 !Val->isLoopInvariant(L)) {
927 Imm = SE->getAddExpr(Imm, Val);
928 Val = SE->getIntegerSCEV(0, Val->getType());
932 // Otherwise, no immediates to move.
935 static void MoveImmediateValues(const TargetLowering *TLI,
937 SCEVHandle &Val, SCEVHandle &Imm,
938 bool isAddress, Loop *L,
939 ScalarEvolution *SE) {
940 const Type *UseTy = getAccessType(User);
941 MoveImmediateValues(TLI, UseTy, Val, Imm, isAddress, L, SE);
944 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
945 /// added together. This is used to reassociate common addition subexprs
946 /// together for maximal sharing when rewriting bases.
947 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
949 ScalarEvolution *SE) {
950 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
951 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
952 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
953 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
954 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
955 if (SARE->getOperand(0) == Zero) {
956 SubExprs.push_back(Expr);
958 // Compute the addrec with zero as its base.
959 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
960 Ops[0] = Zero; // Start with zero base.
961 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
964 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
966 } else if (!Expr->isZero()) {
968 SubExprs.push_back(Expr);
972 // This is logically local to the following function, but C++ says we have
973 // to make it file scope.
974 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
976 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
977 /// the Uses, removing any common subexpressions, except that if all such
978 /// subexpressions can be folded into an addressing mode for all uses inside
979 /// the loop (this case is referred to as "free" in comments herein) we do
980 /// not remove anything. This looks for things like (a+b+c) and
981 /// (a+c+d) and computes the common (a+c) subexpression. The common expression
982 /// is *removed* from the Bases and returned.
984 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
985 ScalarEvolution *SE, Loop *L,
986 const TargetLowering *TLI) {
987 unsigned NumUses = Uses.size();
989 // Only one use? This is a very common case, so we handle it specially and
991 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
992 SCEVHandle Result = Zero;
993 SCEVHandle FreeResult = Zero;
995 // If the use is inside the loop, use its base, regardless of what it is:
996 // it is clearly shared across all the IV's. If the use is outside the loop
997 // (which means after it) we don't want to factor anything *into* the loop,
998 // so just use 0 as the base.
999 if (L->contains(Uses[0].Inst->getParent()))
1000 std::swap(Result, Uses[0].Base);
1004 // To find common subexpressions, count how many of Uses use each expression.
1005 // If any subexpressions are used Uses.size() times, they are common.
1006 // Also track whether all uses of each expression can be moved into an
1007 // an addressing mode "for free"; such expressions are left within the loop.
1008 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
1009 std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
1011 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
1012 // order we see them.
1013 std::vector<SCEVHandle> UniqueSubExprs;
1015 std::vector<SCEVHandle> SubExprs;
1016 unsigned NumUsesInsideLoop = 0;
1017 for (unsigned i = 0; i != NumUses; ++i) {
1018 // If the user is outside the loop, just ignore it for base computation.
1019 // Since the user is outside the loop, it must be *after* the loop (if it
1020 // were before, it could not be based on the loop IV). We don't want users
1021 // after the loop to affect base computation of values *inside* the loop,
1022 // because we can always add their offsets to the result IV after the loop
1023 // is done, ensuring we get good code inside the loop.
1024 if (!L->contains(Uses[i].Inst->getParent()))
1026 NumUsesInsideLoop++;
1028 // If the base is zero (which is common), return zero now, there are no
1029 // CSEs we can find.
1030 if (Uses[i].Base == Zero) return Zero;
1032 // If this use is as an address we may be able to put CSEs in the addressing
1033 // mode rather than hoisting them.
1034 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
1035 // We may need the UseTy below, but only when isAddrUse, so compute it
1036 // only in that case.
1037 const Type *UseTy = 0;
1039 UseTy = getAccessType(Uses[i].Inst);
1041 // Split the expression into subexprs.
1042 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1043 // Add one to SubExpressionUseData.Count for each subexpr present, and
1044 // if the subexpr is not a valid immediate within an addressing mode use,
1045 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
1046 // hoist these out of the loop (if they are common to all uses).
1047 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1048 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
1049 UniqueSubExprs.push_back(SubExprs[j]);
1050 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], UseTy, TLI, false))
1051 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
1056 // Now that we know how many times each is used, build Result. Iterate over
1057 // UniqueSubexprs so that we have a stable ordering.
1058 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
1059 std::map<SCEVHandle, SubExprUseData>::iterator I =
1060 SubExpressionUseData.find(UniqueSubExprs[i]);
1061 assert(I != SubExpressionUseData.end() && "Entry not found?");
1062 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
1063 if (I->second.notAllUsesAreFree)
1064 Result = SE->getAddExpr(Result, I->first);
1066 FreeResult = SE->getAddExpr(FreeResult, I->first);
1068 // Remove non-cse's from SubExpressionUseData.
1069 SubExpressionUseData.erase(I);
1072 if (FreeResult != Zero) {
1073 // We have some subexpressions that can be subsumed into addressing
1074 // modes in every use inside the loop. However, it's possible that
1075 // there are so many of them that the combined FreeResult cannot
1076 // be subsumed, or that the target cannot handle both a FreeResult
1077 // and a Result in the same instruction (for example because it would
1078 // require too many registers). Check this.
1079 for (unsigned i=0; i<NumUses; ++i) {
1080 if (!L->contains(Uses[i].Inst->getParent()))
1082 // We know this is an addressing mode use; if there are any uses that
1083 // are not, FreeResult would be Zero.
1084 const Type *UseTy = getAccessType(Uses[i].Inst);
1085 if (!fitsInAddressMode(FreeResult, UseTy, TLI, Result!=Zero)) {
1086 // FIXME: could split up FreeResult into pieces here, some hoisted
1087 // and some not. There is no obvious advantage to this.
1088 Result = SE->getAddExpr(Result, FreeResult);
1095 // If we found no CSE's, return now.
1096 if (Result == Zero) return Result;
1098 // If we still have a FreeResult, remove its subexpressions from
1099 // SubExpressionUseData. This means they will remain in the use Bases.
1100 if (FreeResult != Zero) {
1101 SeparateSubExprs(SubExprs, FreeResult, SE);
1102 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1103 std::map<SCEVHandle, SubExprUseData>::iterator I =
1104 SubExpressionUseData.find(SubExprs[j]);
1105 SubExpressionUseData.erase(I);
1110 // Otherwise, remove all of the CSE's we found from each of the base values.
1111 for (unsigned i = 0; i != NumUses; ++i) {
1112 // Uses outside the loop don't necessarily include the common base, but
1113 // the final IV value coming into those uses does. Instead of trying to
1114 // remove the pieces of the common base, which might not be there,
1115 // subtract off the base to compensate for this.
1116 if (!L->contains(Uses[i].Inst->getParent())) {
1117 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
1121 // Split the expression into subexprs.
1122 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1124 // Remove any common subexpressions.
1125 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
1126 if (SubExpressionUseData.count(SubExprs[j])) {
1127 SubExprs.erase(SubExprs.begin()+j);
1131 // Finally, add the non-shared expressions together.
1132 if (SubExprs.empty())
1133 Uses[i].Base = Zero;
1135 Uses[i].Base = SE->getAddExpr(SubExprs);
1142 /// ValidStride - Check whether the given Scale is valid for all loads and
1143 /// stores in UsersToProcess.
1145 bool LoopStrengthReduce::ValidStride(bool HasBaseReg,
1147 const std::vector<BasedUser>& UsersToProcess) {
1151 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
1152 // If this is a load or other access, pass the type of the access in.
1153 const Type *AccessTy = Type::VoidTy;
1154 if (isAddressUse(UsersToProcess[i].Inst,
1155 UsersToProcess[i].OperandValToReplace))
1156 AccessTy = getAccessType(UsersToProcess[i].Inst);
1157 else if (isa<PHINode>(UsersToProcess[i].Inst))
1160 TargetLowering::AddrMode AM;
1161 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
1162 AM.BaseOffs = SC->getValue()->getSExtValue();
1163 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
1166 // If load[imm+r*scale] is illegal, bail out.
1167 if (!TLI->isLegalAddressingMode(AM, AccessTy))
1173 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
1175 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
1179 if (Ty1->canLosslesslyBitCastTo(Ty2))
1181 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
1183 if (isa<PointerType>(Ty2) && Ty1->canLosslesslyBitCastTo(UIntPtrTy))
1185 if (isa<PointerType>(Ty1) && Ty2->canLosslesslyBitCastTo(UIntPtrTy))
1190 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
1191 /// of a previous stride and it is a legal value for the target addressing
1192 /// mode scale component and optional base reg. This allows the users of
1193 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
1194 /// reuse is possible. Factors can be negative on same targets, e.g. ARM.
1196 /// If all uses are outside the loop, we don't require that all multiplies
1197 /// be folded into the addressing mode, nor even that the factor be constant;
1198 /// a multiply (executed once) outside the loop is better than another IV
1199 /// within. Well, usually.
1200 SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
1201 bool AllUsesAreAddresses,
1202 bool AllUsesAreOutsideLoop,
1203 const SCEVHandle &Stride,
1204 IVExpr &IV, const Type *Ty,
1205 const std::vector<BasedUser>& UsersToProcess) {
1206 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1207 int64_t SInt = SC->getValue()->getSExtValue();
1208 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1210 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1211 IVsByStride.find(StrideOrder[NewStride]);
1212 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1214 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1215 if (SI->first != Stride &&
1216 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
1218 int64_t Scale = SInt / SSInt;
1219 // Check that this stride is valid for all the types used for loads and
1220 // stores; if it can be used for some and not others, we might as well use
1221 // the original stride everywhere, since we have to create the IV for it
1222 // anyway. If the scale is 1, then we don't need to worry about folding
1225 (AllUsesAreAddresses &&
1226 ValidStride(HasBaseReg, Scale, UsersToProcess)))
1227 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1228 IE = SI->second.IVs.end(); II != IE; ++II)
1229 // FIXME: Only handle base == 0 for now.
1230 // Only reuse previous IV if it would not require a type conversion.
1231 if (II->Base->isZero() &&
1232 !RequiresTypeConversion(II->Base->getType(), Ty)) {
1234 return SE->getIntegerSCEV(Scale, Stride->getType());
1237 } else if (AllUsesAreOutsideLoop) {
1238 // Accept nonconstant strides here; it is really really right to substitute
1239 // an existing IV if we can.
1240 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1242 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1243 IVsByStride.find(StrideOrder[NewStride]);
1244 if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1246 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1247 if (SI->first != Stride && SSInt != 1)
1249 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1250 IE = SI->second.IVs.end(); II != IE; ++II)
1251 // Accept nonzero base here.
1252 // Only reuse previous IV if it would not require a type conversion.
1253 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1258 // Special case, old IV is -1*x and this one is x. Can treat this one as
1260 for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1262 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
1263 IVsByStride.find(StrideOrder[NewStride]);
1264 if (SI == IVsByStride.end())
1266 if (SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1267 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1268 if (Stride == ME->getOperand(1) &&
1269 SC->getValue()->getSExtValue() == -1LL)
1270 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1271 IE = SI->second.IVs.end(); II != IE; ++II)
1272 // Accept nonzero base here.
1273 // Only reuse previous IV if it would not require type conversion.
1274 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1276 return SE->getIntegerSCEV(-1LL, Stride->getType());
1280 return SE->getIntegerSCEV(0, Stride->getType());
1283 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1284 /// returns true if Val's isUseOfPostIncrementedValue is true.
1285 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1286 return Val.isUseOfPostIncrementedValue;
1289 /// isNonConstantNegative - Return true if the specified scev is negated, but
1291 static bool isNonConstantNegative(const SCEVHandle &Expr) {
1292 SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1293 if (!Mul) return false;
1295 // If there is a constant factor, it will be first.
1296 SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1297 if (!SC) return false;
1299 // Return true if the value is negative, this matches things like (-42 * V).
1300 return SC->getValue()->getValue().isNegative();
1303 // CollectIVUsers - Transform our list of users and offsets to a bit more
1304 // complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1305 // of the strided accesses, as well as the old information from Uses. We
1306 // progressively move information from the Base field to the Imm field, until
1307 // we eventually have the full access expression to rewrite the use.
1308 SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1309 IVUsersOfOneStride &Uses,
1311 bool &AllUsesAreAddresses,
1312 bool &AllUsesAreOutsideLoop,
1313 std::vector<BasedUser> &UsersToProcess) {
1314 UsersToProcess.reserve(Uses.Users.size());
1315 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
1316 UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
1318 // Move any loop variant operands from the offset field to the immediate
1319 // field of the use, so that we don't try to use something before it is
1321 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1322 UsersToProcess.back().Imm, L, SE);
1323 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1324 "Base value is not loop invariant!");
1327 // We now have a whole bunch of uses of like-strided induction variables, but
1328 // they might all have different bases. We want to emit one PHI node for this
1329 // stride which we fold as many common expressions (between the IVs) into as
1330 // possible. Start by identifying the common expressions in the base values
1331 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1332 // "A+B"), emit it to the preheader, then remove the expression from the
1333 // UsersToProcess base values.
1334 SCEVHandle CommonExprs =
1335 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1337 // Next, figure out what we can represent in the immediate fields of
1338 // instructions. If we can represent anything there, move it to the imm
1339 // fields of the BasedUsers. We do this so that it increases the commonality
1340 // of the remaining uses.
1341 unsigned NumPHI = 0;
1342 bool HasAddress = false;
1343 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1344 // If the user is not in the current loop, this means it is using the exit
1345 // value of the IV. Do not put anything in the base, make sure it's all in
1346 // the immediate field to allow as much factoring as possible.
1347 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1348 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1349 UsersToProcess[i].Base);
1350 UsersToProcess[i].Base =
1351 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1353 // Not all uses are outside the loop.
1354 AllUsesAreOutsideLoop = false;
1356 // Addressing modes can be folded into loads and stores. Be careful that
1357 // the store is through the expression, not of the expression though.
1359 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1360 UsersToProcess[i].OperandValToReplace);
1361 if (isa<PHINode>(UsersToProcess[i].Inst)) {
1369 // If this use isn't an address, then not all uses are addresses.
1370 if (!isAddress && !isPHI)
1371 AllUsesAreAddresses = false;
1373 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1374 UsersToProcess[i].Imm, isAddress, L, SE);
1378 // If one of the use is a PHI node and all other uses are addresses, still
1379 // allow iv reuse. Essentially we are trading one constant multiplication
1380 // for one fewer iv.
1382 AllUsesAreAddresses = false;
1384 // There are no in-loop address uses.
1385 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1386 AllUsesAreAddresses = false;
1391 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1392 /// is valid and profitable for the given set of users of a stride. In
1393 /// full strength-reduction mode, all addresses at the current stride are
1394 /// strength-reduced all the way down to pointer arithmetic.
1396 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1397 const std::vector<BasedUser> &UsersToProcess,
1399 bool AllUsesAreAddresses,
1400 SCEVHandle Stride) {
1401 if (!EnableFullLSRMode)
1404 // The heuristics below aim to avoid increasing register pressure, but
1405 // fully strength-reducing all the addresses increases the number of
1406 // add instructions, so don't do this when optimizing for size.
1407 // TODO: If the loop is large, the savings due to simpler addresses
1408 // may oughtweight the costs of the extra increment instructions.
1409 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1412 // TODO: For now, don't do full strength reduction if there could
1413 // potentially be greater-stride multiples of the current stride
1414 // which could reuse the current stride IV.
1415 if (StrideOrder.back() != Stride)
1418 // Iterate through the uses to find conditions that automatically rule out
1420 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1421 SCEV *Base = UsersToProcess[i].Base;
1422 SCEV *Imm = UsersToProcess[i].Imm;
1423 // If any users have a loop-variant component, they can't be fully
1424 // strength-reduced.
1425 if (Imm && !Imm->isLoopInvariant(L))
1427 // If there are to users with the same base and the difference between
1428 // the two Imm values can't be folded into the address, full
1429 // strength reduction would increase register pressure.
1431 SCEV *CurImm = UsersToProcess[i].Imm;
1432 if ((CurImm || Imm) && CurImm != Imm) {
1433 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1434 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1435 const Instruction *Inst = UsersToProcess[i].Inst;
1436 const Type *UseTy = getAccessType(Inst);
1437 SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1438 if (!Diff->isZero() &&
1439 (!AllUsesAreAddresses ||
1440 !fitsInAddressMode(Diff, UseTy, TLI, /*HasBaseReg=*/true)))
1443 } while (++i != e && Base == UsersToProcess[i].Base);
1446 // If there's exactly one user in this stride, fully strength-reducing it
1447 // won't increase register pressure. If it's starting from a non-zero base,
1448 // it'll be simpler this way.
1449 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1452 // Otherwise, if there are any users in this stride that don't require
1453 // a register for their base, full strength-reduction will increase
1454 // register pressure.
1455 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1456 if (UsersToProcess[i].Base->isZero())
1459 // Otherwise, go for it.
1463 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1464 /// with the specified start and step values in the specified loop.
1466 /// If NegateStride is true, the stride should be negated by using a
1467 /// subtract instead of an add.
1469 /// Return the created phi node.
1471 static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
1473 const TargetData *TD,
1474 SCEVExpander &Rewriter) {
1475 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1476 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1478 BasicBlock *Header = L->getHeader();
1479 BasicBlock *Preheader = L->getLoopPreheader();
1480 BasicBlock *LatchBlock = L->getLoopLatch();
1481 const Type *Ty = Start->getType();
1482 if (isa<PointerType>(Ty)) Ty = TD->getIntPtrType();
1484 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1485 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1488 // If the stride is negative, insert a sub instead of an add for the
1490 bool isNegative = isNonConstantNegative(Step);
1491 SCEVHandle IncAmount = Step;
1493 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1495 // Insert an add instruction right before the terminator corresponding
1496 // to the back-edge.
1497 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1498 Preheader->getTerminator());
1501 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1502 LatchBlock->getTerminator());
1504 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1505 LatchBlock->getTerminator());
1507 if (!isa<ConstantInt>(StepV)) ++NumVariable;
1509 PN->addIncoming(IncV, LatchBlock);
1515 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1516 // We want to emit code for users inside the loop first. To do this, we
1517 // rearrange BasedUser so that the entries at the end have
1518 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1519 // vector (so we handle them first).
1520 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1521 PartitionByIsUseOfPostIncrementedValue);
1523 // Sort this by base, so that things with the same base are handled
1524 // together. By partitioning first and stable-sorting later, we are
1525 // guaranteed that within each base we will pop off users from within the
1526 // loop before users outside of the loop with a particular base.
1528 // We would like to use stable_sort here, but we can't. The problem is that
1529 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1530 // we don't have anything to do a '<' comparison on. Because we think the
1531 // number of uses is small, do a horrible bubble sort which just relies on
1533 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1534 // Get a base value.
1535 SCEVHandle Base = UsersToProcess[i].Base;
1537 // Compact everything with this base to be consecutive with this one.
1538 for (unsigned j = i+1; j != e; ++j) {
1539 if (UsersToProcess[j].Base == Base) {
1540 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1547 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1548 /// UsersToProcess, meaning lowering addresses all the way down to direct
1549 /// pointer arithmetic.
1552 LoopStrengthReduce::PrepareToStrengthReduceFully(
1553 std::vector<BasedUser> &UsersToProcess,
1555 SCEVHandle CommonExprs,
1557 SCEVExpander &PreheaderRewriter) {
1558 DOUT << " Fully reducing all users\n";
1560 // Rewrite the UsersToProcess records, creating a separate PHI for each
1561 // unique Base value.
1562 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1563 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1564 // pick the first Imm value here to start with, and adjust it for the
1566 SCEVHandle Imm = UsersToProcess[i].Imm;
1567 SCEVHandle Base = UsersToProcess[i].Base;
1568 SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
1569 PHINode *Phi = InsertAffinePhi(Start, Stride, L, TD,
1571 // Loop over all the users with the same base.
1573 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1574 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1575 UsersToProcess[i].Phi = Phi;
1576 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1577 "ShouldUseFullStrengthReductionMode should reject this!");
1578 } while (++i != e && Base == UsersToProcess[i].Base);
1582 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1583 /// given users to share.
1586 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1587 std::vector<BasedUser> &UsersToProcess,
1589 SCEVHandle CommonExprs,
1592 SCEVExpander &PreheaderRewriter) {
1593 DOUT << " Inserting new PHI:\n";
1595 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1599 // Remember this in case a later stride is multiple of this.
1600 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1602 // All the users will share this new IV.
1603 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1604 UsersToProcess[i].Phi = Phi;
1607 DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
1611 /// PrepareToStrengthReduceWithNewPhi - Prepare for the given users to reuse
1612 /// an induction variable with a stride that is a factor of the current
1613 /// induction variable.
1616 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1617 std::vector<BasedUser> &UsersToProcess,
1619 const IVExpr &ReuseIV,
1620 Instruction *PreInsertPt) {
1621 DOUT << " Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1622 << " and BASE " << *ReuseIV.Base << "\n";
1624 // All the users will share the reused IV.
1625 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1626 UsersToProcess[i].Phi = ReuseIV.PHI;
1628 Constant *C = dyn_cast<Constant>(CommonBaseV);
1630 (!C->isNullValue() &&
1631 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1633 // We want the common base emitted into the preheader! This is just
1634 // using cast as a copy so BitCast (no-op cast) is appropriate
1635 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1636 "commonbase", PreInsertPt);
1639 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1640 const Type *AccessTy,
1641 std::vector<BasedUser> &UsersToProcess,
1642 const TargetLowering *TLI) {
1643 SmallVector<Instruction*, 16> AddrModeInsts;
1644 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1645 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1647 ExtAddrMode AddrMode =
1648 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1649 AccessTy, UsersToProcess[i].Inst,
1650 AddrModeInsts, *TLI);
1651 if (GV && GV != AddrMode.BaseGV)
1653 if (Offset && !AddrMode.BaseOffs)
1654 // FIXME: How to accurate check it's immediate offset is folded.
1656 AddrModeInsts.clear();
1661 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1662 /// stride of IV. All of the users may have different starting values, and this
1663 /// may not be the only stride.
1664 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1665 IVUsersOfOneStride &Uses,
1667 // If all the users are moved to another stride, then there is nothing to do.
1668 if (Uses.Users.empty())
1671 // Keep track if every use in UsersToProcess is an address. If they all are,
1672 // we may be able to rewrite the entire collection of them in terms of a
1673 // smaller-stride IV.
1674 bool AllUsesAreAddresses = true;
1676 // Keep track if every use of a single stride is outside the loop. If so,
1677 // we want to be more aggressive about reusing a smaller-stride IV; a
1678 // multiply outside the loop is better than another IV inside. Well, usually.
1679 bool AllUsesAreOutsideLoop = true;
1681 // Transform our list of users and offsets to a bit more complex table. In
1682 // this new vector, each 'BasedUser' contains 'Base' the base of the
1683 // strided accessas well as the old information from Uses. We progressively
1684 // move information from the Base field to the Imm field, until we eventually
1685 // have the full access expression to rewrite the use.
1686 std::vector<BasedUser> UsersToProcess;
1687 SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1688 AllUsesAreOutsideLoop,
1691 // Sort the UsersToProcess array so that users with common bases are
1692 // next to each other.
1693 SortUsersToProcess(UsersToProcess);
1695 // If we managed to find some expressions in common, we'll need to carry
1696 // their value in a register and add it in for each use. This will take up
1697 // a register operand, which potentially restricts what stride values are
1699 bool HaveCommonExprs = !CommonExprs->isZero();
1701 const Type *ReplacedTy = CommonExprs->getType();
1702 if (isa<PointerType>(ReplacedTy)) ReplacedTy = TD->getIntPtrType();
1704 // If all uses are addresses, consider sinking the immediate part of the
1705 // common expression back into uses if they can fit in the immediate fields.
1706 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1707 SCEVHandle NewCommon = CommonExprs;
1708 SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
1709 MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
1710 if (!Imm->isZero()) {
1713 // If the immediate part of the common expression is a GV, check if it's
1714 // possible to fold it into the target addressing mode.
1715 GlobalValue *GV = 0;
1716 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1717 GV = dyn_cast<GlobalValue>(SU->getValue());
1719 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1720 Offset = SC->getValue()->getSExtValue();
1722 // Pass VoidTy as the AccessTy to be conservative, because
1723 // there could be multiple access types among all the uses.
1724 DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
1725 UsersToProcess, TLI);
1728 DOUT << " Sinking " << *Imm << " back down into uses\n";
1729 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1730 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1731 CommonExprs = NewCommon;
1732 HaveCommonExprs = !CommonExprs->isZero();
1738 // Now that we know what we need to do, insert the PHI node itself.
1740 DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1742 << " Common base: " << *CommonExprs << "\n";
1744 SCEVExpander Rewriter(*SE, *LI, *TD);
1745 SCEVExpander PreheaderRewriter(*SE, *LI, *TD);
1747 BasicBlock *Preheader = L->getLoopPreheader();
1748 Instruction *PreInsertPt = Preheader->getTerminator();
1749 BasicBlock *LatchBlock = L->getLoopLatch();
1751 Value *CommonBaseV = ConstantInt::get(ReplacedTy, 0);
1753 SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1754 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1755 SE->getIntegerSCEV(0, Type::Int32Ty),
1758 /// Choose a strength-reduction strategy and prepare for it by creating
1759 /// the necessary PHIs and adjusting the bookkeeping.
1760 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1761 AllUsesAreAddresses, Stride)) {
1762 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1765 // Emit the initial base value into the loop preheader.
1766 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1769 // If all uses are addresses, check if it is possible to reuse an IV with a
1770 // stride that is a factor of this stride. And that the multiple is a number
1771 // that can be encoded in the scale field of the target addressing mode. And
1772 // that we will have a valid instruction after this substition, including
1773 // the immediate field, if any.
1774 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1775 AllUsesAreOutsideLoop,
1776 Stride, ReuseIV, ReplacedTy,
1778 if (isa<SCEVConstant>(RewriteFactor) &&
1779 cast<SCEVConstant>(RewriteFactor)->isZero())
1780 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1781 CommonBaseV, L, PreheaderRewriter);
1783 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1784 ReuseIV, PreInsertPt);
1787 // Process all the users now, replacing their strided uses with
1788 // strength-reduced forms. This outer loop handles all bases, the inner
1789 // loop handles all users of a particular base.
1790 while (!UsersToProcess.empty()) {
1791 SCEVHandle Base = UsersToProcess.back().Base;
1792 Instruction *Inst = UsersToProcess.back().Inst;
1794 // Emit the code for Base into the preheader.
1796 if (!Base->isZero()) {
1797 BaseV = PreheaderRewriter.expandCodeFor(Base, Base->getType(),
1800 DOUT << " INSERTING code for BASE = " << *Base << ":";
1801 if (BaseV->hasName())
1802 DOUT << " Result value name = %" << BaseV->getNameStr();
1805 // If BaseV is a non-zero constant, make sure that it gets inserted into
1806 // the preheader, instead of being forward substituted into the uses. We
1807 // do this by forcing a BitCast (noop cast) to be inserted into the
1808 // preheader in this case.
1809 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
1810 // We want this constant emitted into the preheader! This is just
1811 // using cast as a copy so BitCast (no-op cast) is appropriate
1812 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1817 // Emit the code to add the immediate offset to the Phi value, just before
1818 // the instructions that we identified as using this stride and base.
1820 // FIXME: Use emitted users to emit other users.
1821 BasedUser &User = UsersToProcess.back();
1823 DOUT << " Examining use ";
1824 DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1825 /*PrintType=*/false));
1826 DOUT << " in Inst: " << *Inst;
1828 // If this instruction wants to use the post-incremented value, move it
1829 // after the post-inc and use its value instead of the PHI.
1830 Value *RewriteOp = User.Phi;
1831 if (User.isUseOfPostIncrementedValue) {
1832 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1834 // If this user is in the loop, make sure it is the last thing in the
1835 // loop to ensure it is dominated by the increment.
1836 if (L->contains(User.Inst->getParent()))
1837 User.Inst->moveBefore(LatchBlock->getTerminator());
1840 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
1842 if (TD->getTypeSizeInBits(RewriteOp->getType()) !=
1843 TD->getTypeSizeInBits(ReplacedTy)) {
1844 assert(TD->getTypeSizeInBits(RewriteOp->getType()) >
1845 TD->getTypeSizeInBits(ReplacedTy) &&
1846 "Unexpected widening cast!");
1847 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1850 // If we had to insert new instructions for RewriteOp, we have to
1851 // consider that they may not have been able to end up immediately
1852 // next to RewriteOp, because non-PHI instructions may never precede
1853 // PHI instructions in a block. In this case, remember where the last
1854 // instruction was inserted so that if we're replacing a different
1855 // PHI node, we can use the later point to expand the final
1857 Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1858 if (RewriteOp == User.Phi) NewBasePt = 0;
1860 // Clear the SCEVExpander's expression map so that we are guaranteed
1861 // to have the code emitted where we expect it.
1864 // If we are reusing the iv, then it must be multiplied by a constant
1865 // factor to take advantage of the addressing mode scale component.
1866 if (!RewriteFactor->isZero()) {
1867 // If we're reusing an IV with a nonzero base (currently this happens
1868 // only when all reuses are outside the loop) subtract that base here.
1869 // The base has been used to initialize the PHI node but we don't want
1871 if (!ReuseIV.Base->isZero()) {
1872 SCEVHandle typedBase = ReuseIV.Base;
1873 if (RewriteExpr->getType()->getPrimitiveSizeInBits() !=
1874 ReuseIV.Base->getType()->getPrimitiveSizeInBits()) {
1875 // It's possible the original IV is a larger type than the new IV,
1876 // in which case we have to truncate the Base. We checked in
1877 // RequiresTypeConversion that this is valid.
1878 assert (RewriteExpr->getType()->getPrimitiveSizeInBits() <
1879 ReuseIV.Base->getType()->getPrimitiveSizeInBits() &&
1880 "Unexpected lengthening conversion!");
1881 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1882 RewriteExpr->getType());
1884 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1887 // Multiply old variable, with base removed, by new scale factor.
1888 RewriteExpr = SE->getMulExpr(RewriteFactor,
1891 // The common base is emitted in the loop preheader. But since we
1892 // are reusing an IV, it has not been used to initialize the PHI node.
1893 // Add it to the expression used to rewrite the uses.
1894 // When this use is outside the loop, we earlier subtracted the
1895 // common base, and are adding it back here. Use the same expression
1896 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1897 if (!CommonExprs->isZero()) {
1898 if (L->contains(User.Inst->getParent()))
1899 RewriteExpr = SE->getAddExpr(RewriteExpr,
1900 SE->getUnknown(CommonBaseV));
1902 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1906 // Now that we know what we need to do, insert code before User for the
1907 // immediate and any loop-variant expressions.
1909 // Add BaseV to the PHI value if needed.
1910 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1912 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1916 // Mark old value we replaced as possibly dead, so that it is eliminated
1917 // if we just replaced the last use of that value.
1918 DeadInsts.push_back(cast<Instruction>(User.OperandValToReplace));
1920 UsersToProcess.pop_back();
1923 // If there are any more users to process with the same base, process them
1924 // now. We sorted by base above, so we just have to check the last elt.
1925 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1926 // TODO: Next, find out which base index is the most common, pull it out.
1929 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1930 // different starting values, into different PHIs.
1933 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1934 /// set the IV user and stride information and return true, otherwise return
1936 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1937 const SCEVHandle *&CondStride) {
1938 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1940 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1941 IVUsesByStride.find(StrideOrder[Stride]);
1942 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1944 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1945 E = SI->second.Users.end(); UI != E; ++UI)
1946 if (UI->User == Cond) {
1947 // NOTE: we could handle setcc instructions with multiple uses here, but
1948 // InstCombine does it as well for simple uses, it's not clear that it
1949 // occurs enough in real life to handle.
1951 CondStride = &SI->first;
1959 // Constant strides come first which in turns are sorted by their absolute
1960 // values. If absolute values are the same, then positive strides comes first.
1962 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1963 struct StrideCompare {
1964 const TargetData *TD;
1965 explicit StrideCompare(const TargetData *td) : TD(td) {}
1967 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1968 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1969 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1971 int64_t LV = LHSC->getValue()->getSExtValue();
1972 int64_t RV = RHSC->getValue()->getSExtValue();
1973 uint64_t ALV = (LV < 0) ? -LV : LV;
1974 uint64_t ARV = (RV < 0) ? -RV : RV;
1982 // If it's the same value but different type, sort by bit width so
1983 // that we emit larger induction variables before smaller
1984 // ones, letting the smaller be re-written in terms of larger ones.
1985 return TD->getTypeSizeInBits(RHS->getType()) <
1986 TD->getTypeSizeInBits(LHS->getType());
1988 return LHSC && !RHSC;
1993 /// ChangeCompareStride - If a loop termination compare instruction is the
1994 /// only use of its stride, and the compaison is against a constant value,
1995 /// try eliminate the stride by moving the compare instruction to another
1996 /// stride and change its constant operand accordingly. e.g.
2002 /// if (v2 < 10) goto loop
2007 /// if (v1 < 30) goto loop
2008 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
2009 IVStrideUse* &CondUse,
2010 const SCEVHandle* &CondStride) {
2011 if (StrideOrder.size() < 2 ||
2012 IVUsesByStride[*CondStride].Users.size() != 1)
2014 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
2015 if (!SC) return Cond;
2017 ICmpInst::Predicate Predicate = Cond->getPredicate();
2018 int64_t CmpSSInt = SC->getValue()->getSExtValue();
2019 unsigned BitWidth = TD->getTypeSizeInBits((*CondStride)->getType());
2020 uint64_t SignBit = 1ULL << (BitWidth-1);
2021 const Type *CmpTy = Cond->getOperand(0)->getType();
2022 const Type *NewCmpTy = NULL;
2023 unsigned TyBits = TD->getTypeSizeInBits(CmpTy);
2024 unsigned NewTyBits = 0;
2025 SCEVHandle *NewStride = NULL;
2026 Value *NewCmpLHS = NULL;
2027 Value *NewCmpRHS = NULL;
2029 SCEVHandle NewOffset = SE->getIntegerSCEV(0, UIntPtrTy);
2031 if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
2032 int64_t CmpVal = C->getValue().getSExtValue();
2034 // Check stride constant and the comparision constant signs to detect
2036 if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
2039 // Look for a suitable stride / iv as replacement.
2040 for (unsigned i = 0, e = StrideOrder.size(); i != e; ++i) {
2041 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2042 IVUsesByStride.find(StrideOrder[i]);
2043 if (!isa<SCEVConstant>(SI->first))
2045 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2046 if (abs(SSInt) <= abs(CmpSSInt) || (SSInt % CmpSSInt) != 0)
2049 Scale = SSInt / CmpSSInt;
2050 int64_t NewCmpVal = CmpVal * Scale;
2051 APInt Mul = APInt(BitWidth, NewCmpVal);
2052 // Check for overflow.
2053 if (Mul.getSExtValue() != NewCmpVal)
2056 // Watch out for overflow.
2057 if (ICmpInst::isSignedPredicate(Predicate) &&
2058 (CmpVal & SignBit) != (NewCmpVal & SignBit))
2061 if (NewCmpVal == CmpVal)
2063 // Pick the best iv to use trying to avoid a cast.
2065 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2066 E = SI->second.Users.end(); UI != E; ++UI) {
2067 NewCmpLHS = UI->OperandValToReplace;
2068 if (NewCmpLHS->getType() == CmpTy)
2074 NewCmpTy = NewCmpLHS->getType();
2075 NewTyBits = TD->getTypeSizeInBits(NewCmpTy);
2076 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
2077 // Check if it is possible to rewrite it using
2078 // an iv / stride of a smaller integer type.
2079 bool TruncOk = false;
2080 if (NewCmpTy->isInteger()) {
2081 unsigned Bits = NewTyBits;
2082 if (ICmpInst::isSignedPredicate(Predicate))
2084 uint64_t Mask = (1ULL << Bits) - 1;
2085 if (((uint64_t)NewCmpVal & Mask) == (uint64_t)NewCmpVal)
2092 // Don't rewrite if use offset is non-constant and the new type is
2093 // of a different type.
2094 // FIXME: too conservative?
2095 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->Offset))
2098 bool AllUsesAreAddresses = true;
2099 bool AllUsesAreOutsideLoop = true;
2100 std::vector<BasedUser> UsersToProcess;
2101 SCEVHandle CommonExprs = CollectIVUsers(SI->first, SI->second, L,
2102 AllUsesAreAddresses,
2103 AllUsesAreOutsideLoop,
2105 // Avoid rewriting the compare instruction with an iv of new stride
2106 // if it's likely the new stride uses will be rewritten using the
2107 // stride of the compare instruction.
2108 if (AllUsesAreAddresses &&
2109 ValidStride(!CommonExprs->isZero(), Scale, UsersToProcess))
2112 // If scale is negative, use swapped predicate unless it's testing
2114 if (Scale < 0 && !Cond->isEquality())
2115 Predicate = ICmpInst::getSwappedPredicate(Predicate);
2117 NewStride = &StrideOrder[i];
2118 if (!isa<PointerType>(NewCmpTy))
2119 NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
2121 ConstantInt *CI = ConstantInt::get(UIntPtrTy, NewCmpVal);
2122 NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2124 NewOffset = TyBits == NewTyBits
2125 ? SE->getMulExpr(CondUse->Offset,
2126 SE->getConstant(ConstantInt::get(CmpTy, Scale)))
2127 : SE->getConstant(ConstantInt::get(NewCmpTy,
2128 cast<SCEVConstant>(CondUse->Offset)->getValue()->getSExtValue()*Scale));
2133 // Forgo this transformation if it the increment happens to be
2134 // unfortunately positioned after the condition, and the condition
2135 // has multiple uses which prevent it from being moved immediately
2136 // before the branch. See
2137 // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2138 // for an example of this situation.
2139 if (!Cond->hasOneUse()) {
2140 for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2147 // Create a new compare instruction using new stride / iv.
2148 ICmpInst *OldCond = Cond;
2149 // Insert new compare instruction.
2150 Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
2151 L->getHeader()->getName() + ".termcond",
2154 // Remove the old compare instruction. The old indvar is probably dead too.
2155 DeadInsts.push_back(cast<Instruction>(CondUse->OperandValToReplace));
2156 SE->deleteValueFromRecords(OldCond);
2157 OldCond->replaceAllUsesWith(Cond);
2158 OldCond->eraseFromParent();
2160 IVUsesByStride[*CondStride].Users.pop_back();
2161 IVUsesByStride[*NewStride].addUser(NewOffset, Cond, NewCmpLHS);
2162 CondUse = &IVUsesByStride[*NewStride].Users.back();
2163 CondStride = NewStride;
2170 /// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2171 /// an smax computation.
2173 /// This is a narrow solution to a specific, but acute, problem. For loops
2179 /// } while (++i < n);
2181 /// where the comparison is signed, the trip count isn't just 'n', because
2182 /// 'n' could be negative. And unfortunately this can come up even for loops
2183 /// where the user didn't use a C do-while loop. For example, seemingly
2184 /// well-behaved top-test loops will commonly be lowered like this:
2190 /// } while (++i < n);
2193 /// and then it's possible for subsequent optimization to obscure the if
2194 /// test in such a way that indvars can't find it.
2196 /// When indvars can't find the if test in loops like this, it creates a
2197 /// signed-max expression, which allows it to give the loop a canonical
2198 /// induction variable:
2201 /// smax = n < 1 ? 1 : n;
2204 /// } while (++i != smax);
2206 /// Canonical induction variables are necessary because the loop passes
2207 /// are designed around them. The most obvious example of this is the
2208 /// LoopInfo analysis, which doesn't remember trip count values. It
2209 /// expects to be able to rediscover the trip count each time it is
2210 /// needed, and it does this using a simple analyis that only succeeds if
2211 /// the loop has a canonical induction variable.
2213 /// However, when it comes time to generate code, the maximum operation
2214 /// can be quite costly, especially if it's inside of an outer loop.
2216 /// This function solves this problem by detecting this type of loop and
2217 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2218 /// the instructions for the maximum computation.
2220 ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2221 IVStrideUse* &CondUse) {
2222 // Check that the loop matches the pattern we're looking for.
2223 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2224 Cond->getPredicate() != CmpInst::ICMP_NE)
2227 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2228 if (!Sel || !Sel->hasOneUse()) return Cond;
2230 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2231 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2233 SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2235 // Add one to the backedge-taken count to get the trip count.
2236 SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2238 // Check for a max calculation that matches the pattern.
2239 SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
2240 if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2242 SCEVHandle SMaxLHS = SMax->getOperand(0);
2243 SCEVHandle SMaxRHS = SMax->getOperand(1);
2244 if (!SMaxLHS || SMaxLHS != One) return Cond;
2246 // Check the relevant induction variable for conformance to
2248 SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2249 SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2250 if (!AR || !AR->isAffine() ||
2251 AR->getStart() != One ||
2252 AR->getStepRecurrence(*SE) != One)
2255 assert(AR->getLoop() == L &&
2256 "Loop condition operand is an addrec in a different loop!");
2258 // Check the right operand of the select, and remember it, as it will
2259 // be used in the new comparison instruction.
2261 if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2262 NewRHS = Sel->getOperand(1);
2263 else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2264 NewRHS = Sel->getOperand(2);
2265 if (!NewRHS) return Cond;
2267 // Ok, everything looks ok to change the condition into an SLT or SGE and
2268 // delete the max calculation.
2270 new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2273 Cond->getOperand(0), NewRHS, "scmp", Cond);
2275 // Delete the max calculation instructions.
2276 SE->deleteValueFromRecords(Cond);
2277 Cond->replaceAllUsesWith(NewCond);
2278 Cond->eraseFromParent();
2279 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2280 SE->deleteValueFromRecords(Sel);
2281 Sel->eraseFromParent();
2282 if (Cmp->use_empty()) {
2283 SE->deleteValueFromRecords(Cmp);
2284 Cmp->eraseFromParent();
2286 CondUse->User = NewCond;
2290 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2291 /// inside the loop then try to eliminate the cast opeation.
2292 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2294 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2295 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2298 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e;
2300 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2301 IVUsesByStride.find(StrideOrder[Stride]);
2302 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2303 if (!isa<SCEVConstant>(SI->first))
2306 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2307 E = SI->second.Users.end(); UI != E; /* empty */) {
2308 std::vector<IVStrideUse>::iterator CandidateUI = UI;
2310 Instruction *ShadowUse = CandidateUI->User;
2311 const Type *DestTy = NULL;
2313 /* If shadow use is a int->float cast then insert a second IV
2314 to eliminate this cast.
2316 for (unsigned i = 0; i < n; ++i)
2322 for (unsigned i = 0; i < n; ++i, ++d)
2325 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->User))
2326 DestTy = UCast->getDestTy();
2327 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->User))
2328 DestTy = SCast->getDestTy();
2329 if (!DestTy) continue;
2332 /* If target does not support DestTy natively then do not apply
2333 this transformation. */
2334 MVT DVT = TLI->getValueType(DestTy);
2335 if (!TLI->isTypeLegal(DVT)) continue;
2338 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2340 if (PH->getNumIncomingValues() != 2) continue;
2342 const Type *SrcTy = PH->getType();
2343 int Mantissa = DestTy->getFPMantissaWidth();
2344 if (Mantissa == -1) continue;
2345 if ((int)TD->getTypeSizeInBits(SrcTy) > Mantissa)
2348 unsigned Entry, Latch;
2349 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2357 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2358 if (!Init) continue;
2359 ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2361 BinaryOperator *Incr =
2362 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2363 if (!Incr) continue;
2364 if (Incr->getOpcode() != Instruction::Add
2365 && Incr->getOpcode() != Instruction::Sub)
2368 /* Initialize new IV, double d = 0.0 in above example. */
2369 ConstantInt *C = NULL;
2370 if (Incr->getOperand(0) == PH)
2371 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2372 else if (Incr->getOperand(1) == PH)
2373 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2379 /* Add new PHINode. */
2380 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2382 /* create new increment. '++d' in above example. */
2383 ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2384 BinaryOperator *NewIncr =
2385 BinaryOperator::Create(Incr->getOpcode(),
2386 NewPH, CFP, "IV.S.next.", Incr);
2388 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2389 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2391 /* Remove cast operation */
2392 SE->deleteValueFromRecords(ShadowUse);
2393 ShadowUse->replaceAllUsesWith(NewPH);
2394 ShadowUse->eraseFromParent();
2395 SI->second.Users.erase(CandidateUI);
2402 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2403 // uses in the loop, look to see if we can eliminate some, in favor of using
2404 // common indvars for the different uses.
2405 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2406 // TODO: implement optzns here.
2408 OptimizeShadowIV(L);
2410 // Finally, get the terminating condition for the loop if possible. If we
2411 // can, we want to change it to use a post-incremented version of its
2412 // induction variable, to allow coalescing the live ranges for the IV into
2413 // one register value.
2414 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
2415 BasicBlock *Preheader = L->getLoopPreheader();
2416 BasicBlock *LatchBlock =
2417 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
2418 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
2419 if (!TermBr || TermBr->isUnconditional() ||
2420 !isa<ICmpInst>(TermBr->getCondition()))
2422 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2424 // Search IVUsesByStride to find Cond's IVUse if there is one.
2425 IVStrideUse *CondUse = 0;
2426 const SCEVHandle *CondStride = 0;
2428 if (!FindIVUserForCond(Cond, CondUse, CondStride))
2429 return; // setcc doesn't use the IV.
2431 // If the trip count is computed in terms of an smax (due to ScalarEvolution
2432 // being unable to find a sufficient guard, for example), change the loop
2433 // comparison to use SLT instead of NE.
2434 Cond = OptimizeSMax(L, Cond, CondUse);
2436 // If possible, change stride and operands of the compare instruction to
2437 // eliminate one stride.
2438 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2440 // It's possible for the setcc instruction to be anywhere in the loop, and
2441 // possible for it to have multiple users. If it is not immediately before
2442 // the latch block branch, move it.
2443 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2444 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
2445 Cond->moveBefore(TermBr);
2447 // Otherwise, clone the terminating condition and insert into the loopend.
2448 Cond = cast<ICmpInst>(Cond->clone());
2449 Cond->setName(L->getHeader()->getName() + ".termcond");
2450 LatchBlock->getInstList().insert(TermBr, Cond);
2452 // Clone the IVUse, as the old use still exists!
2453 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
2454 CondUse->OperandValToReplace);
2455 CondUse = &IVUsesByStride[*CondStride].Users.back();
2459 // If we get to here, we know that we can transform the setcc instruction to
2460 // use the post-incremented version of the IV, allowing us to coalesce the
2461 // live ranges for the IV correctly.
2462 CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
2463 CondUse->isUseOfPostIncrementedValue = true;
2467 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2469 LI = &getAnalysis<LoopInfo>();
2470 DT = &getAnalysis<DominatorTree>();
2471 SE = &getAnalysis<ScalarEvolution>();
2472 TD = &getAnalysis<TargetData>();
2473 UIntPtrTy = TD->getIntPtrType();
2476 // Find all uses of induction variables in this loop, and categorize
2477 // them by stride. Start by finding all of the PHI nodes in the header for
2478 // this loop. If they are induction variables, inspect their uses.
2479 SmallPtrSet<Instruction*,16> Processed; // Don't reprocess instructions.
2480 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
2481 AddUsersIfInteresting(I, L, Processed);
2483 if (!IVUsesByStride.empty()) {
2485 DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2490 // Sort the StrideOrder so we process larger strides first.
2491 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare(TD));
2493 // Optimize induction variables. Some indvar uses can be transformed to use
2494 // strides that will be needed for other purposes. A common example of this
2495 // is the exit test for the loop, which can often be rewritten to use the
2496 // computation of some other indvar to decide when to terminate the loop.
2499 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
2500 // doing computation in byte values, promote to 32-bit values if safe.
2502 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
2503 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2504 // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2505 // Need to be careful that IV's are all the same type. Only works for
2506 // intptr_t indvars.
2508 // IVsByStride keeps IVs for one particular loop.
2509 assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2511 // Note: this processes each stride/type pair individually. All users
2512 // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2513 // Also, note that we iterate over IVUsesByStride indirectly by using
2514 // StrideOrder. This extra layer of indirection makes the ordering of
2515 // strides deterministic - not dependent on map order.
2516 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
2517 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
2518 IVUsesByStride.find(StrideOrder[Stride]);
2519 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2520 StrengthReduceStridedIVUsers(SI->first, SI->second, L);
2524 // We're done analyzing this loop; release all the state we built up for it.
2525 IVUsesByStride.clear();
2526 IVsByStride.clear();
2527 StrideOrder.clear();
2529 // Clean up after ourselves
2530 if (!DeadInsts.empty()) {
2531 DeleteTriviallyDeadInstructions();
2533 BasicBlock::iterator I = L->getHeader()->begin();
2534 while (PHINode *PN = dyn_cast<PHINode>(I++)) {
2535 // At this point, we know that we have killed one or more IV users.
2536 // It is worth checking to see if the cannonical indvar is also
2537 // dead, so that we can remove it as well.
2539 // We can remove a PHI if it is on a cycle in the def-use graph
2540 // where each node in the cycle has degree one, i.e. only one use,
2541 // and is an instruction with no side effects.
2543 // FIXME: this needs to eliminate an induction variable even if it's being
2544 // compared against some value to decide loop termination.
2545 if (!PN->hasOneUse())
2548 SmallPtrSet<PHINode *, 4> PHIs;
2549 for (Instruction *J = dyn_cast<Instruction>(*PN->use_begin());
2550 J && J->hasOneUse() && !J->mayWriteToMemory();
2551 J = dyn_cast<Instruction>(*J->use_begin())) {
2552 // If we find the original PHI, we've discovered a cycle.
2554 // Break the cycle and mark the PHI for deletion.
2555 SE->deleteValueFromRecords(PN);
2556 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
2557 DeadInsts.push_back(PN);
2561 // If we find a PHI more than once, we're on a cycle that
2562 // won't prove fruitful.
2563 if (isa<PHINode>(J) && !PHIs.insert(cast<PHINode>(J)))
2567 DeleteTriviallyDeadInstructions();