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/ScalarEvolutionExpander.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/GetElementPtrTypeIterator.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Debug.h"
39 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
40 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
41 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
43 /// IVStrideUse - Keep track of one use of a strided induction variable, where
44 /// the stride is stored externally. The Offset member keeps track of the
45 /// offset from the IV, User is the actual user of the operand, and 'Operand'
46 /// is the operand # of the User that is the use.
50 Value *OperandValToReplace;
52 // isUseOfPostIncrementedValue - True if this should use the
53 // post-incremented version of this IV, not the preincremented version.
54 // This can only be set in special cases, such as the terminating setcc
55 // instruction for a loop or uses dominated by the loop.
56 bool isUseOfPostIncrementedValue;
58 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
59 : Offset(Offs), User(U), OperandValToReplace(O),
60 isUseOfPostIncrementedValue(false) {}
63 /// IVUsersOfOneStride - This structure keeps track of all instructions that
64 /// have an operand that is based on the trip count multiplied by some stride.
65 /// The stride for all of these users is common and kept external to this
67 struct IVUsersOfOneStride {
68 /// Users - Keep track of all of the users of this stride as well as the
69 /// initial value and the operand that uses the IV.
70 std::vector<IVStrideUse> Users;
72 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
73 Users.push_back(IVStrideUse(Offset, User, Operand));
78 class LoopStrengthReduce : public FunctionPass {
83 const Type *UIntPtrTy;
86 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
87 /// target can handle for free with its addressing modes.
88 unsigned MaxTargetAMSize;
90 /// IVUsesByStride - Keep track of all uses of induction variables that we
91 /// are interested in. The key of the map is the stride of the access.
92 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
94 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
95 /// We use this to iterate over the IVUsesByStride collection without being
96 /// dependent on random ordering of pointers in the process.
97 std::vector<SCEVHandle> StrideOrder;
99 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
100 /// of the casted version of each value. This is accessed by
101 /// getCastedVersionOf.
102 std::map<Value*, Value*> CastedPointers;
104 /// DeadInsts - Keep track of instructions we may have made dead, so that
105 /// we can remove them after we are done working.
106 std::set<Instruction*> DeadInsts;
108 LoopStrengthReduce(unsigned MTAMS = 1)
109 : MaxTargetAMSize(MTAMS) {
112 virtual bool runOnFunction(Function &) {
113 LI = &getAnalysis<LoopInfo>();
114 EF = &getAnalysis<ETForest>();
115 SE = &getAnalysis<ScalarEvolution>();
116 TD = &getAnalysis<TargetData>();
117 UIntPtrTy = TD->getIntPtrType();
120 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
126 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
127 // We split critical edges, so we change the CFG. However, we do update
128 // many analyses if they are around.
129 AU.addPreservedID(LoopSimplifyID);
130 AU.addPreserved<LoopInfo>();
131 AU.addPreserved<DominatorSet>();
132 AU.addPreserved<ETForest>();
133 AU.addPreserved<ImmediateDominators>();
134 AU.addPreserved<DominanceFrontier>();
135 AU.addPreserved<DominatorTree>();
137 AU.addRequiredID(LoopSimplifyID);
138 AU.addRequired<LoopInfo>();
139 AU.addRequired<ETForest>();
140 AU.addRequired<TargetData>();
141 AU.addRequired<ScalarEvolution>();
144 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
146 Value *getCastedVersionOf(Value *V);
148 void runOnLoop(Loop *L);
149 bool AddUsersIfInteresting(Instruction *I, Loop *L,
150 std::set<Instruction*> &Processed);
151 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
153 void OptimizeIndvars(Loop *L);
155 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
156 IVUsersOfOneStride &Uses,
157 Loop *L, bool isOnlyStride);
158 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
160 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
161 "Loop Strength Reduction");
164 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
165 return new LoopStrengthReduce(MaxTargetAMSize);
168 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
170 Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
171 if (V->getType() == UIntPtrTy) return V;
172 if (Constant *CB = dyn_cast<Constant>(V))
173 return ConstantExpr::getCast(CB, UIntPtrTy);
175 Value *&New = CastedPointers[V];
178 BasicBlock::iterator InsertPt;
179 if (Argument *Arg = dyn_cast<Argument>(V)) {
180 // Insert into the entry of the function, after any allocas.
181 InsertPt = Arg->getParent()->begin()->begin();
182 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
184 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
185 InsertPt = II->getNormalDest()->begin();
187 InsertPt = cast<Instruction>(V);
191 // Do not insert casts into the middle of PHI node blocks.
192 while (isa<PHINode>(InsertPt)) ++InsertPt;
195 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
196 DeadInsts.insert(cast<Instruction>(New));
201 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
202 /// specified set are trivially dead, delete them and see if this makes any of
203 /// their operands subsequently dead.
204 void LoopStrengthReduce::
205 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
206 while (!Insts.empty()) {
207 Instruction *I = *Insts.begin();
208 Insts.erase(Insts.begin());
209 if (isInstructionTriviallyDead(I)) {
210 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
211 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
213 SE->deleteInstructionFromRecords(I);
214 I->eraseFromParent();
221 /// GetExpressionSCEV - Compute and return the SCEV for the specified
223 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
224 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
225 // If this is a GEP that SE doesn't know about, compute it now and insert it.
226 // If this is not a GEP, or if we have already done this computation, just let
228 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
229 if (!GEP || SE->hasSCEV(GEP))
230 return SE->getSCEV(Exp);
232 // Analyze all of the subscripts of this getelementptr instruction, looking
233 // for uses that are determined by the trip count of L. First, skip all
234 // operands the are not dependent on the IV.
236 // Build up the base expression. Insert an LLVM cast of the pointer to
238 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
240 gep_type_iterator GTI = gep_type_begin(GEP);
242 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
243 // If this is a use of a recurrence that we can analyze, and it comes before
244 // Op does in the GEP operand list, we will handle this when we process this
246 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
247 const StructLayout *SL = TD->getStructLayout(STy);
248 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
249 uint64_t Offset = SL->MemberOffsets[Idx];
250 GEPVal = SCEVAddExpr::get(GEPVal,
251 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
253 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
254 SCEVHandle Idx = SE->getSCEV(OpVal);
256 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
258 Idx = SCEVMulExpr::get(Idx,
259 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
261 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
265 SE->setSCEV(GEP, GEPVal);
269 /// getSCEVStartAndStride - Compute the start and stride of this expression,
270 /// returning false if the expression is not a start/stride pair, or true if it
271 /// is. The stride must be a loop invariant expression, but the start may be
272 /// a mix of loop invariant and loop variant expressions.
273 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
274 SCEVHandle &Start, SCEVHandle &Stride) {
275 SCEVHandle TheAddRec = Start; // Initialize to zero.
277 // If the outer level is an AddExpr, the operands are all start values except
278 // for a nested AddRecExpr.
279 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
280 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
281 if (SCEVAddRecExpr *AddRec =
282 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
283 if (AddRec->getLoop() == L)
284 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
286 return false; // Nested IV of some sort?
288 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
291 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
294 return false; // not analyzable.
297 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
298 if (!AddRec || AddRec->getLoop() != L) return false;
300 // FIXME: Generalize to non-affine IV's.
301 if (!AddRec->isAffine()) return false;
303 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
305 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
306 DEBUG(std::cerr << "[" << L->getHeader()->getName()
307 << "] Variable stride: " << *AddRec << "\n");
309 Stride = AddRec->getOperand(1);
310 // Check that all constant strides are the unsigned type, we don't want to
311 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
313 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
314 "Constants should be canonicalized to unsigned!");
319 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
320 /// and now we need to decide whether the user should use the preinc or post-inc
321 /// value. If this user should use the post-inc version of the IV, return true.
323 /// Choosing wrong here can break dominance properties (if we choose to use the
324 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
325 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
326 /// should use the post-inc value).
327 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
328 Loop *L, ETForest *EF, Pass *P) {
329 // If the user is in the loop, use the preinc value.
330 if (L->contains(User->getParent())) return false;
332 BasicBlock *LatchBlock = L->getLoopLatch();
334 // Ok, the user is outside of the loop. If it is dominated by the latch
335 // block, use the post-inc value.
336 if (EF->dominates(LatchBlock, User->getParent()))
339 // There is one case we have to be careful of: PHI nodes. These little guys
340 // can live in blocks that do not dominate the latch block, but (since their
341 // uses occur in the predecessor block, not the block the PHI lives in) should
342 // still use the post-inc value. Check for this case now.
343 PHINode *PN = dyn_cast<PHINode>(User);
344 if (!PN) return false; // not a phi, not dominated by latch block.
346 // Look at all of the uses of IV by the PHI node. If any use corresponds to
347 // a block that is not dominated by the latch block, give up and use the
348 // preincremented value.
349 unsigned NumUses = 0;
350 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
351 if (PN->getIncomingValue(i) == IV) {
353 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
357 // Okay, all uses of IV by PN are in predecessor blocks that really are
358 // dominated by the latch block. Split the critical edges and use the
359 // post-incremented value.
360 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
361 if (PN->getIncomingValue(i) == IV) {
362 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
363 if (--NumUses == 0) break;
371 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
372 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
373 /// return true. Otherwise, return false.
374 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
375 std::set<Instruction*> &Processed) {
376 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
377 return false; // Void and FP expressions cannot be reduced.
378 if (!Processed.insert(I).second)
379 return true; // Instruction already handled.
381 // Get the symbolic expression for this instruction.
382 SCEVHandle ISE = GetExpressionSCEV(I, L);
383 if (isa<SCEVCouldNotCompute>(ISE)) return false;
385 // Get the start and stride for this expression.
386 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
387 SCEVHandle Stride = Start;
388 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
389 return false; // Non-reducible symbolic expression, bail out.
391 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
392 Instruction *User = cast<Instruction>(*UI);
394 // Do not infinitely recurse on PHI nodes.
395 if (isa<PHINode>(User) && Processed.count(User))
398 // If this is an instruction defined in a nested loop, or outside this loop,
399 // don't recurse into it.
400 bool AddUserToIVUsers = false;
401 if (LI->getLoopFor(User->getParent()) != L) {
402 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
403 << " OF SCEV: " << *ISE << "\n");
404 AddUserToIVUsers = true;
405 } else if (!AddUsersIfInteresting(User, L, Processed)) {
406 DEBUG(std::cerr << "FOUND USER: " << *User
407 << " OF SCEV: " << *ISE << "\n");
408 AddUserToIVUsers = true;
411 if (AddUserToIVUsers) {
412 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
413 if (StrideUses.Users.empty()) // First occurance of this stride?
414 StrideOrder.push_back(Stride);
416 // Okay, we found a user that we cannot reduce. Analyze the instruction
417 // and decide what to do with it. If we are a use inside of the loop, use
418 // the value before incrementation, otherwise use it after incrementation.
419 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
420 // The value used will be incremented by the stride more than we are
421 // expecting, so subtract this off.
422 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
423 StrideUses.addUser(NewStart, User, I);
424 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
425 DEBUG(std::cerr << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
427 StrideUses.addUser(Start, User, I);
435 /// BasedUser - For a particular base value, keep information about how we've
436 /// partitioned the expression so far.
438 /// Base - The Base value for the PHI node that needs to be inserted for
439 /// this use. As the use is processed, information gets moved from this
440 /// field to the Imm field (below). BasedUser values are sorted by this
444 /// Inst - The instruction using the induction variable.
447 /// OperandValToReplace - The operand value of Inst to replace with the
449 Value *OperandValToReplace;
451 /// Imm - The immediate value that should be added to the base immediately
452 /// before Inst, because it will be folded into the imm field of the
456 /// EmittedBase - The actual value* to use for the base value of this
457 /// operation. This is null if we should just use zero so far.
460 // isUseOfPostIncrementedValue - True if this should use the
461 // post-incremented version of this IV, not the preincremented version.
462 // This can only be set in special cases, such as the terminating setcc
463 // instruction for a loop and uses outside the loop that are dominated by
465 bool isUseOfPostIncrementedValue;
467 BasedUser(IVStrideUse &IVSU)
468 : Base(IVSU.Offset), Inst(IVSU.User),
469 OperandValToReplace(IVSU.OperandValToReplace),
470 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
471 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
473 // Once we rewrite the code to insert the new IVs we want, update the
474 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
476 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
477 SCEVExpander &Rewriter, Loop *L,
483 void BasedUser::dump() const {
484 std::cerr << " Base=" << *Base;
485 std::cerr << " Imm=" << *Imm;
487 std::cerr << " EB=" << *EmittedBase;
489 std::cerr << " Inst: " << *Inst;
492 // Once we rewrite the code to insert the new IVs we want, update the
493 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
495 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
496 SCEVExpander &Rewriter,
498 if (!isa<PHINode>(Inst)) {
499 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
500 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
501 OperandValToReplace->getType());
502 // Replace the use of the operand Value with the new Phi we just created.
503 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
504 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
508 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
509 // expression into each operand block that uses it. Note that PHI nodes can
510 // have multiple entries for the same predecessor. We use a map to make sure
511 // that a PHI node only has a single Value* for each predecessor (which also
512 // prevents us from inserting duplicate code in some blocks).
513 std::map<BasicBlock*, Value*> InsertedCode;
514 PHINode *PN = cast<PHINode>(Inst);
515 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
516 if (PN->getIncomingValue(i) == OperandValToReplace) {
517 // If this is a critical edge, split the edge so that we do not insert the
518 // code on all predecessor/successor paths. We do this unless this is the
519 // canonical backedge for this loop, as this can make some inserted code
520 // be in an illegal position.
521 BasicBlock *PHIPred = PN->getIncomingBlock(i);
522 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
523 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
525 // First step, split the critical edge.
526 SplitCriticalEdge(PHIPred, PN->getParent(), P);
528 // Next step: move the basic block. In particular, if the PHI node
529 // is outside of the loop, and PredTI is in the loop, we want to
530 // move the block to be immediately before the PHI block, not
531 // immediately after PredTI.
532 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
533 BasicBlock *NewBB = PN->getIncomingBlock(i);
534 NewBB->moveBefore(PN->getParent());
538 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
540 // Insert the code into the end of the predecessor block.
541 BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
543 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
544 Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
545 OperandValToReplace->getType());
548 // Replace the use of the operand Value with the new Phi we just created.
549 PN->setIncomingValue(i, Code);
553 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
557 /// isTargetConstant - Return true if the following can be referenced by the
558 /// immediate field of a target instruction.
559 static bool isTargetConstant(const SCEVHandle &V) {
561 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
562 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
563 // PPC allows a sign-extended 16-bit immediate field.
564 int64_t V = SC->getValue()->getSExtValue();
565 if (V > -(1 << 16) && V < (1 << 16)-1)
570 return false; // ENABLE this for x86
572 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
573 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
574 if (CE->getOpcode() == Instruction::Cast)
575 if (isa<GlobalValue>(CE->getOperand(0)))
576 // FIXME: should check to see that the dest is uintptr_t!
581 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
582 /// loop varying to the Imm operand.
583 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
585 if (Val->isLoopInvariant(L)) return; // Nothing to do.
587 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
588 std::vector<SCEVHandle> NewOps;
589 NewOps.reserve(SAE->getNumOperands());
591 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
592 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
593 // If this is a loop-variant expression, it must stay in the immediate
594 // field of the expression.
595 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
597 NewOps.push_back(SAE->getOperand(i));
601 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
603 Val = SCEVAddExpr::get(NewOps);
604 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
605 // Try to pull immediates out of the start value of nested addrec's.
606 SCEVHandle Start = SARE->getStart();
607 MoveLoopVariantsToImediateField(Start, Imm, L);
609 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
611 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
613 // Otherwise, all of Val is variant, move the whole thing over.
614 Imm = SCEVAddExpr::get(Imm, Val);
615 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
620 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
621 /// that can fit into the immediate field of instructions in the target.
622 /// Accumulate these immediate values into the Imm value.
623 static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
624 bool isAddress, Loop *L) {
625 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
626 std::vector<SCEVHandle> NewOps;
627 NewOps.reserve(SAE->getNumOperands());
629 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
630 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
631 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
632 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
633 // If this is a loop-variant expression, it must stay in the immediate
634 // field of the expression.
635 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
637 NewOps.push_back(SAE->getOperand(i));
641 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
643 Val = SCEVAddExpr::get(NewOps);
645 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
646 // Try to pull immediates out of the start value of nested addrec's.
647 SCEVHandle Start = SARE->getStart();
648 MoveImmediateValues(Start, Imm, isAddress, L);
650 if (Start != SARE->getStart()) {
651 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
653 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
658 // Loop-variant expressions must stay in the immediate field of the
660 if ((isAddress && isTargetConstant(Val)) ||
661 !Val->isLoopInvariant(L)) {
662 Imm = SCEVAddExpr::get(Imm, Val);
663 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
667 // Otherwise, no immediates to move.
671 /// IncrementAddExprUses - Decompose the specified expression into its added
672 /// subexpressions, and increment SubExpressionUseCounts for each of these
673 /// decomposed parts.
674 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
676 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
677 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
678 SeparateSubExprs(SubExprs, AE->getOperand(j));
679 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
680 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
681 if (SARE->getOperand(0) == Zero) {
682 SubExprs.push_back(Expr);
684 // Compute the addrec with zero as its base.
685 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
686 Ops[0] = Zero; // Start with zero base.
687 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
690 SeparateSubExprs(SubExprs, SARE->getOperand(0));
692 } else if (!isa<SCEVConstant>(Expr) ||
693 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
695 SubExprs.push_back(Expr);
700 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
701 /// removing any common subexpressions from it. Anything truly common is
702 /// removed, accumulated, and returned. This looks for things like (a+b+c) and
703 /// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
705 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
706 unsigned NumUses = Uses.size();
708 // Only one use? Use its base, regardless of what it is!
709 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
710 SCEVHandle Result = Zero;
712 std::swap(Result, Uses[0].Base);
716 // To find common subexpressions, count how many of Uses use each expression.
717 // If any subexpressions are used Uses.size() times, they are common.
718 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
720 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
721 // order we see them.
722 std::vector<SCEVHandle> UniqueSubExprs;
724 std::vector<SCEVHandle> SubExprs;
725 for (unsigned i = 0; i != NumUses; ++i) {
726 // If the base is zero (which is common), return zero now, there are no
728 if (Uses[i].Base == Zero) return Zero;
730 // Split the expression into subexprs.
731 SeparateSubExprs(SubExprs, Uses[i].Base);
732 // Add one to SubExpressionUseCounts for each subexpr present.
733 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
734 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
735 UniqueSubExprs.push_back(SubExprs[j]);
739 // Now that we know how many times each is used, build Result. Iterate over
740 // UniqueSubexprs so that we have a stable ordering.
741 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
742 std::map<SCEVHandle, unsigned>::iterator I =
743 SubExpressionUseCounts.find(UniqueSubExprs[i]);
744 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
745 if (I->second == NumUses) { // Found CSE!
746 Result = SCEVAddExpr::get(Result, I->first);
748 // Remove non-cse's from SubExpressionUseCounts.
749 SubExpressionUseCounts.erase(I);
753 // If we found no CSE's, return now.
754 if (Result == Zero) return Result;
756 // Otherwise, remove all of the CSE's we found from each of the base values.
757 for (unsigned i = 0; i != NumUses; ++i) {
758 // Split the expression into subexprs.
759 SeparateSubExprs(SubExprs, Uses[i].Base);
761 // Remove any common subexpressions.
762 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
763 if (SubExpressionUseCounts.count(SubExprs[j])) {
764 SubExprs.erase(SubExprs.begin()+j);
768 // Finally, the non-shared expressions together.
769 if (SubExprs.empty())
772 Uses[i].Base = SCEVAddExpr::get(SubExprs);
780 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
781 /// stride of IV. All of the users may have different starting values, and this
782 /// may not be the only stride (we know it is if isOnlyStride is true).
783 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
784 IVUsersOfOneStride &Uses,
787 // Transform our list of users and offsets to a bit more complex table. In
788 // this new vector, each 'BasedUser' contains 'Base' the base of the
789 // strided accessas well as the old information from Uses. We progressively
790 // move information from the Base field to the Imm field, until we eventually
791 // have the full access expression to rewrite the use.
792 std::vector<BasedUser> UsersToProcess;
793 UsersToProcess.reserve(Uses.Users.size());
794 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
795 UsersToProcess.push_back(Uses.Users[i]);
797 // Move any loop invariant operands from the offset field to the immediate
798 // field of the use, so that we don't try to use something before it is
800 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
801 UsersToProcess.back().Imm, L);
802 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
803 "Base value is not loop invariant!");
806 // We now have a whole bunch of uses of like-strided induction variables, but
807 // they might all have different bases. We want to emit one PHI node for this
808 // stride which we fold as many common expressions (between the IVs) into as
809 // possible. Start by identifying the common expressions in the base values
810 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
811 // "A+B"), emit it to the preheader, then remove the expression from the
812 // UsersToProcess base values.
813 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
815 // Next, figure out what we can represent in the immediate fields of
816 // instructions. If we can represent anything there, move it to the imm
817 // fields of the BasedUsers. We do this so that it increases the commonality
818 // of the remaining uses.
819 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
820 // If the user is not in the current loop, this means it is using the exit
821 // value of the IV. Do not put anything in the base, make sure it's all in
822 // the immediate field to allow as much factoring as possible.
823 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
824 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
825 UsersToProcess[i].Base);
826 UsersToProcess[i].Base =
827 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
830 // Addressing modes can be folded into loads and stores. Be careful that
831 // the store is through the expression, not of the expression though.
832 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
833 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
834 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
837 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
842 // Now that we know what we need to do, insert the PHI node itself.
844 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
845 << *CommonExprs << " :\n");
847 SCEVExpander Rewriter(*SE, *LI);
848 SCEVExpander PreheaderRewriter(*SE, *LI);
850 BasicBlock *Preheader = L->getLoopPreheader();
851 Instruction *PreInsertPt = Preheader->getTerminator();
852 Instruction *PhiInsertBefore = L->getHeader()->begin();
854 BasicBlock *LatchBlock = L->getLoopLatch();
856 // Create a new Phi for this base, and stick it in the loop header.
857 const Type *ReplacedTy = CommonExprs->getType();
858 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
861 // Insert the stride into the preheader.
862 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
864 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
867 // Emit the initial base value into the loop preheader, and add it to the
869 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
871 NewPHI->addIncoming(PHIBaseV, Preheader);
873 // Emit the increment of the base value before the terminator of the loop
874 // latch block, and add it to the Phi node.
875 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
876 SCEVUnknown::get(StrideV));
878 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
880 IncV->setName(NewPHI->getName()+".inc");
881 NewPHI->addIncoming(IncV, LatchBlock);
883 // Sort by the base value, so that all IVs with identical bases are next to
885 while (!UsersToProcess.empty()) {
886 SCEVHandle Base = UsersToProcess.back().Base;
888 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
890 // Emit the code for Base into the preheader.
891 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
894 // If BaseV is a constant other than 0, make sure that it gets inserted into
895 // the preheader, instead of being forward substituted into the uses. We do
896 // this by forcing a noop cast to be inserted into the preheader in this
898 if (Constant *C = dyn_cast<Constant>(BaseV))
899 if (!C->isNullValue() && !isTargetConstant(Base)) {
900 // We want this constant emitted into the preheader!
901 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
905 // Emit the code to add the immediate offset to the Phi value, just before
906 // the instructions that we identified as using this stride and base.
907 unsigned ScanPos = 0;
909 BasedUser &User = UsersToProcess.back();
911 // If this instruction wants to use the post-incremented value, move it
912 // after the post-inc and use its value instead of the PHI.
913 Value *RewriteOp = NewPHI;
914 if (User.isUseOfPostIncrementedValue) {
917 // If this user is in the loop, make sure it is the last thing in the
918 // loop to ensure it is dominated by the increment.
919 if (L->contains(User.Inst->getParent()))
920 User.Inst->moveBefore(LatchBlock->getTerminator());
922 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
924 // Clear the SCEVExpander's expression map so that we are guaranteed
925 // to have the code emitted where we expect it.
928 // Now that we know what we need to do, insert code before User for the
929 // immediate and any loop-variant expressions.
930 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
931 // Add BaseV to the PHI value if needed.
932 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
934 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
936 // Mark old value we replaced as possibly dead, so that it is elminated
937 // if we just replaced the last use of that value.
938 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
940 UsersToProcess.pop_back();
943 // If there are any more users to process with the same base, move one of
944 // them to the end of the list so that we will process it.
945 if (!UsersToProcess.empty()) {
946 for (unsigned e = UsersToProcess.size(); ScanPos != e; ++ScanPos)
947 if (UsersToProcess[ScanPos].Base == Base) {
948 std::swap(UsersToProcess[ScanPos], UsersToProcess.back());
952 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
953 // TODO: Next, find out which base index is the most common, pull it out.
956 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
957 // different starting values, into different PHIs.
960 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
961 // uses in the loop, look to see if we can eliminate some, in favor of using
962 // common indvars for the different uses.
963 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
964 // TODO: implement optzns here.
969 // Finally, get the terminating condition for the loop if possible. If we
970 // can, we want to change it to use a post-incremented version of its
971 // induction variable, to allow coallescing the live ranges for the IV into
972 // one register value.
973 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
974 BasicBlock *Preheader = L->getLoopPreheader();
975 BasicBlock *LatchBlock =
976 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
977 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
978 if (!TermBr || TermBr->isUnconditional() ||
979 !isa<SetCondInst>(TermBr->getCondition()))
981 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
983 // Search IVUsesByStride to find Cond's IVUse if there is one.
984 IVStrideUse *CondUse = 0;
985 const SCEVHandle *CondStride = 0;
987 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
989 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
990 IVUsesByStride.find(StrideOrder[Stride]);
991 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
993 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
994 E = SI->second.Users.end(); UI != E; ++UI)
995 if (UI->User == Cond) {
997 CondStride = &SI->first;
998 // NOTE: we could handle setcc instructions with multiple uses here, but
999 // InstCombine does it as well for simple uses, it's not clear that it
1000 // occurs enough in real life to handle.
1004 if (!CondUse) return; // setcc doesn't use the IV.
1006 // setcc stride is complex, don't mess with users.
1007 // FIXME: Evaluate whether this is a good idea or not.
1008 if (!isa<SCEVConstant>(*CondStride)) return;
1010 // It's possible for the setcc instruction to be anywhere in the loop, and
1011 // possible for it to have multiple users. If it is not immediately before
1012 // the latch block branch, move it.
1013 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1014 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1015 Cond->moveBefore(TermBr);
1017 // Otherwise, clone the terminating condition and insert into the loopend.
1018 Cond = cast<SetCondInst>(Cond->clone());
1019 Cond->setName(L->getHeader()->getName() + ".termcond");
1020 LatchBlock->getInstList().insert(TermBr, Cond);
1022 // Clone the IVUse, as the old use still exists!
1023 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1024 CondUse->OperandValToReplace);
1025 CondUse = &IVUsesByStride[*CondStride].Users.back();
1029 // If we get to here, we know that we can transform the setcc instruction to
1030 // use the post-incremented version of the IV, allowing us to coallesce the
1031 // live ranges for the IV correctly.
1032 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
1033 CondUse->isUseOfPostIncrementedValue = true;
1036 void LoopStrengthReduce::runOnLoop(Loop *L) {
1037 // First step, transform all loops nesting inside of this loop.
1038 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1041 // Next, find all uses of induction variables in this loop, and catagorize
1042 // them by stride. Start by finding all of the PHI nodes in the header for
1043 // this loop. If they are induction variables, inspect their uses.
1044 std::set<Instruction*> Processed; // Don't reprocess instructions.
1045 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1046 AddUsersIfInteresting(I, L, Processed);
1048 // If we have nothing to do, return.
1049 if (IVUsesByStride.empty()) return;
1051 // Optimize induction variables. Some indvar uses can be transformed to use
1052 // strides that will be needed for other purposes. A common example of this
1053 // is the exit test for the loop, which can often be rewritten to use the
1054 // computation of some other indvar to decide when to terminate the loop.
1058 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1059 // doing computation in byte values, promote to 32-bit values if safe.
1061 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1062 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1063 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1064 // to be careful that IV's are all the same type. Only works for intptr_t
1067 // If we only have one stride, we can more aggressively eliminate some things.
1068 bool HasOneStride = IVUsesByStride.size() == 1;
1070 // Note: this processes each stride/type pair individually. All users passed
1071 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1072 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1073 // This extra layer of indirection makes the ordering of strides deterministic
1074 // - not dependent on map order.
1075 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1076 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1077 IVUsesByStride.find(StrideOrder[Stride]);
1078 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1079 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1082 // Clean up after ourselves
1083 if (!DeadInsts.empty()) {
1084 DeleteTriviallyDeadInstructions(DeadInsts);
1086 BasicBlock::iterator I = L->getHeader()->begin();
1088 while ((PN = dyn_cast<PHINode>(I))) {
1089 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1091 // At this point, we know that we have killed one or more GEP
1092 // instructions. It is worth checking to see if the cann indvar is also
1093 // dead, so that we can remove it as well. The requirements for the cann
1094 // indvar to be considered dead are:
1095 // 1. the cann indvar has one use
1096 // 2. the use is an add instruction
1097 // 3. the add has one use
1098 // 4. the add is used by the cann indvar
1099 // If all four cases above are true, then we can remove both the add and
1101 // FIXME: this needs to eliminate an induction variable even if it's being
1102 // compared against some value to decide loop termination.
1103 if (PN->hasOneUse()) {
1104 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
1105 if (BO && BO->hasOneUse()) {
1106 if (PN == *(BO->use_begin())) {
1107 DeadInsts.insert(BO);
1108 // Break the cycle, then delete the PHI.
1109 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1110 SE->deleteInstructionFromRecords(PN);
1111 PN->eraseFromParent();
1116 DeleteTriviallyDeadInstructions(DeadInsts);
1119 CastedPointers.clear();
1120 IVUsesByStride.clear();
1121 StrideOrder.clear();