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 // Pointer to pointer bitcast instructions return the same value as their
240 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Exp)) {
241 if (SE->hasSCEV(BCI) || !isa<Instruction>(BCI->getOperand(0)))
242 return SE->getSCEV(BCI);
243 SCEVHandle R = GetExpressionSCEV(cast<Instruction>(BCI->getOperand(0)), L);
248 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
249 // If this is a GEP that SE doesn't know about, compute it now and insert it.
250 // If this is not a GEP, or if we have already done this computation, just let
252 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
253 if (!GEP || SE->hasSCEV(GEP))
254 return SE->getSCEV(Exp);
256 // Analyze all of the subscripts of this getelementptr instruction, looking
257 // for uses that are determined by the trip count of L. First, skip all
258 // operands the are not dependent on the IV.
260 // Build up the base expression. Insert an LLVM cast of the pointer to
262 SCEVHandle GEPVal = SCEVUnknown::get(
263 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
265 gep_type_iterator GTI = gep_type_begin(GEP);
267 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
268 // If this is a use of a recurrence that we can analyze, and it comes before
269 // Op does in the GEP operand list, we will handle this when we process this
271 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
272 const StructLayout *SL = TD->getStructLayout(STy);
273 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
274 uint64_t Offset = SL->getElementOffset(Idx);
275 GEPVal = SCEVAddExpr::get(GEPVal,
276 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
278 unsigned GEPOpiBits =
279 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
280 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
281 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
282 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
283 Instruction::BitCast));
284 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
285 SCEVHandle Idx = SE->getSCEV(OpVal);
287 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
289 Idx = SCEVMulExpr::get(Idx,
290 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
292 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
296 SE->setSCEV(GEP, GEPVal);
300 /// getSCEVStartAndStride - Compute the start and stride of this expression,
301 /// returning false if the expression is not a start/stride pair, or true if it
302 /// is. The stride must be a loop invariant expression, but the start may be
303 /// a mix of loop invariant and loop variant expressions.
304 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
305 SCEVHandle &Start, SCEVHandle &Stride) {
306 SCEVHandle TheAddRec = Start; // Initialize to zero.
308 // If the outer level is an AddExpr, the operands are all start values except
309 // for a nested AddRecExpr.
310 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
311 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
312 if (SCEVAddRecExpr *AddRec =
313 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
314 if (AddRec->getLoop() == L)
315 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
317 return false; // Nested IV of some sort?
319 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
322 } else if (isa<SCEVAddRecExpr>(SH)) {
325 return false; // not analyzable.
328 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
329 if (!AddRec || AddRec->getLoop() != L) return false;
331 // FIXME: Generalize to non-affine IV's.
332 if (!AddRec->isAffine()) return false;
334 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
336 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
337 DOUT << "[" << L->getHeader()->getName()
338 << "] Variable stride: " << *AddRec << "\n";
340 Stride = AddRec->getOperand(1);
344 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
345 /// and now we need to decide whether the user should use the preinc or post-inc
346 /// value. If this user should use the post-inc version of the IV, return true.
348 /// Choosing wrong here can break dominance properties (if we choose to use the
349 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
350 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
351 /// should use the post-inc value).
352 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
353 Loop *L, ETForest *EF, Pass *P) {
354 // If the user is in the loop, use the preinc value.
355 if (L->contains(User->getParent())) return false;
357 BasicBlock *LatchBlock = L->getLoopLatch();
359 // Ok, the user is outside of the loop. If it is dominated by the latch
360 // block, use the post-inc value.
361 if (EF->dominates(LatchBlock, User->getParent()))
364 // There is one case we have to be careful of: PHI nodes. These little guys
365 // can live in blocks that do not dominate the latch block, but (since their
366 // uses occur in the predecessor block, not the block the PHI lives in) should
367 // still use the post-inc value. Check for this case now.
368 PHINode *PN = dyn_cast<PHINode>(User);
369 if (!PN) return false; // not a phi, not dominated by latch block.
371 // Look at all of the uses of IV by the PHI node. If any use corresponds to
372 // a block that is not dominated by the latch block, give up and use the
373 // preincremented value.
374 unsigned NumUses = 0;
375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
376 if (PN->getIncomingValue(i) == IV) {
378 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
382 // Okay, all uses of IV by PN are in predecessor blocks that really are
383 // dominated by the latch block. Split the critical edges and use the
384 // post-incremented value.
385 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
386 if (PN->getIncomingValue(i) == IV) {
387 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
389 // Splitting the critical edge can reduce the number of entries in this
391 e = PN->getNumIncomingValues();
392 if (--NumUses == 0) break;
400 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
401 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
402 /// return true. Otherwise, return false.
403 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
404 std::set<Instruction*> &Processed) {
405 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
406 return false; // Void and FP expressions cannot be reduced.
407 if (!Processed.insert(I).second)
408 return true; // Instruction already handled.
410 // Get the symbolic expression for this instruction.
411 SCEVHandle ISE = GetExpressionSCEV(I, L);
412 if (isa<SCEVCouldNotCompute>(ISE)) return false;
414 // Get the start and stride for this expression.
415 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
416 SCEVHandle Stride = Start;
417 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
418 return false; // Non-reducible symbolic expression, bail out.
420 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;) {
421 Instruction *User = cast<Instruction>(*UI);
423 // Increment iterator now because IVUseShouldUsePostIncValue may remove
424 // User from the list of I users.
427 // Do not infinitely recurse on PHI nodes.
428 if (isa<PHINode>(User) && Processed.count(User))
431 // If this is an instruction defined in a nested loop, or outside this loop,
432 // don't recurse into it.
433 bool AddUserToIVUsers = false;
434 if (LI->getLoopFor(User->getParent()) != L) {
435 DOUT << "FOUND USER in other loop: " << *User
436 << " OF SCEV: " << *ISE << "\n";
437 AddUserToIVUsers = true;
438 } else if (!AddUsersIfInteresting(User, L, Processed)) {
439 DOUT << "FOUND USER: " << *User
440 << " OF SCEV: " << *ISE << "\n";
441 AddUserToIVUsers = true;
444 if (AddUserToIVUsers) {
445 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
446 if (StrideUses.Users.empty()) // First occurance of this stride?
447 StrideOrder.push_back(Stride);
449 // Okay, we found a user that we cannot reduce. Analyze the instruction
450 // and decide what to do with it. If we are a use inside of the loop, use
451 // the value before incrementation, otherwise use it after incrementation.
452 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
453 // The value used will be incremented by the stride more than we are
454 // expecting, so subtract this off.
455 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
456 StrideUses.addUser(NewStart, User, I);
457 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
458 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
460 StrideUses.addUser(Start, User, I);
468 /// BasedUser - For a particular base value, keep information about how we've
469 /// partitioned the expression so far.
471 /// Base - The Base value for the PHI node that needs to be inserted for
472 /// this use. As the use is processed, information gets moved from this
473 /// field to the Imm field (below). BasedUser values are sorted by this
477 /// Inst - The instruction using the induction variable.
480 /// OperandValToReplace - The operand value of Inst to replace with the
482 Value *OperandValToReplace;
484 /// Imm - The immediate value that should be added to the base immediately
485 /// before Inst, because it will be folded into the imm field of the
489 /// EmittedBase - The actual value* to use for the base value of this
490 /// operation. This is null if we should just use zero so far.
493 // isUseOfPostIncrementedValue - True if this should use the
494 // post-incremented version of this IV, not the preincremented version.
495 // This can only be set in special cases, such as the terminating setcc
496 // instruction for a loop and uses outside the loop that are dominated by
498 bool isUseOfPostIncrementedValue;
500 BasedUser(IVStrideUse &IVSU)
501 : Base(IVSU.Offset), Inst(IVSU.User),
502 OperandValToReplace(IVSU.OperandValToReplace),
503 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
504 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
506 // Once we rewrite the code to insert the new IVs we want, update the
507 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
509 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
510 SCEVExpander &Rewriter, Loop *L,
513 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
514 SCEVExpander &Rewriter,
515 Instruction *IP, Loop *L);
520 void BasedUser::dump() const {
521 cerr << " Base=" << *Base;
522 cerr << " Imm=" << *Imm;
524 cerr << " EB=" << *EmittedBase;
526 cerr << " Inst: " << *Inst;
529 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
530 SCEVExpander &Rewriter,
531 Instruction *IP, Loop *L) {
532 // Figure out where we *really* want to insert this code. In particular, if
533 // the user is inside of a loop that is nested inside of L, we really don't
534 // want to insert this expression before the user, we'd rather pull it out as
535 // many loops as possible.
536 LoopInfo &LI = Rewriter.getLoopInfo();
537 Instruction *BaseInsertPt = IP;
539 // Figure out the most-nested loop that IP is in.
540 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
542 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
543 // the preheader of the outer-most loop where NewBase is not loop invariant.
544 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
545 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
546 InsertLoop = InsertLoop->getParentLoop();
549 // If there is no immediate value, skip the next part.
550 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
551 if (SC->getValue()->isZero())
552 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
553 OperandValToReplace->getType());
555 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
557 // Always emit the immediate (if non-zero) into the same block as the user.
558 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
559 return Rewriter.expandCodeFor(NewValSCEV, IP,
560 OperandValToReplace->getType());
564 // Once we rewrite the code to insert the new IVs we want, update the
565 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
567 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
568 SCEVExpander &Rewriter,
570 if (!isa<PHINode>(Inst)) {
571 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
572 // Replace the use of the operand Value with the new Phi we just created.
573 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
574 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
578 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
579 // expression into each operand block that uses it. Note that PHI nodes can
580 // have multiple entries for the same predecessor. We use a map to make sure
581 // that a PHI node only has a single Value* for each predecessor (which also
582 // prevents us from inserting duplicate code in some blocks).
583 std::map<BasicBlock*, Value*> InsertedCode;
584 PHINode *PN = cast<PHINode>(Inst);
585 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
586 if (PN->getIncomingValue(i) == OperandValToReplace) {
587 // If this is a critical edge, split the edge so that we do not insert the
588 // code on all predecessor/successor paths. We do this unless this is the
589 // canonical backedge for this loop, as this can make some inserted code
590 // be in an illegal position.
591 BasicBlock *PHIPred = PN->getIncomingBlock(i);
592 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
593 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
595 // First step, split the critical edge.
596 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
598 // Next step: move the basic block. In particular, if the PHI node
599 // is outside of the loop, and PredTI is in the loop, we want to
600 // move the block to be immediately before the PHI block, not
601 // immediately after PredTI.
602 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
603 BasicBlock *NewBB = PN->getIncomingBlock(i);
604 NewBB->moveBefore(PN->getParent());
607 // Splitting the edge can reduce the number of PHI entries we have.
608 e = PN->getNumIncomingValues();
611 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
613 // Insert the code into the end of the predecessor block.
614 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
615 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
618 // Replace the use of the operand Value with the new Phi we just created.
619 PN->setIncomingValue(i, Code);
623 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
627 /// isTargetConstant - Return true if the following can be referenced by the
628 /// immediate field of a target instruction.
629 static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
630 const TargetLowering *TLI) {
631 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
632 int64_t VC = SC->getValue()->getSExtValue();
634 return TLI->isLegalAddressImmediate(VC, UseTy);
636 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
637 return (VC > -(1 << 16) && VC < (1 << 16)-1);
640 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
641 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
642 if (CE->getOpcode() == Instruction::PtrToInt) {
643 Constant *Op0 = CE->getOperand(0);
644 if (isa<GlobalValue>(Op0) && TLI &&
645 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
651 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
652 /// loop varying to the Imm operand.
653 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
655 if (Val->isLoopInvariant(L)) return; // Nothing to do.
657 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
658 std::vector<SCEVHandle> NewOps;
659 NewOps.reserve(SAE->getNumOperands());
661 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
662 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
663 // If this is a loop-variant expression, it must stay in the immediate
664 // field of the expression.
665 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
667 NewOps.push_back(SAE->getOperand(i));
671 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
673 Val = SCEVAddExpr::get(NewOps);
674 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
675 // Try to pull immediates out of the start value of nested addrec's.
676 SCEVHandle Start = SARE->getStart();
677 MoveLoopVariantsToImediateField(Start, Imm, L);
679 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
681 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
683 // Otherwise, all of Val is variant, move the whole thing over.
684 Imm = SCEVAddExpr::get(Imm, Val);
685 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
690 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
691 /// that can fit into the immediate field of instructions in the target.
692 /// Accumulate these immediate values into the Imm value.
693 static void MoveImmediateValues(const TargetLowering *TLI,
695 SCEVHandle &Val, SCEVHandle &Imm,
696 bool isAddress, Loop *L) {
697 const Type *UseTy = User->getType();
698 if (StoreInst *SI = dyn_cast<StoreInst>(User))
699 UseTy = SI->getOperand(0)->getType();
701 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
702 std::vector<SCEVHandle> NewOps;
703 NewOps.reserve(SAE->getNumOperands());
705 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
706 SCEVHandle NewOp = SAE->getOperand(i);
707 MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L);
709 if (!NewOp->isLoopInvariant(L)) {
710 // If this is a loop-variant expression, it must stay in the immediate
711 // field of the expression.
712 Imm = SCEVAddExpr::get(Imm, NewOp);
714 NewOps.push_back(NewOp);
719 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
721 Val = SCEVAddExpr::get(NewOps);
723 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
724 // Try to pull immediates out of the start value of nested addrec's.
725 SCEVHandle Start = SARE->getStart();
726 MoveImmediateValues(TLI, User, Start, Imm, isAddress, L);
728 if (Start != SARE->getStart()) {
729 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
731 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
734 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
735 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
736 if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
737 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
739 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
740 SCEVHandle NewOp = SME->getOperand(1);
741 MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L);
743 // If we extracted something out of the subexpressions, see if we can
745 if (NewOp != SME->getOperand(1)) {
746 // Scale SubImm up by "8". If the result is a target constant, we are
748 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
749 if (isTargetConstant(SubImm, UseTy, TLI)) {
750 // Accumulate the immediate.
751 Imm = SCEVAddExpr::get(Imm, SubImm);
753 // Update what is left of 'Val'.
754 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
761 // Loop-variant expressions must stay in the immediate field of the
763 if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
764 !Val->isLoopInvariant(L)) {
765 Imm = SCEVAddExpr::get(Imm, Val);
766 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
770 // Otherwise, no immediates to move.
774 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
775 /// added together. This is used to reassociate common addition subexprs
776 /// together for maximal sharing when rewriting bases.
777 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
779 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
780 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
781 SeparateSubExprs(SubExprs, AE->getOperand(j));
782 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
783 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
784 if (SARE->getOperand(0) == Zero) {
785 SubExprs.push_back(Expr);
787 // Compute the addrec with zero as its base.
788 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
789 Ops[0] = Zero; // Start with zero base.
790 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
793 SeparateSubExprs(SubExprs, SARE->getOperand(0));
795 } else if (!isa<SCEVConstant>(Expr) ||
796 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
798 SubExprs.push_back(Expr);
803 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
804 /// removing any common subexpressions from it. Anything truly common is
805 /// removed, accumulated, and returned. This looks for things like (a+b+c) and
806 /// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
808 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
809 unsigned NumUses = Uses.size();
811 // Only one use? Use its base, regardless of what it is!
812 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
813 SCEVHandle Result = Zero;
815 std::swap(Result, Uses[0].Base);
819 // To find common subexpressions, count how many of Uses use each expression.
820 // If any subexpressions are used Uses.size() times, they are common.
821 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
823 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
824 // order we see them.
825 std::vector<SCEVHandle> UniqueSubExprs;
827 std::vector<SCEVHandle> SubExprs;
828 for (unsigned i = 0; i != NumUses; ++i) {
829 // If the base is zero (which is common), return zero now, there are no
831 if (Uses[i].Base == Zero) return Zero;
833 // Split the expression into subexprs.
834 SeparateSubExprs(SubExprs, Uses[i].Base);
835 // Add one to SubExpressionUseCounts for each subexpr present.
836 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
837 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
838 UniqueSubExprs.push_back(SubExprs[j]);
842 // Now that we know how many times each is used, build Result. Iterate over
843 // UniqueSubexprs so that we have a stable ordering.
844 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
845 std::map<SCEVHandle, unsigned>::iterator I =
846 SubExpressionUseCounts.find(UniqueSubExprs[i]);
847 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
848 if (I->second == NumUses) { // Found CSE!
849 Result = SCEVAddExpr::get(Result, I->first);
851 // Remove non-cse's from SubExpressionUseCounts.
852 SubExpressionUseCounts.erase(I);
856 // If we found no CSE's, return now.
857 if (Result == Zero) return Result;
859 // Otherwise, remove all of the CSE's we found from each of the base values.
860 for (unsigned i = 0; i != NumUses; ++i) {
861 // Split the expression into subexprs.
862 SeparateSubExprs(SubExprs, Uses[i].Base);
864 // Remove any common subexpressions.
865 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
866 if (SubExpressionUseCounts.count(SubExprs[j])) {
867 SubExprs.erase(SubExprs.begin()+j);
871 // Finally, the non-shared expressions together.
872 if (SubExprs.empty())
875 Uses[i].Base = SCEVAddExpr::get(SubExprs);
882 /// isZero - returns true if the scalar evolution expression is zero.
884 static bool isZero(SCEVHandle &V) {
885 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
886 return SC->getValue()->isZero();
890 /// ValidStride - Check whether the given Scale is valid for all loads and
891 /// stores in UsersToProcess. Pulled into a function to avoid disturbing the
892 /// sensibilities of those who dislike goto's.
894 bool LoopStrengthReduce::ValidStride(int64_t Scale,
895 const std::vector<BasedUser>& UsersToProcess) {
897 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
898 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
899 Imm = SC->getValue()->getSExtValue();
903 // If this is a load or other access, pass the type of the access in.
904 const Type *AccessTy = Type::VoidTy;
905 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
906 AccessTy = SI->getOperand(0)->getType();
907 else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
908 AccessTy = LI->getType();
910 if (!TLI->isLegalAddressScaleAndImm(Scale, Imm, AccessTy))
916 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
917 /// of a previous stride and it is a legal value for the target addressing
918 /// mode scale component. This allows the users of this stride to be rewritten
919 /// as prev iv * factor. It returns 0 if no reuse is possible.
920 unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
921 IVExpr &IV, const Type *Ty,
922 const std::vector<BasedUser>& UsersToProcess) {
925 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
926 int64_t SInt = SC->getValue()->getSExtValue();
927 if (SInt == 1) return 0;
929 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
930 SE = IVsByStride.end(); SI != SE; ++SI) {
931 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
932 if (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0)
934 int64_t Scale = SInt / SSInt;
935 // Check that this stride is valid for all the types used for loads and
936 // stores; if it can be used for some and not others, we might as well use
937 // the original stride everywhere, since we have to create the IV for it
939 if (ValidStride(Scale, UsersToProcess))
940 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
941 IE = SI->second.IVs.end(); II != IE; ++II)
942 // FIXME: Only handle base == 0 for now.
943 // Only reuse previous IV if it would not require a type conversion.
944 if (isZero(II->Base) && II->Base->getType() == Ty) {
953 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
954 /// returns true if Val's isUseOfPostIncrementedValue is true.
955 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
956 return Val.isUseOfPostIncrementedValue;
959 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
960 /// stride of IV. All of the users may have different starting values, and this
961 /// may not be the only stride (we know it is if isOnlyStride is true).
962 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
963 IVUsersOfOneStride &Uses,
966 // Transform our list of users and offsets to a bit more complex table. In
967 // this new vector, each 'BasedUser' contains 'Base' the base of the
968 // strided accessas well as the old information from Uses. We progressively
969 // move information from the Base field to the Imm field, until we eventually
970 // have the full access expression to rewrite the use.
971 std::vector<BasedUser> UsersToProcess;
972 UsersToProcess.reserve(Uses.Users.size());
973 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
974 UsersToProcess.push_back(Uses.Users[i]);
976 // Move any loop invariant operands from the offset field to the immediate
977 // field of the use, so that we don't try to use something before it is
979 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
980 UsersToProcess.back().Imm, L);
981 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
982 "Base value is not loop invariant!");
985 // We now have a whole bunch of uses of like-strided induction variables, but
986 // they might all have different bases. We want to emit one PHI node for this
987 // stride which we fold as many common expressions (between the IVs) into as
988 // possible. Start by identifying the common expressions in the base values
989 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
990 // "A+B"), emit it to the preheader, then remove the expression from the
991 // UsersToProcess base values.
992 SCEVHandle CommonExprs =
993 RemoveCommonExpressionsFromUseBases(UsersToProcess);
995 // Next, figure out what we can represent in the immediate fields of
996 // instructions. If we can represent anything there, move it to the imm
997 // fields of the BasedUsers. We do this so that it increases the commonality
998 // of the remaining uses.
999 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1000 // If the user is not in the current loop, this means it is using the exit
1001 // value of the IV. Do not put anything in the base, make sure it's all in
1002 // the immediate field to allow as much factoring as possible.
1003 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1004 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
1005 UsersToProcess[i].Base);
1006 UsersToProcess[i].Base =
1007 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1010 // Addressing modes can be folded into loads and stores. Be careful that
1011 // the store is through the expression, not of the expression though.
1012 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
1013 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
1014 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1017 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1018 UsersToProcess[i].Imm, isAddress, L);
1022 // Check if it is possible to reuse a IV with stride that is factor of this
1023 // stride. And the multiple is a number that can be encoded in the scale
1024 // field of the target addressing mode. And we will have a valid
1025 // instruction after this substition, including the immediate field, if any.
1026 PHINode *NewPHI = NULL;
1029 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
1030 CommonExprs->getType(),
1032 if (RewriteFactor != 0) {
1033 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1034 << " and BASE " << *ReuseIV.Base << " :\n";
1035 NewPHI = ReuseIV.PHI;
1036 IncV = ReuseIV.IncV;
1039 const Type *ReplacedTy = CommonExprs->getType();
1041 // Now that we know what we need to do, insert the PHI node itself.
1043 DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
1044 << *Stride << " and BASE " << *CommonExprs << " :\n";
1046 SCEVExpander Rewriter(*SE, *LI);
1047 SCEVExpander PreheaderRewriter(*SE, *LI);
1049 BasicBlock *Preheader = L->getLoopPreheader();
1050 Instruction *PreInsertPt = Preheader->getTerminator();
1051 Instruction *PhiInsertBefore = L->getHeader()->begin();
1053 BasicBlock *LatchBlock = L->getLoopLatch();
1056 // Emit the initial base value into the loop preheader.
1058 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1061 if (RewriteFactor == 0) {
1062 // Create a new Phi for this base, and stick it in the loop header.
1063 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1066 // Add common base to the new Phi node.
1067 NewPHI->addIncoming(CommonBaseV, Preheader);
1069 // Insert the stride into the preheader.
1070 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1072 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
1074 // Emit the increment of the base value before the terminator of the loop
1075 // latch block, and add it to the Phi node.
1076 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1077 SCEVUnknown::get(StrideV));
1079 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1081 IncV->setName(NewPHI->getName()+".inc");
1082 NewPHI->addIncoming(IncV, LatchBlock);
1084 // Remember this in case a later stride is multiple of this.
1085 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
1087 Constant *C = dyn_cast<Constant>(CommonBaseV);
1089 (!C->isNullValue() &&
1090 !isTargetConstant(SCEVUnknown::get(CommonBaseV), ReplacedTy, TLI)))
1091 // We want the common base emitted into the preheader! This is just
1092 // using cast as a copy so BitCast (no-op cast) is appropriate
1093 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1094 "commonbase", PreInsertPt);
1097 // We want to emit code for users inside the loop first. To do this, we
1098 // rearrange BasedUser so that the entries at the end have
1099 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1100 // vector (so we handle them first).
1101 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1102 PartitionByIsUseOfPostIncrementedValue);
1104 // Sort this by base, so that things with the same base are handled
1105 // together. By partitioning first and stable-sorting later, we are
1106 // guaranteed that within each base we will pop off users from within the
1107 // loop before users outside of the loop with a particular base.
1109 // We would like to use stable_sort here, but we can't. The problem is that
1110 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1111 // we don't have anything to do a '<' comparison on. Because we think the
1112 // number of uses is small, do a horrible bubble sort which just relies on
1114 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1115 // Get a base value.
1116 SCEVHandle Base = UsersToProcess[i].Base;
1118 // Compact everything with this base to be consequetive with this one.
1119 for (unsigned j = i+1; j != e; ++j) {
1120 if (UsersToProcess[j].Base == Base) {
1121 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1127 // Process all the users now. This outer loop handles all bases, the inner
1128 // loop handles all users of a particular base.
1129 while (!UsersToProcess.empty()) {
1130 SCEVHandle Base = UsersToProcess.back().Base;
1132 DOUT << " INSERTING code for BASE = " << *Base << ":\n";
1134 // Emit the code for Base into the preheader.
1135 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1138 // If BaseV is a constant other than 0, make sure that it gets inserted into
1139 // the preheader, instead of being forward substituted into the uses. We do
1140 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1142 if (Constant *C = dyn_cast<Constant>(BaseV)) {
1143 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
1144 // We want this constant emitted into the preheader! This is just
1145 // using cast as a copy so BitCast (no-op cast) is appropriate
1146 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1151 // Emit the code to add the immediate offset to the Phi value, just before
1152 // the instructions that we identified as using this stride and base.
1154 // FIXME: Use emitted users to emit other users.
1155 BasedUser &User = UsersToProcess.back();
1157 // If this instruction wants to use the post-incremented value, move it
1158 // after the post-inc and use its value instead of the PHI.
1159 Value *RewriteOp = NewPHI;
1160 if (User.isUseOfPostIncrementedValue) {
1163 // If this user is in the loop, make sure it is the last thing in the
1164 // loop to ensure it is dominated by the increment.
1165 if (L->contains(User.Inst->getParent()))
1166 User.Inst->moveBefore(LatchBlock->getTerminator());
1168 if (RewriteOp->getType() != ReplacedTy) {
1169 Instruction::CastOps opcode = Instruction::Trunc;
1170 if (ReplacedTy->getPrimitiveSizeInBits() ==
1171 RewriteOp->getType()->getPrimitiveSizeInBits())
1172 opcode = Instruction::BitCast;
1173 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1176 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1178 // Clear the SCEVExpander's expression map so that we are guaranteed
1179 // to have the code emitted where we expect it.
1182 // If we are reusing the iv, then it must be multiplied by a constant
1183 // factor take advantage of addressing mode scale component.
1184 if (RewriteFactor != 0) {
1186 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
1187 RewriteExpr->getType()),
1190 // The common base is emitted in the loop preheader. But since we
1191 // are reusing an IV, it has not been used to initialize the PHI node.
1192 // Add it to the expression used to rewrite the uses.
1193 if (!isa<ConstantInt>(CommonBaseV) ||
1194 !cast<ConstantInt>(CommonBaseV)->isZero())
1195 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1196 SCEVUnknown::get(CommonBaseV));
1199 // Now that we know what we need to do, insert code before User for the
1200 // immediate and any loop-variant expressions.
1201 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
1202 // Add BaseV to the PHI value if needed.
1203 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
1205 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
1207 // Mark old value we replaced as possibly dead, so that it is elminated
1208 // if we just replaced the last use of that value.
1209 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
1211 UsersToProcess.pop_back();
1214 // If there are any more users to process with the same base, process them
1215 // now. We sorted by base above, so we just have to check the last elt.
1216 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1217 // TODO: Next, find out which base index is the most common, pull it out.
1220 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1221 // different starting values, into different PHIs.
1224 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1225 // uses in the loop, look to see if we can eliminate some, in favor of using
1226 // common indvars for the different uses.
1227 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1228 // TODO: implement optzns here.
1230 // Finally, get the terminating condition for the loop if possible. If we
1231 // can, we want to change it to use a post-incremented version of its
1232 // induction variable, to allow coalescing the live ranges for the IV into
1233 // one register value.
1234 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1235 BasicBlock *Preheader = L->getLoopPreheader();
1236 BasicBlock *LatchBlock =
1237 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1238 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1239 if (!TermBr || TermBr->isUnconditional() ||
1240 !isa<ICmpInst>(TermBr->getCondition()))
1242 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1244 // Search IVUsesByStride to find Cond's IVUse if there is one.
1245 IVStrideUse *CondUse = 0;
1246 const SCEVHandle *CondStride = 0;
1248 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1250 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1251 IVUsesByStride.find(StrideOrder[Stride]);
1252 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1254 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1255 E = SI->second.Users.end(); UI != E; ++UI)
1256 if (UI->User == Cond) {
1258 CondStride = &SI->first;
1259 // NOTE: we could handle setcc instructions with multiple uses here, but
1260 // InstCombine does it as well for simple uses, it's not clear that it
1261 // occurs enough in real life to handle.
1265 if (!CondUse) return; // setcc doesn't use the IV.
1267 // It's possible for the setcc instruction to be anywhere in the loop, and
1268 // possible for it to have multiple users. If it is not immediately before
1269 // the latch block branch, move it.
1270 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1271 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1272 Cond->moveBefore(TermBr);
1274 // Otherwise, clone the terminating condition and insert into the loopend.
1275 Cond = cast<ICmpInst>(Cond->clone());
1276 Cond->setName(L->getHeader()->getName() + ".termcond");
1277 LatchBlock->getInstList().insert(TermBr, Cond);
1279 // Clone the IVUse, as the old use still exists!
1280 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1281 CondUse->OperandValToReplace);
1282 CondUse = &IVUsesByStride[*CondStride].Users.back();
1286 // If we get to here, we know that we can transform the setcc instruction to
1287 // use the post-incremented version of the IV, allowing us to coalesce the
1288 // live ranges for the IV correctly.
1289 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
1290 CondUse->isUseOfPostIncrementedValue = true;
1294 // Constant strides come first which in turns are sorted by their absolute
1295 // values. If absolute values are the same, then positive strides comes first.
1297 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1298 struct StrideCompare {
1299 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1300 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1301 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1303 int64_t LV = LHSC->getValue()->getSExtValue();
1304 int64_t RV = RHSC->getValue()->getSExtValue();
1305 uint64_t ALV = (LV < 0) ? -LV : LV;
1306 uint64_t ARV = (RV < 0) ? -RV : RV;
1312 return (LHSC && !RHSC);
1317 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
1319 LI = &getAnalysis<LoopInfo>();
1320 EF = &getAnalysis<ETForest>();
1321 SE = &getAnalysis<ScalarEvolution>();
1322 TD = &getAnalysis<TargetData>();
1323 UIntPtrTy = TD->getIntPtrType();
1325 // Find all uses of induction variables in this loop, and catagorize
1326 // them by stride. Start by finding all of the PHI nodes in the header for
1327 // this loop. If they are induction variables, inspect their uses.
1328 std::set<Instruction*> Processed; // Don't reprocess instructions.
1329 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1330 AddUsersIfInteresting(I, L, Processed);
1332 // If we have nothing to do, return.
1333 if (IVUsesByStride.empty()) return false;
1335 // Optimize induction variables. Some indvar uses can be transformed to use
1336 // strides that will be needed for other purposes. A common example of this
1337 // is the exit test for the loop, which can often be rewritten to use the
1338 // computation of some other indvar to decide when to terminate the loop.
1342 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1343 // doing computation in byte values, promote to 32-bit values if safe.
1345 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1346 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1347 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1348 // to be careful that IV's are all the same type. Only works for intptr_t
1351 // If we only have one stride, we can more aggressively eliminate some things.
1352 bool HasOneStride = IVUsesByStride.size() == 1;
1355 DOUT << "\nLSR on ";
1359 // IVsByStride keeps IVs for one particular loop.
1360 IVsByStride.clear();
1362 // Sort the StrideOrder so we process larger strides first.
1363 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1365 // Note: this processes each stride/type pair individually. All users passed
1366 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1367 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1368 // This extra layer of indirection makes the ordering of strides deterministic
1369 // - not dependent on map order.
1370 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1371 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1372 IVUsesByStride.find(StrideOrder[Stride]);
1373 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1374 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1377 // Clean up after ourselves
1378 if (!DeadInsts.empty()) {
1379 DeleteTriviallyDeadInstructions(DeadInsts);
1381 BasicBlock::iterator I = L->getHeader()->begin();
1383 while ((PN = dyn_cast<PHINode>(I))) {
1384 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1386 // At this point, we know that we have killed one or more GEP
1387 // instructions. It is worth checking to see if the cann indvar is also
1388 // dead, so that we can remove it as well. The requirements for the cann
1389 // indvar to be considered dead are:
1390 // 1. the cann indvar has one use
1391 // 2. the use is an add instruction
1392 // 3. the add has one use
1393 // 4. the add is used by the cann indvar
1394 // If all four cases above are true, then we can remove both the add and
1396 // FIXME: this needs to eliminate an induction variable even if it's being
1397 // compared against some value to decide loop termination.
1398 if (PN->hasOneUse()) {
1399 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1400 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1401 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
1402 DeadInsts.insert(BO);
1403 // Break the cycle, then delete the PHI.
1404 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1405 SE->deleteInstructionFromRecords(PN);
1406 PN->eraseFromParent();
1411 DeleteTriviallyDeadInstructions(DeadInsts);
1414 CastedPointers.clear();
1415 IVUsesByStride.clear();
1416 StrideOrder.clear();