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.
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 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
95 /// of the casted version of each value. This is accessed by
96 /// getCastedVersionOf.
97 std::map<Value*, Value*> CastedPointers;
99 /// DeadInsts - Keep track of instructions we may have made dead, so that
100 /// we can remove them after we are done working.
101 std::set<Instruction*> DeadInsts;
103 LoopStrengthReduce(unsigned MTAMS = 1)
104 : MaxTargetAMSize(MTAMS) {
107 virtual bool runOnFunction(Function &) {
108 LI = &getAnalysis<LoopInfo>();
109 DS = &getAnalysis<DominatorSet>();
110 SE = &getAnalysis<ScalarEvolution>();
111 TD = &getAnalysis<TargetData>();
112 UIntPtrTy = TD->getIntPtrType();
115 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
122 AU.setPreservesCFG();
123 AU.addRequiredID(LoopSimplifyID);
124 AU.addRequired<LoopInfo>();
125 AU.addRequired<DominatorSet>();
126 AU.addRequired<TargetData>();
127 AU.addRequired<ScalarEvolution>();
130 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
132 Value *getCastedVersionOf(Value *V);
134 void runOnLoop(Loop *L);
135 bool AddUsersIfInteresting(Instruction *I, Loop *L,
136 std::set<Instruction*> &Processed);
137 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
139 void OptimizeIndvars(Loop *L);
141 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
142 IVUsersOfOneStride &Uses,
143 Loop *L, bool isOnlyStride);
144 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
146 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
147 "Strength Reduce GEP Uses of Ind. Vars");
150 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
151 return new LoopStrengthReduce(MaxTargetAMSize);
154 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
156 Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
157 if (V->getType() == UIntPtrTy) return V;
158 if (Constant *CB = dyn_cast<Constant>(V))
159 return ConstantExpr::getCast(CB, UIntPtrTy);
161 Value *&New = CastedPointers[V];
164 BasicBlock::iterator InsertPt;
165 if (Argument *Arg = dyn_cast<Argument>(V)) {
166 // Insert into the entry of the function, after any allocas.
167 InsertPt = Arg->getParent()->begin()->begin();
168 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
170 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
171 InsertPt = II->getNormalDest()->begin();
173 InsertPt = cast<Instruction>(V);
177 // Do not insert casts into the middle of PHI node blocks.
178 while (isa<PHINode>(InsertPt)) ++InsertPt;
181 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
182 DeadInsts.insert(cast<Instruction>(New));
187 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
188 /// specified set are trivially dead, delete them and see if this makes any of
189 /// their operands subsequently dead.
190 void LoopStrengthReduce::
191 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
192 while (!Insts.empty()) {
193 Instruction *I = *Insts.begin();
194 Insts.erase(Insts.begin());
195 if (isInstructionTriviallyDead(I)) {
196 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
197 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
199 SE->deleteInstructionFromRecords(I);
200 I->eraseFromParent();
207 /// GetExpressionSCEV - Compute and return the SCEV for the specified
209 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
210 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
211 // If this is a GEP that SE doesn't know about, compute it now and insert it.
212 // If this is not a GEP, or if we have already done this computation, just let
214 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
215 if (!GEP || SE->hasSCEV(GEP))
216 return SE->getSCEV(Exp);
218 // Analyze all of the subscripts of this getelementptr instruction, looking
219 // for uses that are determined by the trip count of L. First, skip all
220 // operands the are not dependent on the IV.
222 // Build up the base expression. Insert an LLVM cast of the pointer to
224 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
226 gep_type_iterator GTI = gep_type_begin(GEP);
228 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
229 // If this is a use of a recurrence that we can analyze, and it comes before
230 // Op does in the GEP operand list, we will handle this when we process this
232 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
233 const StructLayout *SL = TD->getStructLayout(STy);
234 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
235 uint64_t Offset = SL->MemberOffsets[Idx];
236 GEPVal = SCEVAddExpr::get(GEPVal,
237 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
239 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
240 SCEVHandle Idx = SE->getSCEV(OpVal);
242 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
244 Idx = SCEVMulExpr::get(Idx,
245 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
247 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
251 SE->setSCEV(GEP, GEPVal);
255 /// getSCEVStartAndStride - Compute the start and stride of this expression,
256 /// returning false if the expression is not a start/stride pair, or true if it
257 /// is. The stride must be a loop invariant expression, but the start may be
258 /// a mix of loop invariant and loop variant expressions.
259 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
260 SCEVHandle &Start, SCEVHandle &Stride) {
261 SCEVHandle TheAddRec = Start; // Initialize to zero.
263 // If the outer level is an AddExpr, the operands are all start values except
264 // for a nested AddRecExpr.
265 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
266 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
267 if (SCEVAddRecExpr *AddRec =
268 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
269 if (AddRec->getLoop() == L)
270 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
272 return false; // Nested IV of some sort?
274 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
277 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
280 return false; // not analyzable.
283 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
284 if (!AddRec || AddRec->getLoop() != L) return false;
286 // FIXME: Generalize to non-affine IV's.
287 if (!AddRec->isAffine()) return false;
289 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
291 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
292 DEBUG(std::cerr << "[" << L->getHeader()->getName()
293 << "] Variable stride: " << *AddRec << "\n");
295 Stride = AddRec->getOperand(1);
296 // Check that all constant strides are the unsigned type, we don't want to
297 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
299 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
300 "Constants should be canonicalized to unsigned!");
305 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
306 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
307 /// return true. Otherwise, return false.
308 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
309 std::set<Instruction*> &Processed) {
310 if (I->getType() == Type::VoidTy) return false;
311 if (!Processed.insert(I).second)
312 return true; // Instruction already handled.
314 // Get the symbolic expression for this instruction.
315 SCEVHandle ISE = GetExpressionSCEV(I, L);
316 if (isa<SCEVCouldNotCompute>(ISE)) return false;
318 // Get the start and stride for this expression.
319 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
320 SCEVHandle Stride = Start;
321 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
322 return false; // Non-reducible symbolic expression, bail out.
324 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
325 Instruction *User = cast<Instruction>(*UI);
327 // Do not infinitely recurse on PHI nodes.
328 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
331 // If this is an instruction defined in a nested loop, or outside this loop,
332 // don't recurse into it.
333 bool AddUserToIVUsers = false;
334 if (LI->getLoopFor(User->getParent()) != L) {
335 DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
336 << " OF SCEV: " << *ISE << "\n");
337 AddUserToIVUsers = true;
338 } else if (!AddUsersIfInteresting(User, L, Processed)) {
339 DEBUG(std::cerr << "FOUND USER: " << *User
340 << " OF SCEV: " << *ISE << "\n");
341 AddUserToIVUsers = true;
344 if (AddUserToIVUsers) {
345 // Okay, we found a user that we cannot reduce. Analyze the instruction
346 // and decide what to do with it.
347 IVUsesByStride[Stride].addUser(Start, User, I);
354 /// BasedUser - For a particular base value, keep information about how we've
355 /// partitioned the expression so far.
357 /// Base - The Base value for the PHI node that needs to be inserted for
358 /// this use. As the use is processed, information gets moved from this
359 /// field to the Imm field (below). BasedUser values are sorted by this
363 /// Inst - The instruction using the induction variable.
366 /// OperandValToReplace - The operand value of Inst to replace with the
368 Value *OperandValToReplace;
370 /// Imm - The immediate value that should be added to the base immediately
371 /// before Inst, because it will be folded into the imm field of the
375 /// EmittedBase - The actual value* to use for the base value of this
376 /// operation. This is null if we should just use zero so far.
379 // isUseOfPostIncrementedValue - True if this should use the
380 // post-incremented version of this IV, not the preincremented version.
381 // This can only be set in special cases, such as the terminating setcc
382 // instruction for a loop.
383 bool isUseOfPostIncrementedValue;
385 BasedUser(IVStrideUse &IVSU)
386 : Base(IVSU.Offset), Inst(IVSU.User),
387 OperandValToReplace(IVSU.OperandValToReplace),
388 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
389 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
391 // Once we rewrite the code to insert the new IVs we want, update the
392 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
394 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
395 SCEVExpander &Rewriter, Loop *L,
398 // Sort by the Base field.
399 bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
405 void BasedUser::dump() const {
406 std::cerr << " Base=" << *Base;
407 std::cerr << " Imm=" << *Imm;
409 std::cerr << " EB=" << *EmittedBase;
411 std::cerr << " Inst: " << *Inst;
414 // Once we rewrite the code to insert the new IVs we want, update the
415 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
417 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
418 SCEVExpander &Rewriter,
420 if (!isa<PHINode>(Inst)) {
421 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
422 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
423 OperandValToReplace->getType());
424 // Replace the use of the operand Value with the new Phi we just created.
425 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
426 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
430 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
431 // expression into each operand block that uses it. Note that PHI nodes can
432 // have multiple entries for the same predecessor. We use a map to make sure
433 // that a PHI node only has a single Value* for each predecessor (which also
434 // prevents us from inserting duplicate code in some blocks).
435 std::map<BasicBlock*, Value*> InsertedCode;
436 PHINode *PN = cast<PHINode>(Inst);
437 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
438 if (PN->getIncomingValue(i) == OperandValToReplace) {
439 // If this is a critical edge, split the edge so that we do not insert the
440 // code on all predecessor/successor paths.
442 PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() > 1) {
443 TerminatorInst *PredTI = PN->getIncomingBlock(i)->getTerminator();
444 for (unsigned Succ = 0; ; ++Succ) {
445 assert(Succ != PredTI->getNumSuccessors() &&"Didn't find successor?");
446 if (PredTI->getSuccessor(Succ) == PN->getParent()) {
447 // First step, split the critical edge.
448 SplitCriticalEdge(PredTI, Succ, P);
450 // Next step: move the basic block. In particular, if the PHI node
451 // is outside of the loop, and PredTI is in the loop, we want to
452 // move the block to be immediately before the PHI block, not
453 // immediately after PredTI.
454 if (L->contains(PredTI->getParent()) &&
455 !L->contains(PN->getParent())) {
456 BasicBlock *NewBB = PN->getIncomingBlock(i);
457 NewBB->moveBefore(PN->getParent());
464 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
466 // Insert the code into the end of the predecessor block.
467 BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
469 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
470 Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
471 OperandValToReplace->getType());
474 // Replace the use of the operand Value with the new Phi we just created.
475 PN->setIncomingValue(i, Code);
479 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
483 /// isTargetConstant - Return true if the following can be referenced by the
484 /// immediate field of a target instruction.
485 static bool isTargetConstant(const SCEVHandle &V) {
487 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
488 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
489 // PPC allows a sign-extended 16-bit immediate field.
490 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
491 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
496 return false; // ENABLE this for x86
498 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
499 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
500 if (CE->getOpcode() == Instruction::Cast)
501 if (isa<GlobalValue>(CE->getOperand(0)))
502 // FIXME: should check to see that the dest is uintptr_t!
507 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
508 /// loop varying to the Imm operand.
509 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
511 if (Val->isLoopInvariant(L)) return; // Nothing to do.
513 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
514 std::vector<SCEVHandle> NewOps;
515 NewOps.reserve(SAE->getNumOperands());
517 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
518 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
519 // If this is a loop-variant expression, it must stay in the immediate
520 // field of the expression.
521 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
523 NewOps.push_back(SAE->getOperand(i));
527 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
529 Val = SCEVAddExpr::get(NewOps);
530 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
531 // Try to pull immediates out of the start value of nested addrec's.
532 SCEVHandle Start = SARE->getStart();
533 MoveLoopVariantsToImediateField(Start, Imm, L);
535 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
537 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
539 // Otherwise, all of Val is variant, move the whole thing over.
540 Imm = SCEVAddExpr::get(Imm, Val);
541 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
546 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
547 /// that can fit into the immediate field of instructions in the target.
548 /// Accumulate these immediate values into the Imm value.
549 static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
550 bool isAddress, Loop *L) {
551 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
552 std::vector<SCEVHandle> NewOps;
553 NewOps.reserve(SAE->getNumOperands());
555 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
556 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
557 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
558 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
559 // If this is a loop-variant expression, it must stay in the immediate
560 // field of the expression.
561 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
563 NewOps.push_back(SAE->getOperand(i));
567 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
569 Val = SCEVAddExpr::get(NewOps);
571 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
572 // Try to pull immediates out of the start value of nested addrec's.
573 SCEVHandle Start = SARE->getStart();
574 MoveImmediateValues(Start, Imm, isAddress, L);
576 if (Start != SARE->getStart()) {
577 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
579 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
584 // Loop-variant expressions must stay in the immediate field of the
586 if ((isAddress && isTargetConstant(Val)) ||
587 !Val->isLoopInvariant(L)) {
588 Imm = SCEVAddExpr::get(Imm, Val);
589 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
593 // Otherwise, no immediates to move.
597 /// IncrementAddExprUses - Decompose the specified expression into its added
598 /// subexpressions, and increment SubExpressionUseCounts for each of these
599 /// decomposed parts.
600 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
602 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
603 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
604 SeparateSubExprs(SubExprs, AE->getOperand(j));
605 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
606 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
607 if (SARE->getOperand(0) == Zero) {
608 SubExprs.push_back(Expr);
610 // Compute the addrec with zero as its base.
611 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
612 Ops[0] = Zero; // Start with zero base.
613 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
616 SeparateSubExprs(SubExprs, SARE->getOperand(0));
618 } else if (!isa<SCEVConstant>(Expr) ||
619 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
621 SubExprs.push_back(Expr);
626 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
627 /// removing any common subexpressions from it. Anything truly common is
628 /// removed, accumulated, and returned. This looks for things like (a+b+c) and
629 /// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
631 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
632 unsigned NumUses = Uses.size();
634 // Only one use? Use its base, regardless of what it is!
635 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
636 SCEVHandle Result = Zero;
638 std::swap(Result, Uses[0].Base);
642 // To find common subexpressions, count how many of Uses use each expression.
643 // If any subexpressions are used Uses.size() times, they are common.
644 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
646 std::vector<SCEVHandle> SubExprs;
647 for (unsigned i = 0; i != NumUses; ++i) {
648 // If the base is zero (which is common), return zero now, there are no
650 if (Uses[i].Base == Zero) return Zero;
652 // Split the expression into subexprs.
653 SeparateSubExprs(SubExprs, Uses[i].Base);
654 // Add one to SubExpressionUseCounts for each subexpr present.
655 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
656 SubExpressionUseCounts[SubExprs[j]]++;
661 // Now that we know how many times each is used, build Result.
662 for (std::map<SCEVHandle, unsigned>::iterator I =
663 SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
665 if (I->second == NumUses) { // Found CSE!
666 Result = SCEVAddExpr::get(Result, I->first);
669 // Remove non-cse's from SubExpressionUseCounts.
670 SubExpressionUseCounts.erase(I++);
673 // If we found no CSE's, return now.
674 if (Result == Zero) return Result;
676 // Otherwise, remove all of the CSE's we found from each of the base values.
677 for (unsigned i = 0; i != NumUses; ++i) {
678 // Split the expression into subexprs.
679 SeparateSubExprs(SubExprs, Uses[i].Base);
681 // Remove any common subexpressions.
682 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
683 if (SubExpressionUseCounts.count(SubExprs[j])) {
684 SubExprs.erase(SubExprs.begin()+j);
688 // Finally, the non-shared expressions together.
689 if (SubExprs.empty())
692 Uses[i].Base = SCEVAddExpr::get(SubExprs);
700 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
701 /// stride of IV. All of the users may have different starting values, and this
702 /// may not be the only stride (we know it is if isOnlyStride is true).
703 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
704 IVUsersOfOneStride &Uses,
707 // Transform our list of users and offsets to a bit more complex table. In
708 // this new vector, each 'BasedUser' contains 'Base' the base of the
709 // strided accessas well as the old information from Uses. We progressively
710 // move information from the Base field to the Imm field, until we eventually
711 // have the full access expression to rewrite the use.
712 std::vector<BasedUser> UsersToProcess;
713 UsersToProcess.reserve(Uses.Users.size());
714 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
715 UsersToProcess.push_back(Uses.Users[i]);
717 // Move any loop invariant operands from the offset field to the immediate
718 // field of the use, so that we don't try to use something before it is
720 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
721 UsersToProcess.back().Imm, L);
722 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
723 "Base value is not loop invariant!");
726 // We now have a whole bunch of uses of like-strided induction variables, but
727 // they might all have different bases. We want to emit one PHI node for this
728 // stride which we fold as many common expressions (between the IVs) into as
729 // possible. Start by identifying the common expressions in the base values
730 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
731 // "A+B"), emit it to the preheader, then remove the expression from the
732 // UsersToProcess base values.
733 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
735 // Next, figure out what we can represent in the immediate fields of
736 // instructions. If we can represent anything there, move it to the imm
737 // fields of the BasedUsers. We do this so that it increases the commonality
738 // of the remaining uses.
739 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
740 // Addressing modes can be folded into loads and stores. Be careful that
741 // the store is through the expression, not of the expression though.
742 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
743 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
744 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
747 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
751 // Now that we know what we need to do, insert the PHI node itself.
753 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
754 << *CommonExprs << " :\n");
756 SCEVExpander Rewriter(*SE, *LI);
757 SCEVExpander PreheaderRewriter(*SE, *LI);
759 BasicBlock *Preheader = L->getLoopPreheader();
760 Instruction *PreInsertPt = Preheader->getTerminator();
761 Instruction *PhiInsertBefore = L->getHeader()->begin();
763 assert(isa<PHINode>(PhiInsertBefore) &&
764 "How could this loop have IV's without any phis?");
765 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
766 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
767 "This loop isn't canonicalized right");
768 BasicBlock *LatchBlock =
769 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
771 // Create a new Phi for this base, and stick it in the loop header.
772 const Type *ReplacedTy = CommonExprs->getType();
773 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
776 // Insert the stride into the preheader.
777 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
779 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
782 // Emit the initial base value into the loop preheader, and add it to the
784 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
786 NewPHI->addIncoming(PHIBaseV, Preheader);
788 // Emit the increment of the base value before the terminator of the loop
789 // latch block, and add it to the Phi node.
790 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
791 SCEVUnknown::get(StrideV));
793 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
795 IncV->setName(NewPHI->getName()+".inc");
796 NewPHI->addIncoming(IncV, LatchBlock);
798 // Sort by the base value, so that all IVs with identical bases are next to
800 std::sort(UsersToProcess.begin(), UsersToProcess.end());
801 while (!UsersToProcess.empty()) {
802 SCEVHandle Base = UsersToProcess.front().Base;
804 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
806 // Emit the code for Base into the preheader.
807 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
810 // If BaseV is a constant other than 0, make sure that it gets inserted into
811 // the preheader, instead of being forward substituted into the uses. We do
812 // this by forcing a noop cast to be inserted into the preheader in this
814 if (Constant *C = dyn_cast<Constant>(BaseV))
815 if (!C->isNullValue()) {
816 // We want this constant emitted into the preheader!
817 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
821 // Emit the code to add the immediate offset to the Phi value, just before
822 // the instructions that we identified as using this stride and base.
823 while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
824 BasedUser &User = UsersToProcess.front();
826 // If this instruction wants to use the post-incremented value, move it
827 // after the post-inc and use its value instead of the PHI.
828 Value *RewriteOp = NewPHI;
829 if (User.isUseOfPostIncrementedValue) {
831 User.Inst->moveBefore(LatchBlock->getTerminator());
833 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
835 // Clear the SCEVExpander's expression map so that we are guaranteed
836 // to have the code emitted where we expect it.
839 // Now that we know what we need to do, insert code before User for the
840 // immediate and any loop-variant expressions.
841 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
842 // Add BaseV to the PHI value if needed.
843 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
845 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
847 // Mark old value we replaced as possibly dead, so that it is elminated
848 // if we just replaced the last use of that value.
849 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
851 UsersToProcess.erase(UsersToProcess.begin());
854 // TODO: Next, find out which base index is the most common, pull it out.
857 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
858 // different starting values, into different PHIs.
861 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
862 // uses in the loop, look to see if we can eliminate some, in favor of using
863 // common indvars for the different uses.
864 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
865 // TODO: implement optzns here.
870 // Finally, get the terminating condition for the loop if possible. If we
871 // can, we want to change it to use a post-incremented version of its
872 // induction variable, to allow coallescing the live ranges for the IV into
873 // one register value.
874 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
875 BasicBlock *Preheader = L->getLoopPreheader();
876 BasicBlock *LatchBlock =
877 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
878 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
879 if (!TermBr || TermBr->isUnconditional() ||
880 !isa<SetCondInst>(TermBr->getCondition()))
882 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
884 // Search IVUsesByStride to find Cond's IVUse if there is one.
885 IVStrideUse *CondUse = 0;
886 const SCEVHandle *CondStride = 0;
888 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator
889 I = IVUsesByStride.begin(), E = IVUsesByStride.end();
890 I != E && !CondUse; ++I)
891 for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
892 E = I->second.Users.end(); UI != E; ++UI)
893 if (UI->User == Cond) {
895 CondStride = &I->first;
896 // NOTE: we could handle setcc instructions with multiple uses here, but
897 // InstCombine does it as well for simple uses, it's not clear that it
898 // occurs enough in real life to handle.
901 if (!CondUse) return; // setcc doesn't use the IV.
903 // setcc stride is complex, don't mess with users.
904 // FIXME: Evaluate whether this is a good idea or not.
905 if (!isa<SCEVConstant>(*CondStride)) return;
907 // It's possible for the setcc instruction to be anywhere in the loop, and
908 // possible for it to have multiple users. If it is not immediately before
909 // the latch block branch, move it.
910 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
911 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
912 Cond->moveBefore(TermBr);
914 // Otherwise, clone the terminating condition and insert into the loopend.
915 Cond = cast<SetCondInst>(Cond->clone());
916 Cond->setName(L->getHeader()->getName() + ".termcond");
917 LatchBlock->getInstList().insert(TermBr, Cond);
919 // Clone the IVUse, as the old use still exists!
920 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
921 CondUse->OperandValToReplace);
922 CondUse = &IVUsesByStride[*CondStride].Users.back();
926 // If we get to here, we know that we can transform the setcc instruction to
927 // use the post-incremented version of the IV, allowing us to coallesce the
928 // live ranges for the IV correctly.
929 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
930 CondUse->isUseOfPostIncrementedValue = true;
933 void LoopStrengthReduce::runOnLoop(Loop *L) {
934 // First step, transform all loops nesting inside of this loop.
935 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
938 // Next, find all uses of induction variables in this loop, and catagorize
939 // them by stride. Start by finding all of the PHI nodes in the header for
940 // this loop. If they are induction variables, inspect their uses.
941 std::set<Instruction*> Processed; // Don't reprocess instructions.
942 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
943 AddUsersIfInteresting(I, L, Processed);
945 // If we have nothing to do, return.
946 if (IVUsesByStride.empty()) return;
948 // Optimize induction variables. Some indvar uses can be transformed to use
949 // strides that will be needed for other purposes. A common example of this
950 // is the exit test for the loop, which can often be rewritten to use the
951 // computation of some other indvar to decide when to terminate the loop.
955 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
956 // doing computation in byte values, promote to 32-bit values if safe.
958 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
959 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
960 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
961 // to be careful that IV's are all the same type. Only works for intptr_t
964 // If we only have one stride, we can more aggressively eliminate some things.
965 bool HasOneStride = IVUsesByStride.size() == 1;
967 // Note: this processes each stride/type pair individually. All users passed
968 // into StrengthReduceStridedIVUsers have the same type AND stride.
969 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI
970 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
971 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
973 // Clean up after ourselves
974 if (!DeadInsts.empty()) {
975 DeleteTriviallyDeadInstructions(DeadInsts);
977 BasicBlock::iterator I = L->getHeader()->begin();
979 while ((PN = dyn_cast<PHINode>(I))) {
980 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
982 // At this point, we know that we have killed one or more GEP
983 // instructions. It is worth checking to see if the cann indvar is also
984 // dead, so that we can remove it as well. The requirements for the cann
985 // indvar to be considered dead are:
986 // 1. the cann indvar has one use
987 // 2. the use is an add instruction
988 // 3. the add has one use
989 // 4. the add is used by the cann indvar
990 // If all four cases above are true, then we can remove both the add and
992 // FIXME: this needs to eliminate an induction variable even if it's being
993 // compared against some value to decide loop termination.
994 if (PN->hasOneUse()) {
995 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
996 if (BO && BO->hasOneUse()) {
997 if (PN == *(BO->use_begin())) {
998 DeadInsts.insert(BO);
999 // Break the cycle, then delete the PHI.
1000 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1001 SE->deleteInstructionFromRecords(PN);
1002 PN->eraseFromParent();
1007 DeleteTriviallyDeadInstructions(DeadInsts);
1010 CastedPointers.clear();
1011 IVUsesByStride.clear();