1 //===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Nate Begeman and is distributed under the
6 // University of Illinois Open Source 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. This is
12 // accomplished by creating a new Value to hold the initial value of the array
13 // access for the first iteration, and then creating a new GEP instruction in
14 // the loop to increment the value by the appropriate amount.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "loop-reduce"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Type.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/LoopPass.h"
27 #include "llvm/Analysis/ScalarEvolutionExpander.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Compiler.h"
36 #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");
49 /// IVStrideUse - Keep track of one use of a strided induction variable, where
50 /// the stride is stored externally. The Offset member keeps track of the
51 /// offset from the IV, User is the actual user of the operand, and 'Operand'
52 /// is the operand # of the User that is the use.
53 struct VISIBILITY_HIDDEN IVStrideUse {
56 Value *OperandValToReplace;
58 // isUseOfPostIncrementedValue - True if this should use the
59 // post-incremented version of this IV, not the preincremented version.
60 // This can only be set in special cases, such as the terminating setcc
61 // instruction for a loop or uses dominated by the loop.
62 bool isUseOfPostIncrementedValue;
64 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
65 : Offset(Offs), User(U), OperandValToReplace(O),
66 isUseOfPostIncrementedValue(false) {}
69 /// IVUsersOfOneStride - This structure keeps track of all instructions that
70 /// have an operand that is based on the trip count multiplied by some stride.
71 /// The stride for all of these users is common and kept external to this
73 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
74 /// Users - Keep track of all of the users of this stride as well as the
75 /// initial value and the operand that uses the IV.
76 std::vector<IVStrideUse> Users;
78 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
79 Users.push_back(IVStrideUse(Offset, User, Operand));
83 /// IVInfo - This structure keeps track of one IV expression inserted during
84 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
85 /// well as the PHI node and increment value created for rewrite.
86 struct VISIBILITY_HIDDEN IVExpr {
93 : Stride(SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)),
94 Base (SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)) {}
95 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
97 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
100 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
101 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
102 struct VISIBILITY_HIDDEN IVsOfOneStride {
103 std::vector<IVExpr> IVs;
105 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
107 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
111 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
115 const TargetData *TD;
116 const Type *UIntPtrTy;
119 /// IVUsesByStride - Keep track of all uses of induction variables that we
120 /// are interested in. The key of the map is the stride of the access.
121 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
123 /// IVsByStride - Keep track of all IVs that have been inserted for a
124 /// particular stride.
125 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
127 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
128 /// We use this to iterate over the IVUsesByStride collection without being
129 /// dependent on random ordering of pointers in the process.
130 std::vector<SCEVHandle> StrideOrder;
132 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
133 /// of the casted version of each value. This is accessed by
134 /// getCastedVersionOf.
135 std::map<Value*, Value*> CastedPointers;
137 /// DeadInsts - Keep track of instructions we may have made dead, so that
138 /// we can remove them after we are done working.
139 std::set<Instruction*> DeadInsts;
141 /// TLI - Keep a pointer of a TargetLowering to consult for determining
142 /// transformation profitability.
143 const TargetLowering *TLI;
146 LoopStrengthReduce(const TargetLowering *tli = NULL)
150 bool runOnLoop(Loop *L, LPPassManager &LPM);
152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153 // We split critical edges, so we change the CFG. However, we do update
154 // many analyses if they are around.
155 AU.addPreservedID(LoopSimplifyID);
156 AU.addPreserved<LoopInfo>();
157 AU.addPreserved<DominatorSet>();
158 AU.addPreserved<ETForest>();
159 AU.addPreserved<ImmediateDominators>();
160 AU.addPreserved<DominanceFrontier>();
161 AU.addPreserved<DominatorTree>();
163 AU.addRequiredID(LoopSimplifyID);
164 AU.addRequired<LoopInfo>();
165 AU.addRequired<ETForest>();
166 AU.addRequired<TargetData>();
167 AU.addRequired<ScalarEvolution>();
170 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
172 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
174 bool AddUsersIfInteresting(Instruction *I, Loop *L,
175 std::set<Instruction*> &Processed);
176 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
178 void OptimizeIndvars(Loop *L);
180 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*,
181 const std::vector<BasedUser>& UsersToProcess);
183 bool ValidStride(int64_t, const std::vector<BasedUser>& UsersToProcess);
185 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
186 IVUsersOfOneStride &Uses,
187 Loop *L, bool isOnlyStride);
188 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
190 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
193 LoopPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
194 return new LoopStrengthReduce(TLI);
197 /// getCastedVersionOf - Return the specified value casted to uintptr_t. This
198 /// assumes that the Value* V is of integer or pointer type only.
200 Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
202 if (V->getType() == UIntPtrTy) return V;
203 if (Constant *CB = dyn_cast<Constant>(V))
204 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
206 Value *&New = CastedPointers[V];
209 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
210 DeadInsts.insert(cast<Instruction>(New));
215 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
216 /// specified set are trivially dead, delete them and see if this makes any of
217 /// their operands subsequently dead.
218 void LoopStrengthReduce::
219 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
220 while (!Insts.empty()) {
221 Instruction *I = *Insts.begin();
222 Insts.erase(Insts.begin());
223 if (isInstructionTriviallyDead(I)) {
224 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
225 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
227 SE->deleteInstructionFromRecords(I);
228 I->eraseFromParent();
235 /// GetExpressionSCEV - Compute and return the SCEV for the specified
237 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
238 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
239 // If this is a GEP that SE doesn't know about, compute it now and insert it.
240 // If this is not a GEP, or if we have already done this computation, just let
242 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
243 if (!GEP || SE->hasSCEV(GEP))
244 return SE->getSCEV(Exp);
246 // Analyze all of the subscripts of this getelementptr instruction, looking
247 // for uses that are determined by the trip count of L. First, skip all
248 // operands the are not dependent on the IV.
250 // Build up the base expression. Insert an LLVM cast of the pointer to
252 SCEVHandle GEPVal = SCEVUnknown::get(
253 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
255 gep_type_iterator GTI = gep_type_begin(GEP);
257 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
258 // If this is a use of a recurrence that we can analyze, and it comes before
259 // Op does in the GEP operand list, we will handle this when we process this
261 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
262 const StructLayout *SL = TD->getStructLayout(STy);
263 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
264 uint64_t Offset = SL->getElementOffset(Idx);
265 GEPVal = SCEVAddExpr::get(GEPVal,
266 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
268 unsigned GEPOpiBits =
269 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
270 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
271 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
272 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
273 Instruction::BitCast));
274 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
275 SCEVHandle Idx = SE->getSCEV(OpVal);
277 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
279 Idx = SCEVMulExpr::get(Idx,
280 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
282 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
286 SE->setSCEV(GEP, GEPVal);
290 /// getSCEVStartAndStride - Compute the start and stride of this expression,
291 /// returning false if the expression is not a start/stride pair, or true if it
292 /// is. The stride must be a loop invariant expression, but the start may be
293 /// a mix of loop invariant and loop variant expressions.
294 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
295 SCEVHandle &Start, SCEVHandle &Stride) {
296 SCEVHandle TheAddRec = Start; // Initialize to zero.
298 // If the outer level is an AddExpr, the operands are all start values except
299 // for a nested AddRecExpr.
300 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
301 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
302 if (SCEVAddRecExpr *AddRec =
303 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
304 if (AddRec->getLoop() == L)
305 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
307 return false; // Nested IV of some sort?
309 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
312 } else if (isa<SCEVAddRecExpr>(SH)) {
315 return false; // not analyzable.
318 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
319 if (!AddRec || AddRec->getLoop() != L) return false;
321 // FIXME: Generalize to non-affine IV's.
322 if (!AddRec->isAffine()) return false;
324 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
326 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
327 DOUT << "[" << L->getHeader()->getName()
328 << "] Variable stride: " << *AddRec << "\n";
330 Stride = AddRec->getOperand(1);
334 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
335 /// and now we need to decide whether the user should use the preinc or post-inc
336 /// value. If this user should use the post-inc version of the IV, return true.
338 /// Choosing wrong here can break dominance properties (if we choose to use the
339 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
340 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
341 /// should use the post-inc value).
342 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
343 Loop *L, ETForest *EF, Pass *P) {
344 // If the user is in the loop, use the preinc value.
345 if (L->contains(User->getParent())) return false;
347 BasicBlock *LatchBlock = L->getLoopLatch();
349 // Ok, the user is outside of the loop. If it is dominated by the latch
350 // block, use the post-inc value.
351 if (EF->dominates(LatchBlock, User->getParent()))
354 // There is one case we have to be careful of: PHI nodes. These little guys
355 // can live in blocks that do not dominate the latch block, but (since their
356 // uses occur in the predecessor block, not the block the PHI lives in) should
357 // still use the post-inc value. Check for this case now.
358 PHINode *PN = dyn_cast<PHINode>(User);
359 if (!PN) return false; // not a phi, not dominated by latch block.
361 // Look at all of the uses of IV by the PHI node. If any use corresponds to
362 // a block that is not dominated by the latch block, give up and use the
363 // preincremented value.
364 unsigned NumUses = 0;
365 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
366 if (PN->getIncomingValue(i) == IV) {
368 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
372 // Okay, all uses of IV by PN are in predecessor blocks that really are
373 // dominated by the latch block. Split the critical edges and use the
374 // post-incremented value.
375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
376 if (PN->getIncomingValue(i) == IV) {
377 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
379 // Splitting the critical edge can reduce the number of entries in this
381 e = PN->getNumIncomingValues();
382 if (--NumUses == 0) break;
390 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
391 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
392 /// return true. Otherwise, return false.
393 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
394 std::set<Instruction*> &Processed) {
395 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
396 return false; // Void and FP expressions cannot be reduced.
397 if (!Processed.insert(I).second)
398 return true; // Instruction already handled.
400 // Get the symbolic expression for this instruction.
401 SCEVHandle ISE = GetExpressionSCEV(I, L);
402 if (isa<SCEVCouldNotCompute>(ISE)) return false;
404 // Get the start and stride for this expression.
405 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
406 SCEVHandle Stride = Start;
407 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
408 return false; // Non-reducible symbolic expression, bail out.
410 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;) {
411 Instruction *User = cast<Instruction>(*UI);
413 // Increment iterator now because IVUseShouldUsePostIncValue may remove
414 // User from the list of I users.
417 // Do not infinitely recurse on PHI nodes.
418 if (isa<PHINode>(User) && Processed.count(User))
421 // If this is an instruction defined in a nested loop, or outside this loop,
422 // don't recurse into it.
423 bool AddUserToIVUsers = false;
424 if (LI->getLoopFor(User->getParent()) != L) {
425 DOUT << "FOUND USER in other loop: " << *User
426 << " OF SCEV: " << *ISE << "\n";
427 AddUserToIVUsers = true;
428 } else if (!AddUsersIfInteresting(User, L, Processed)) {
429 DOUT << "FOUND USER: " << *User
430 << " OF SCEV: " << *ISE << "\n";
431 AddUserToIVUsers = true;
434 if (AddUserToIVUsers) {
435 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
436 if (StrideUses.Users.empty()) // First occurance of this stride?
437 StrideOrder.push_back(Stride);
439 // Okay, we found a user that we cannot reduce. Analyze the instruction
440 // and decide what to do with it. If we are a use inside of the loop, use
441 // the value before incrementation, otherwise use it after incrementation.
442 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
443 // The value used will be incremented by the stride more than we are
444 // expecting, so subtract this off.
445 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
446 StrideUses.addUser(NewStart, User, I);
447 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
448 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
450 StrideUses.addUser(Start, User, I);
458 /// BasedUser - For a particular base value, keep information about how we've
459 /// partitioned the expression so far.
461 /// Base - The Base value for the PHI node that needs to be inserted for
462 /// this use. As the use is processed, information gets moved from this
463 /// field to the Imm field (below). BasedUser values are sorted by this
467 /// Inst - The instruction using the induction variable.
470 /// OperandValToReplace - The operand value of Inst to replace with the
472 Value *OperandValToReplace;
474 /// Imm - The immediate value that should be added to the base immediately
475 /// before Inst, because it will be folded into the imm field of the
479 /// EmittedBase - The actual value* to use for the base value of this
480 /// operation. This is null if we should just use zero so far.
483 // isUseOfPostIncrementedValue - True if this should use the
484 // post-incremented version of this IV, not the preincremented version.
485 // This can only be set in special cases, such as the terminating setcc
486 // instruction for a loop and uses outside the loop that are dominated by
488 bool isUseOfPostIncrementedValue;
490 BasedUser(IVStrideUse &IVSU)
491 : Base(IVSU.Offset), Inst(IVSU.User),
492 OperandValToReplace(IVSU.OperandValToReplace),
493 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
494 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
496 // Once we rewrite the code to insert the new IVs we want, update the
497 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
499 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
500 SCEVExpander &Rewriter, Loop *L,
503 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
504 SCEVExpander &Rewriter,
505 Instruction *IP, Loop *L);
510 void BasedUser::dump() const {
511 cerr << " Base=" << *Base;
512 cerr << " Imm=" << *Imm;
514 cerr << " EB=" << *EmittedBase;
516 cerr << " Inst: " << *Inst;
519 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
520 SCEVExpander &Rewriter,
521 Instruction *IP, Loop *L) {
522 // Figure out where we *really* want to insert this code. In particular, if
523 // the user is inside of a loop that is nested inside of L, we really don't
524 // want to insert this expression before the user, we'd rather pull it out as
525 // many loops as possible.
526 LoopInfo &LI = Rewriter.getLoopInfo();
527 Instruction *BaseInsertPt = IP;
529 // Figure out the most-nested loop that IP is in.
530 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
532 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
533 // the preheader of the outer-most loop where NewBase is not loop invariant.
534 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
535 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
536 InsertLoop = InsertLoop->getParentLoop();
539 // If there is no immediate value, skip the next part.
540 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
541 if (SC->getValue()->isZero())
542 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
543 OperandValToReplace->getType());
545 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
547 // Always emit the immediate (if non-zero) into the same block as the user.
548 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
549 return Rewriter.expandCodeFor(NewValSCEV, IP,
550 OperandValToReplace->getType());
554 // Once we rewrite the code to insert the new IVs we want, update the
555 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
557 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
558 SCEVExpander &Rewriter,
560 if (!isa<PHINode>(Inst)) {
561 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
562 // Replace the use of the operand Value with the new Phi we just created.
563 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
564 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
568 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
569 // expression into each operand block that uses it. Note that PHI nodes can
570 // have multiple entries for the same predecessor. We use a map to make sure
571 // that a PHI node only has a single Value* for each predecessor (which also
572 // prevents us from inserting duplicate code in some blocks).
573 std::map<BasicBlock*, Value*> InsertedCode;
574 PHINode *PN = cast<PHINode>(Inst);
575 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
576 if (PN->getIncomingValue(i) == OperandValToReplace) {
577 // If this is a critical edge, split the edge so that we do not insert the
578 // code on all predecessor/successor paths. We do this unless this is the
579 // canonical backedge for this loop, as this can make some inserted code
580 // be in an illegal position.
581 BasicBlock *PHIPred = PN->getIncomingBlock(i);
582 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
583 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
585 // First step, split the critical edge.
586 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
588 // Next step: move the basic block. In particular, if the PHI node
589 // is outside of the loop, and PredTI is in the loop, we want to
590 // move the block to be immediately before the PHI block, not
591 // immediately after PredTI.
592 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
593 BasicBlock *NewBB = PN->getIncomingBlock(i);
594 NewBB->moveBefore(PN->getParent());
597 // Splitting the edge can reduce the number of PHI entries we have.
598 e = PN->getNumIncomingValues();
601 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
603 // Insert the code into the end of the predecessor block.
604 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
605 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
608 // Replace the use of the operand Value with the new Phi we just created.
609 PN->setIncomingValue(i, Code);
613 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
617 /// isTargetConstant - Return true if the following can be referenced by the
618 /// immediate field of a target instruction.
619 static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
620 const TargetLowering *TLI) {
621 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
622 int64_t VC = SC->getValue()->getSExtValue();
624 return TLI->isLegalAddressImmediate(VC, UseTy);
626 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
627 return (VC > -(1 << 16) && VC < (1 << 16)-1);
630 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
631 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
632 if (CE->getOpcode() == Instruction::PtrToInt) {
633 Constant *Op0 = CE->getOperand(0);
634 if (isa<GlobalValue>(Op0) && TLI &&
635 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
641 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
642 /// loop varying to the Imm operand.
643 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
645 if (Val->isLoopInvariant(L)) return; // Nothing to do.
647 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
648 std::vector<SCEVHandle> NewOps;
649 NewOps.reserve(SAE->getNumOperands());
651 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
652 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
653 // If this is a loop-variant expression, it must stay in the immediate
654 // field of the expression.
655 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
657 NewOps.push_back(SAE->getOperand(i));
661 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
663 Val = SCEVAddExpr::get(NewOps);
664 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
665 // Try to pull immediates out of the start value of nested addrec's.
666 SCEVHandle Start = SARE->getStart();
667 MoveLoopVariantsToImediateField(Start, Imm, L);
669 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
671 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
673 // Otherwise, all of Val is variant, move the whole thing over.
674 Imm = SCEVAddExpr::get(Imm, Val);
675 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
680 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
681 /// that can fit into the immediate field of instructions in the target.
682 /// Accumulate these immediate values into the Imm value.
683 static void MoveImmediateValues(const TargetLowering *TLI,
685 SCEVHandle &Val, SCEVHandle &Imm,
686 bool isAddress, Loop *L) {
687 const Type *UseTy = User->getType();
688 if (StoreInst *SI = dyn_cast<StoreInst>(User))
689 UseTy = SI->getOperand(0)->getType();
691 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
692 std::vector<SCEVHandle> NewOps;
693 NewOps.reserve(SAE->getNumOperands());
695 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
696 SCEVHandle NewOp = SAE->getOperand(i);
697 MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L);
699 if (!NewOp->isLoopInvariant(L)) {
700 // If this is a loop-variant expression, it must stay in the immediate
701 // field of the expression.
702 Imm = SCEVAddExpr::get(Imm, NewOp);
704 NewOps.push_back(NewOp);
709 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
711 Val = SCEVAddExpr::get(NewOps);
713 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
714 // Try to pull immediates out of the start value of nested addrec's.
715 SCEVHandle Start = SARE->getStart();
716 MoveImmediateValues(TLI, User, Start, Imm, isAddress, L);
718 if (Start != SARE->getStart()) {
719 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
721 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
724 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
725 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
726 if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
727 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
729 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
730 SCEVHandle NewOp = SME->getOperand(1);
731 MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L);
733 // If we extracted something out of the subexpressions, see if we can
735 if (NewOp != SME->getOperand(1)) {
736 // Scale SubImm up by "8". If the result is a target constant, we are
738 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
739 if (isTargetConstant(SubImm, UseTy, TLI)) {
740 // Accumulate the immediate.
741 Imm = SCEVAddExpr::get(Imm, SubImm);
743 // Update what is left of 'Val'.
744 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
751 // Loop-variant expressions must stay in the immediate field of the
753 if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
754 !Val->isLoopInvariant(L)) {
755 Imm = SCEVAddExpr::get(Imm, Val);
756 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
760 // Otherwise, no immediates to move.
764 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
765 /// added together. This is used to reassociate common addition subexprs
766 /// together for maximal sharing when rewriting bases.
767 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
769 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
770 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
771 SeparateSubExprs(SubExprs, AE->getOperand(j));
772 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
773 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
774 if (SARE->getOperand(0) == Zero) {
775 SubExprs.push_back(Expr);
777 // Compute the addrec with zero as its base.
778 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
779 Ops[0] = Zero; // Start with zero base.
780 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
783 SeparateSubExprs(SubExprs, SARE->getOperand(0));
785 } else if (!isa<SCEVConstant>(Expr) ||
786 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
788 SubExprs.push_back(Expr);
793 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
794 /// removing any common subexpressions from it. Anything truly common is
795 /// removed, accumulated, and returned. This looks for things like (a+b+c) and
796 /// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
798 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
799 unsigned NumUses = Uses.size();
801 // Only one use? Use its base, regardless of what it is!
802 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
803 SCEVHandle Result = Zero;
805 std::swap(Result, Uses[0].Base);
809 // To find common subexpressions, count how many of Uses use each expression.
810 // If any subexpressions are used Uses.size() times, they are common.
811 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
813 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
814 // order we see them.
815 std::vector<SCEVHandle> UniqueSubExprs;
817 std::vector<SCEVHandle> SubExprs;
818 for (unsigned i = 0; i != NumUses; ++i) {
819 // If the base is zero (which is common), return zero now, there are no
821 if (Uses[i].Base == Zero) return Zero;
823 // Split the expression into subexprs.
824 SeparateSubExprs(SubExprs, Uses[i].Base);
825 // Add one to SubExpressionUseCounts for each subexpr present.
826 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
827 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
828 UniqueSubExprs.push_back(SubExprs[j]);
832 // Now that we know how many times each is used, build Result. Iterate over
833 // UniqueSubexprs so that we have a stable ordering.
834 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
835 std::map<SCEVHandle, unsigned>::iterator I =
836 SubExpressionUseCounts.find(UniqueSubExprs[i]);
837 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
838 if (I->second == NumUses) { // Found CSE!
839 Result = SCEVAddExpr::get(Result, I->first);
841 // Remove non-cse's from SubExpressionUseCounts.
842 SubExpressionUseCounts.erase(I);
846 // If we found no CSE's, return now.
847 if (Result == Zero) return Result;
849 // Otherwise, remove all of the CSE's we found from each of the base values.
850 for (unsigned i = 0; i != NumUses; ++i) {
851 // Split the expression into subexprs.
852 SeparateSubExprs(SubExprs, Uses[i].Base);
854 // Remove any common subexpressions.
855 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
856 if (SubExpressionUseCounts.count(SubExprs[j])) {
857 SubExprs.erase(SubExprs.begin()+j);
861 // Finally, the non-shared expressions together.
862 if (SubExprs.empty())
865 Uses[i].Base = SCEVAddExpr::get(SubExprs);
872 /// isZero - returns true if the scalar evolution expression is zero.
874 static bool isZero(SCEVHandle &V) {
875 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
876 return SC->getValue()->isZero();
880 /// ValidStride - Check whether the given Scale is valid for all loads and
881 /// stores in UsersToProcess. Pulled into a function to avoid disturbing the
882 /// sensibilities of those who dislike goto's.
884 bool LoopStrengthReduce::ValidStride(int64_t Scale,
885 const std::vector<BasedUser>& UsersToProcess) {
887 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
888 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
889 Imm = SC->getValue()->getSExtValue();
892 if (!TLI->isLegalAddressScaleAndImm(Scale, Imm,
893 UsersToProcess[i].Inst->getType()))
899 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
900 /// of a previous stride and it is a legal value for the target addressing
901 /// mode scale component. This allows the users of this stride to be rewritten
902 /// as prev iv * factor. It returns 0 if no reuse is possible.
903 unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
904 IVExpr &IV, const Type *Ty,
905 const std::vector<BasedUser>& UsersToProcess) {
908 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
909 int64_t SInt = SC->getValue()->getSExtValue();
910 if (SInt == 1) return 0;
912 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
913 SE = IVsByStride.end(); SI != SE; ++SI) {
914 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
915 if (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0)
917 int64_t Scale = SInt / SSInt;
918 // Check that this stride is valid for all the types used for loads and
919 // stores; if it can be used for some and not others, we might as well use
920 // the original stride everywhere, since we have to create the IV for it
922 if (ValidStride(Scale, UsersToProcess))
923 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
924 IE = SI->second.IVs.end(); II != IE; ++II)
925 // FIXME: Only handle base == 0 for now.
926 // Only reuse previous IV if it would not require a type conversion.
927 if (isZero(II->Base) && II->Base->getType() == Ty) {
936 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
937 /// returns true if Val's isUseOfPostIncrementedValue is true.
938 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
939 return Val.isUseOfPostIncrementedValue;
942 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
943 /// stride of IV. All of the users may have different starting values, and this
944 /// may not be the only stride (we know it is if isOnlyStride is true).
945 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
946 IVUsersOfOneStride &Uses,
949 // Transform our list of users and offsets to a bit more complex table. In
950 // this new vector, each 'BasedUser' contains 'Base' the base of the
951 // strided accessas well as the old information from Uses. We progressively
952 // move information from the Base field to the Imm field, until we eventually
953 // have the full access expression to rewrite the use.
954 std::vector<BasedUser> UsersToProcess;
955 UsersToProcess.reserve(Uses.Users.size());
956 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
957 UsersToProcess.push_back(Uses.Users[i]);
959 // Move any loop invariant operands from the offset field to the immediate
960 // field of the use, so that we don't try to use something before it is
962 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
963 UsersToProcess.back().Imm, L);
964 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
965 "Base value is not loop invariant!");
968 // We now have a whole bunch of uses of like-strided induction variables, but
969 // they might all have different bases. We want to emit one PHI node for this
970 // stride which we fold as many common expressions (between the IVs) into as
971 // possible. Start by identifying the common expressions in the base values
972 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
973 // "A+B"), emit it to the preheader, then remove the expression from the
974 // UsersToProcess base values.
975 SCEVHandle CommonExprs =
976 RemoveCommonExpressionsFromUseBases(UsersToProcess);
978 // Next, figure out what we can represent in the immediate fields of
979 // instructions. If we can represent anything there, move it to the imm
980 // fields of the BasedUsers. We do this so that it increases the commonality
981 // of the remaining uses.
982 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
983 // If the user is not in the current loop, this means it is using the exit
984 // value of the IV. Do not put anything in the base, make sure it's all in
985 // the immediate field to allow as much factoring as possible.
986 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
987 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
988 UsersToProcess[i].Base);
989 UsersToProcess[i].Base =
990 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
993 // Addressing modes can be folded into loads and stores. Be careful that
994 // the store is through the expression, not of the expression though.
995 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
996 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
997 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1000 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1001 UsersToProcess[i].Imm, isAddress, L);
1005 // Check if it is possible to reuse a IV with stride that is factor of this
1006 // stride. And the multiple is a number that can be encoded in the scale
1007 // field of the target addressing mode. And we will have a valid
1008 // instruction after this substition, including the immediate field, if any.
1009 PHINode *NewPHI = NULL;
1012 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
1013 CommonExprs->getType(),
1015 if (RewriteFactor != 0) {
1016 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1017 << " and BASE " << *ReuseIV.Base << " :\n";
1018 NewPHI = ReuseIV.PHI;
1019 IncV = ReuseIV.IncV;
1022 // Now that we know what we need to do, insert the PHI node itself.
1024 DOUT << "INSERTING IV of STRIDE " << *Stride << " and BASE "
1025 << *CommonExprs << " :\n";
1027 SCEVExpander Rewriter(*SE, *LI);
1028 SCEVExpander PreheaderRewriter(*SE, *LI);
1030 BasicBlock *Preheader = L->getLoopPreheader();
1031 Instruction *PreInsertPt = Preheader->getTerminator();
1032 Instruction *PhiInsertBefore = L->getHeader()->begin();
1034 BasicBlock *LatchBlock = L->getLoopLatch();
1036 const Type *ReplacedTy = CommonExprs->getType();
1038 // Emit the initial base value into the loop preheader.
1040 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1043 if (RewriteFactor == 0) {
1044 // Create a new Phi for this base, and stick it in the loop header.
1045 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1048 // Add common base to the new Phi node.
1049 NewPHI->addIncoming(CommonBaseV, Preheader);
1051 // Insert the stride into the preheader.
1052 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1054 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
1056 // Emit the increment of the base value before the terminator of the loop
1057 // latch block, and add it to the Phi node.
1058 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1059 SCEVUnknown::get(StrideV));
1061 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1063 IncV->setName(NewPHI->getName()+".inc");
1064 NewPHI->addIncoming(IncV, LatchBlock);
1066 // Remember this in case a later stride is multiple of this.
1067 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
1069 Constant *C = dyn_cast<Constant>(CommonBaseV);
1071 (!C->isNullValue() &&
1072 !isTargetConstant(SCEVUnknown::get(CommonBaseV), ReplacedTy, TLI)))
1073 // We want the common base emitted into the preheader! This is just
1074 // using cast as a copy so BitCast (no-op cast) is appropriate
1075 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1076 "commonbase", PreInsertPt);
1079 // We want to emit code for users inside the loop first. To do this, we
1080 // rearrange BasedUser so that the entries at the end have
1081 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1082 // vector (so we handle them first).
1083 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1084 PartitionByIsUseOfPostIncrementedValue);
1086 // Sort this by base, so that things with the same base are handled
1087 // together. By partitioning first and stable-sorting later, we are
1088 // guaranteed that within each base we will pop off users from within the
1089 // loop before users outside of the loop with a particular base.
1091 // We would like to use stable_sort here, but we can't. The problem is that
1092 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1093 // we don't have anything to do a '<' comparison on. Because we think the
1094 // number of uses is small, do a horrible bubble sort which just relies on
1096 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1097 // Get a base value.
1098 SCEVHandle Base = UsersToProcess[i].Base;
1100 // Compact everything with this base to be consequetive with this one.
1101 for (unsigned j = i+1; j != e; ++j) {
1102 if (UsersToProcess[j].Base == Base) {
1103 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1109 // Process all the users now. This outer loop handles all bases, the inner
1110 // loop handles all users of a particular base.
1111 while (!UsersToProcess.empty()) {
1112 SCEVHandle Base = UsersToProcess.back().Base;
1114 DOUT << " INSERTING code for BASE = " << *Base << ":\n";
1116 // Emit the code for Base into the preheader.
1117 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1120 // If BaseV is a constant other than 0, make sure that it gets inserted into
1121 // the preheader, instead of being forward substituted into the uses. We do
1122 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1124 if (Constant *C = dyn_cast<Constant>(BaseV)) {
1125 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
1126 // We want this constant emitted into the preheader! This is just
1127 // using cast as a copy so BitCast (no-op cast) is appropriate
1128 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1133 // Emit the code to add the immediate offset to the Phi value, just before
1134 // the instructions that we identified as using this stride and base.
1136 // FIXME: Use emitted users to emit other users.
1137 BasedUser &User = UsersToProcess.back();
1139 // If this instruction wants to use the post-incremented value, move it
1140 // after the post-inc and use its value instead of the PHI.
1141 Value *RewriteOp = NewPHI;
1142 if (User.isUseOfPostIncrementedValue) {
1145 // If this user is in the loop, make sure it is the last thing in the
1146 // loop to ensure it is dominated by the increment.
1147 if (L->contains(User.Inst->getParent()))
1148 User.Inst->moveBefore(LatchBlock->getTerminator());
1150 if (RewriteOp->getType() != ReplacedTy) {
1151 Instruction::CastOps opcode = Instruction::Trunc;
1152 if (ReplacedTy->getPrimitiveSizeInBits() ==
1153 RewriteOp->getType()->getPrimitiveSizeInBits())
1154 opcode = Instruction::BitCast;
1155 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1158 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1160 // Clear the SCEVExpander's expression map so that we are guaranteed
1161 // to have the code emitted where we expect it.
1164 // If we are reusing the iv, then it must be multiplied by a constant
1165 // factor take advantage of addressing mode scale component.
1166 if (RewriteFactor != 0) {
1168 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
1169 RewriteExpr->getType()),
1172 // The common base is emitted in the loop preheader. But since we
1173 // are reusing an IV, it has not been used to initialize the PHI node.
1174 // Add it to the expression used to rewrite the uses.
1175 if (!isa<ConstantInt>(CommonBaseV) ||
1176 !cast<ConstantInt>(CommonBaseV)->isZero())
1177 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1178 SCEVUnknown::get(CommonBaseV));
1181 // Now that we know what we need to do, insert code before User for the
1182 // immediate and any loop-variant expressions.
1183 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
1184 // Add BaseV to the PHI value if needed.
1185 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
1187 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
1189 // Mark old value we replaced as possibly dead, so that it is elminated
1190 // if we just replaced the last use of that value.
1191 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
1193 UsersToProcess.pop_back();
1196 // If there are any more users to process with the same base, process them
1197 // now. We sorted by base above, so we just have to check the last elt.
1198 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1199 // TODO: Next, find out which base index is the most common, pull it out.
1202 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1203 // different starting values, into different PHIs.
1206 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1207 // uses in the loop, look to see if we can eliminate some, in favor of using
1208 // common indvars for the different uses.
1209 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1210 // TODO: implement optzns here.
1212 // Finally, get the terminating condition for the loop if possible. If we
1213 // can, we want to change it to use a post-incremented version of its
1214 // induction variable, to allow coalescing the live ranges for the IV into
1215 // one register value.
1216 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1217 BasicBlock *Preheader = L->getLoopPreheader();
1218 BasicBlock *LatchBlock =
1219 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1220 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1221 if (!TermBr || TermBr->isUnconditional() ||
1222 !isa<ICmpInst>(TermBr->getCondition()))
1224 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1226 // Search IVUsesByStride to find Cond's IVUse if there is one.
1227 IVStrideUse *CondUse = 0;
1228 const SCEVHandle *CondStride = 0;
1230 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1232 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1233 IVUsesByStride.find(StrideOrder[Stride]);
1234 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1236 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1237 E = SI->second.Users.end(); UI != E; ++UI)
1238 if (UI->User == Cond) {
1240 CondStride = &SI->first;
1241 // NOTE: we could handle setcc instructions with multiple uses here, but
1242 // InstCombine does it as well for simple uses, it's not clear that it
1243 // occurs enough in real life to handle.
1247 if (!CondUse) return; // setcc doesn't use the IV.
1249 // It's possible for the setcc instruction to be anywhere in the loop, and
1250 // possible for it to have multiple users. If it is not immediately before
1251 // the latch block branch, move it.
1252 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1253 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1254 Cond->moveBefore(TermBr);
1256 // Otherwise, clone the terminating condition and insert into the loopend.
1257 Cond = cast<ICmpInst>(Cond->clone());
1258 Cond->setName(L->getHeader()->getName() + ".termcond");
1259 LatchBlock->getInstList().insert(TermBr, Cond);
1261 // Clone the IVUse, as the old use still exists!
1262 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1263 CondUse->OperandValToReplace);
1264 CondUse = &IVUsesByStride[*CondStride].Users.back();
1268 // If we get to here, we know that we can transform the setcc instruction to
1269 // use the post-incremented version of the IV, allowing us to coalesce the
1270 // live ranges for the IV correctly.
1271 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
1272 CondUse->isUseOfPostIncrementedValue = true;
1276 // Constant strides come first which in turns are sorted by their absolute
1277 // values. If absolute values are the same, then positive strides comes first.
1279 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1280 struct StrideCompare {
1281 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1282 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1283 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1285 int64_t LV = LHSC->getValue()->getSExtValue();
1286 int64_t RV = RHSC->getValue()->getSExtValue();
1287 uint64_t ALV = (LV < 0) ? -LV : LV;
1288 uint64_t ARV = (RV < 0) ? -RV : RV;
1294 return (LHSC && !RHSC);
1299 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
1301 LI = &getAnalysis<LoopInfo>();
1302 EF = &getAnalysis<ETForest>();
1303 SE = &getAnalysis<ScalarEvolution>();
1304 TD = &getAnalysis<TargetData>();
1305 UIntPtrTy = TD->getIntPtrType();
1307 // Find all uses of induction variables in this loop, and catagorize
1308 // them by stride. Start by finding all of the PHI nodes in the header for
1309 // this loop. If they are induction variables, inspect their uses.
1310 std::set<Instruction*> Processed; // Don't reprocess instructions.
1311 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1312 AddUsersIfInteresting(I, L, Processed);
1314 // If we have nothing to do, return.
1315 if (IVUsesByStride.empty()) return false;
1317 // Optimize induction variables. Some indvar uses can be transformed to use
1318 // strides that will be needed for other purposes. A common example of this
1319 // is the exit test for the loop, which can often be rewritten to use the
1320 // computation of some other indvar to decide when to terminate the loop.
1324 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1325 // doing computation in byte values, promote to 32-bit values if safe.
1327 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1328 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1329 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1330 // to be careful that IV's are all the same type. Only works for intptr_t
1333 // If we only have one stride, we can more aggressively eliminate some things.
1334 bool HasOneStride = IVUsesByStride.size() == 1;
1337 DOUT << "\nLSR on ";
1341 // IVsByStride keeps IVs for one particular loop.
1342 IVsByStride.clear();
1344 // Sort the StrideOrder so we process larger strides first.
1345 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1347 // Note: this processes each stride/type pair individually. All users passed
1348 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1349 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1350 // This extra layer of indirection makes the ordering of strides deterministic
1351 // - not dependent on map order.
1352 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1353 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1354 IVUsesByStride.find(StrideOrder[Stride]);
1355 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1356 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1359 // Clean up after ourselves
1360 if (!DeadInsts.empty()) {
1361 DeleteTriviallyDeadInstructions(DeadInsts);
1363 BasicBlock::iterator I = L->getHeader()->begin();
1365 while ((PN = dyn_cast<PHINode>(I))) {
1366 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1368 // At this point, we know that we have killed one or more GEP
1369 // instructions. It is worth checking to see if the cann indvar is also
1370 // dead, so that we can remove it as well. The requirements for the cann
1371 // indvar to be considered dead are:
1372 // 1. the cann indvar has one use
1373 // 2. the use is an add instruction
1374 // 3. the add has one use
1375 // 4. the add is used by the cann indvar
1376 // If all four cases above are true, then we can remove both the add and
1378 // FIXME: this needs to eliminate an induction variable even if it's being
1379 // compared against some value to decide loop termination.
1380 if (PN->hasOneUse()) {
1381 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1382 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1383 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
1384 DeadInsts.insert(BO);
1385 // Break the cycle, then delete the PHI.
1386 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1387 SE->deleteInstructionFromRecords(PN);
1388 PN->eraseFromParent();
1393 DeleteTriviallyDeadInstructions(DeadInsts);
1396 CastedPointers.clear();
1397 IVUsesByStride.clear();
1398 StrideOrder.clear();