75a681d98ec6d75068cfcf749009936f919531bd
[oota-llvm.git] / lib / Transforms / Scalar / LoopStrengthReduce.cpp
1 //===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
15 //
16 //===----------------------------------------------------------------------===//
17
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"
34 #include <algorithm>
35 #include <set>
36 using namespace llvm;
37
38 namespace {
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");
42
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.
47   struct IVStrideUse {
48     SCEVHandle Offset;
49     Instruction *User;
50     Value *OperandValToReplace;
51
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;
57     
58     IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
59       : Offset(Offs), User(U), OperandValToReplace(O),
60         isUseOfPostIncrementedValue(false) {}
61   };
62   
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
66   /// structure.
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;
71     
72     void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
73       Users.push_back(IVStrideUse(Offset, User, Operand));
74     }
75   };
76
77
78   class LoopStrengthReduce : public FunctionPass {
79     LoopInfo *LI;
80     DominatorSet *DS;
81     ScalarEvolution *SE;
82     const TargetData *TD;
83     const Type *UIntPtrTy;
84     bool Changed;
85
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;
89
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;
93
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;
98
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;
102   public:
103     LoopStrengthReduce(unsigned MTAMS = 1)
104       : MaxTargetAMSize(MTAMS) {
105     }
106
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();
113       Changed = false;
114
115       for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
116         runOnLoop(*I);
117       
118       return Changed;
119     }
120
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>();
128     }
129     
130     /// getCastedVersionOf - Return the specified value casted to uintptr_t.
131     ///
132     Value *getCastedVersionOf(Value *V);
133 private:
134     void runOnLoop(Loop *L);
135     bool AddUsersIfInteresting(Instruction *I, Loop *L,
136                                std::set<Instruction*> &Processed);
137     SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
138
139     void OptimizeIndvars(Loop *L);
140
141     void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
142                                       IVUsersOfOneStride &Uses,
143                                       Loop *L, bool isOnlyStride);
144     void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
145   };
146   RegisterOpt<LoopStrengthReduce> X("loop-reduce",
147                                     "Strength Reduce GEP Uses of Ind. Vars");
148 }
149
150 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
151   return new LoopStrengthReduce(MaxTargetAMSize);
152 }
153
154 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
155 ///
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);
160
161   Value *&New = CastedPointers[V];
162   if (New) return New;
163   
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;
169   } else {
170     if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
171       InsertPt = II->getNormalDest()->begin();
172     } else {
173       InsertPt = cast<Instruction>(V);
174       ++InsertPt;
175     }
176
177     // Do not insert casts into the middle of PHI node blocks.
178     while (isa<PHINode>(InsertPt)) ++InsertPt;
179   }
180   
181   New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
182   DeadInsts.insert(cast<Instruction>(New));
183   return New;
184 }
185
186
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)))
198           Insts.insert(U);
199       SE->deleteInstructionFromRecords(I);
200       I->eraseFromParent();
201       Changed = true;
202     }
203   }
204 }
205
206
207 /// GetExpressionSCEV - Compute and return the SCEV for the specified
208 /// instruction.
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
213   // SE figure it out.
214   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
215   if (!GEP || SE->hasSCEV(GEP))
216     return SE->getSCEV(Exp);
217     
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.
221
222   // Build up the base expression.  Insert an LLVM cast of the pointer to
223   // uintptr_t first.
224   SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
225
226   gep_type_iterator GTI = gep_type_begin(GEP);
227   
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
231     // operand.
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));
238     } else {
239       Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
240       SCEVHandle Idx = SE->getSCEV(OpVal);
241
242       uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
243       if (TypeSize != 1)
244         Idx = SCEVMulExpr::get(Idx,
245                                SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
246                                                                    TypeSize)));
247       GEPVal = SCEVAddExpr::get(GEPVal, Idx);
248     }
249   }
250
251   SE->setSCEV(GEP, GEPVal);
252   return GEPVal;
253 }
254
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.
262
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);
271         else
272           return false;  // Nested IV of some sort?
273       } else {
274         Start = SCEVAddExpr::get(Start, AE->getOperand(i));
275       }
276         
277   } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
278     TheAddRec = SH;
279   } else {
280     return false;  // not analyzable.
281   }
282   
283   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
284   if (!AddRec || AddRec->getLoop() != L) return false;
285   
286   // FIXME: Generalize to non-affine IV's.
287   if (!AddRec->isAffine()) return false;
288
289   Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
290   
291   if (!isa<SCEVConstant>(AddRec->getOperand(1)))
292     DEBUG(std::cerr << "[" << L->getHeader()->getName()
293                     << "] Variable stride: " << *AddRec << "\n");
294
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
298   // merged.
299   assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
300          "Constants should be canonicalized to unsigned!");
301
302   return true;
303 }
304
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.
313   
314   // Get the symbolic expression for this instruction.
315   SCEVHandle ISE = GetExpressionSCEV(I, L);
316   if (isa<SCEVCouldNotCompute>(ISE)) return false;
317   
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.
323   
324   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
325     Instruction *User = cast<Instruction>(*UI);
326
327     // Do not infinitely recurse on PHI nodes.
328     if (isa<PHINode>(User) && User->getParent() == L->getHeader())
329       continue;
330
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;
342     }
343
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);
348     }
349   }
350   return true;
351 }
352
353 namespace {
354   /// BasedUser - For a particular base value, keep information about how we've
355   /// partitioned the expression so far.
356   struct BasedUser {
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
360     /// field.
361     SCEVHandle Base;
362     
363     /// Inst - The instruction using the induction variable.
364     Instruction *Inst;
365
366     /// OperandValToReplace - The operand value of Inst to replace with the
367     /// EmittedBase.
368     Value *OperandValToReplace;
369
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
372     /// instruction.
373     SCEVHandle Imm;
374
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.
377     Value *EmittedBase;
378
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;
384     
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) {}
390
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
393     // to it.
394     void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
395                                         SCEVExpander &Rewriter, Pass *P);
396
397     // Sort by the Base field.
398     bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
399
400     void dump() const;
401   };
402 }
403
404 void BasedUser::dump() const {
405   std::cerr << " Base=" << *Base;
406   std::cerr << " Imm=" << *Imm;
407   if (EmittedBase)
408     std::cerr << "  EB=" << *EmittedBase;
409
410   std::cerr << "   Inst: " << *Inst;
411 }
412
413 // Once we rewrite the code to insert the new IVs we want, update the
414 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
415 // to it.
416 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
417                                                SCEVExpander &Rewriter,
418                                                Pass *P) {
419   if (!isa<PHINode>(Inst)) {
420     SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
421     Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
422                                            OperandValToReplace->getType());
423     // Replace the use of the operand Value with the new Phi we just created.
424     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
425     DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
426     return;
427   }
428   
429   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
430   // expression into each operand block that uses it.  Note that PHI nodes can
431   // have multiple entries for the same predecessor.  We use a map to make sure
432   // that a PHI node only has a single Value* for each predecessor (which also
433   // prevents us from inserting duplicate code in some blocks).
434   std::map<BasicBlock*, Value*> InsertedCode;
435   PHINode *PN = cast<PHINode>(Inst);
436   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
437     if (PN->getIncomingValue(i) == OperandValToReplace) {
438       // If this is a critical edge, split the edge so that we do not insert the
439       // code on all predecessor/successor paths.
440       if (e != 1 &&
441           PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() > 1) {
442         TerminatorInst *PredTI = PN->getIncomingBlock(i)->getTerminator();
443         for (unsigned Succ = 0; ; ++Succ) {
444           assert(Succ != PredTI->getNumSuccessors() &&"Didn't find successor?");
445           if (PredTI->getSuccessor(Succ) == PN->getParent()) {
446             SplitCriticalEdge(PredTI, Succ, P);
447             break;
448           }
449         }
450       }
451
452       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
453       if (!Code) {
454         // Insert the code into the end of the predecessor block.
455         BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
456       
457         SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
458         Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
459                                       OperandValToReplace->getType());
460       }
461       
462       // Replace the use of the operand Value with the new Phi we just created.
463       PN->setIncomingValue(i, Code);
464       Rewriter.clear();
465     }
466   }
467   DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
468 }
469
470
471 /// isTargetConstant - Return true if the following can be referenced by the
472 /// immediate field of a target instruction.
473 static bool isTargetConstant(const SCEVHandle &V) {
474
475   // FIXME: Look at the target to decide if &GV is a legal constant immediate.
476   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
477     // PPC allows a sign-extended 16-bit immediate field.
478     if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
479         (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
480       return true;
481     return false;
482   }
483
484   return false;     // ENABLE this for x86
485
486   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
487     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
488       if (CE->getOpcode() == Instruction::Cast)
489         if (isa<GlobalValue>(CE->getOperand(0)))
490           // FIXME: should check to see that the dest is uintptr_t!
491           return true;
492   return false;
493 }
494
495 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
496 /// loop varying to the Imm operand.
497 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
498                                             Loop *L) {
499   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
500   
501   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
502     std::vector<SCEVHandle> NewOps;
503     NewOps.reserve(SAE->getNumOperands());
504     
505     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
506       if (!SAE->getOperand(i)->isLoopInvariant(L)) {
507         // If this is a loop-variant expression, it must stay in the immediate
508         // field of the expression.
509         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
510       } else {
511         NewOps.push_back(SAE->getOperand(i));
512       }
513
514     if (NewOps.empty())
515       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
516     else
517       Val = SCEVAddExpr::get(NewOps);
518   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
519     // Try to pull immediates out of the start value of nested addrec's.
520     SCEVHandle Start = SARE->getStart();
521     MoveLoopVariantsToImediateField(Start, Imm, L);
522     
523     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
524     Ops[0] = Start;
525     Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
526   } else {
527     // Otherwise, all of Val is variant, move the whole thing over.
528     Imm = SCEVAddExpr::get(Imm, Val);
529     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
530   }
531 }
532
533
534 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
535 /// that can fit into the immediate field of instructions in the target.
536 /// Accumulate these immediate values into the Imm value.
537 static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
538                                 bool isAddress, Loop *L) {
539   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
540     std::vector<SCEVHandle> NewOps;
541     NewOps.reserve(SAE->getNumOperands());
542     
543     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
544       if (isAddress && isTargetConstant(SAE->getOperand(i))) {
545         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
546       } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
547         // If this is a loop-variant expression, it must stay in the immediate
548         // field of the expression.
549         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
550       } else {
551         NewOps.push_back(SAE->getOperand(i));
552       }
553
554     if (NewOps.empty())
555       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
556     else
557       Val = SCEVAddExpr::get(NewOps);
558     return;
559   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
560     // Try to pull immediates out of the start value of nested addrec's.
561     SCEVHandle Start = SARE->getStart();
562     MoveImmediateValues(Start, Imm, isAddress, L);
563     
564     if (Start != SARE->getStart()) {
565       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
566       Ops[0] = Start;
567       Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
568     }
569     return;
570   }
571
572   // Loop-variant expressions must stay in the immediate field of the
573   // expression.
574   if ((isAddress && isTargetConstant(Val)) ||
575       !Val->isLoopInvariant(L)) {
576     Imm = SCEVAddExpr::get(Imm, Val);
577     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
578     return;
579   }
580
581   // Otherwise, no immediates to move.
582 }
583
584 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
585 /// removing any common subexpressions from it.  Anything truly common is
586 /// removed, accumulated, and returned.  This looks for things like (a+b+c) and
587 /// (a+c+d) -> (a+c).  The common expression is *removed* from the Bases.
588 static SCEVHandle 
589 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
590   unsigned NumUses = Uses.size();
591
592   // Only one use?  Use its base, regardless of what it is!
593   SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
594   SCEVHandle Result = Zero;
595   if (NumUses == 1) {
596     std::swap(Result, Uses[0].Base);
597     return Result;
598   }
599
600   // To find common subexpressions, count how many of Uses use each expression.
601   // If any subexpressions are used Uses.size() times, they are common.
602   std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
603   
604   for (unsigned i = 0; i != NumUses; ++i)
605     if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
606       for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
607         SubExpressionUseCounts[AE->getOperand(j)]++;
608     } else {
609       // If the base is zero (which is common), return zero now, there are no
610       // CSEs we can find.
611       if (Uses[i].Base == Zero) return Result;
612       SubExpressionUseCounts[Uses[i].Base]++;
613     }
614   
615   // Now that we know how many times each is used, build Result.
616   for (std::map<SCEVHandle, unsigned>::iterator I =
617        SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
618        I != E; )
619     if (I->second == NumUses) {  // Found CSE!
620       Result = SCEVAddExpr::get(Result, I->first);
621       ++I;
622     } else {
623       // Remove non-cse's from SubExpressionUseCounts.
624       SubExpressionUseCounts.erase(I++);
625     }
626   
627   // If we found no CSE's, return now.
628   if (Result == Zero) return Result;
629   
630   // Otherwise, remove all of the CSE's we found from each of the base values.
631   for (unsigned i = 0; i != NumUses; ++i)
632     if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
633       std::vector<SCEVHandle> NewOps;
634       
635       // Remove all of the values that are now in SubExpressionUseCounts.
636       for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
637         if (!SubExpressionUseCounts.count(AE->getOperand(j)))
638           NewOps.push_back(AE->getOperand(j));
639       if (NewOps.empty())
640         Uses[i].Base = Zero;
641       else
642         Uses[i].Base = SCEVAddExpr::get(NewOps);
643     } else {
644       // If the base is zero (which is common), return zero now, there are no
645       // CSEs we can find.
646       assert(Uses[i].Base == Result);
647       Uses[i].Base = Zero;
648     }
649  
650   return Result;
651 }
652
653
654 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
655 /// stride of IV.  All of the users may have different starting values, and this
656 /// may not be the only stride (we know it is if isOnlyStride is true).
657 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
658                                                       IVUsersOfOneStride &Uses,
659                                                       Loop *L,
660                                                       bool isOnlyStride) {
661   // Transform our list of users and offsets to a bit more complex table.  In
662   // this new vector, each 'BasedUser' contains 'Base' the base of the
663   // strided accessas well as the old information from Uses.  We progressively
664   // move information from the Base field to the Imm field, until we eventually
665   // have the full access expression to rewrite the use.
666   std::vector<BasedUser> UsersToProcess;
667   UsersToProcess.reserve(Uses.Users.size());
668   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
669     UsersToProcess.push_back(Uses.Users[i]);
670     
671     // Move any loop invariant operands from the offset field to the immediate
672     // field of the use, so that we don't try to use something before it is
673     // computed.
674     MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
675                                     UsersToProcess.back().Imm, L);
676     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
677            "Base value is not loop invariant!");
678   }
679   
680   // We now have a whole bunch of uses of like-strided induction variables, but
681   // they might all have different bases.  We want to emit one PHI node for this
682   // stride which we fold as many common expressions (between the IVs) into as
683   // possible.  Start by identifying the common expressions in the base values 
684   // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
685   // "A+B"), emit it to the preheader, then remove the expression from the
686   // UsersToProcess base values.
687   SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
688   
689   // Next, figure out what we can represent in the immediate fields of
690   // instructions.  If we can represent anything there, move it to the imm
691   // fields of the BasedUsers.  We do this so that it increases the commonality
692   // of the remaining uses.
693   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
694     // Addressing modes can be folded into loads and stores.  Be careful that
695     // the store is through the expression, not of the expression though.
696     bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
697     if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
698       if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
699         isAddress = true;
700     
701     MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
702                         isAddress, L);
703   }
704  
705   // Now that we know what we need to do, insert the PHI node itself.
706   //
707   DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
708         << *CommonExprs << " :\n");
709     
710   SCEVExpander Rewriter(*SE, *LI);
711   SCEVExpander PreheaderRewriter(*SE, *LI);
712   
713   BasicBlock  *Preheader = L->getLoopPreheader();
714   Instruction *PreInsertPt = Preheader->getTerminator();
715   Instruction *PhiInsertBefore = L->getHeader()->begin();
716   
717   assert(isa<PHINode>(PhiInsertBefore) &&
718          "How could this loop have IV's without any phis?");
719   PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
720   assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
721          "This loop isn't canonicalized right");
722   BasicBlock *LatchBlock =
723    SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
724   
725   // Create a new Phi for this base, and stick it in the loop header.
726   const Type *ReplacedTy = CommonExprs->getType();
727   PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
728   ++NumInserted;
729   
730   // Insert the stride into the preheader.
731   Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
732                                                    ReplacedTy);
733   if (!isa<ConstantInt>(StrideV)) ++NumVariable;
734
735
736   // Emit the initial base value into the loop preheader, and add it to the
737   // Phi node.
738   Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
739                                                     ReplacedTy);
740   NewPHI->addIncoming(PHIBaseV, Preheader);
741   
742   // Emit the increment of the base value before the terminator of the loop
743   // latch block, and add it to the Phi node.
744   SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
745                                        SCEVUnknown::get(StrideV));
746   
747   Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
748                                        ReplacedTy);
749   IncV->setName(NewPHI->getName()+".inc");
750   NewPHI->addIncoming(IncV, LatchBlock);
751
752   // Sort by the base value, so that all IVs with identical bases are next to
753   // each other.
754   std::sort(UsersToProcess.begin(), UsersToProcess.end());
755   while (!UsersToProcess.empty()) {
756     SCEVHandle Base = UsersToProcess.front().Base;
757
758     DEBUG(std::cerr << "  INSERTING code for BASE = " << *Base << ":\n");
759    
760     // Emit the code for Base into the preheader.
761     Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
762                                                    ReplacedTy);
763     
764     // If BaseV is a constant other than 0, make sure that it gets inserted into
765     // the preheader, instead of being forward substituted into the uses.  We do
766     // this by forcing a noop cast to be inserted into the preheader in this
767     // case.
768     if (Constant *C = dyn_cast<Constant>(BaseV))
769       if (!C->isNullValue()) {
770         // We want this constant emitted into the preheader!
771         BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
772                              PreInsertPt);       
773       }
774     
775     // Emit the code to add the immediate offset to the Phi value, just before
776     // the instructions that we identified as using this stride and base.
777     while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
778       BasedUser &User = UsersToProcess.front();
779
780       // If this instruction wants to use the post-incremented value, move it
781       // after the post-inc and use its value instead of the PHI.
782       Value *RewriteOp = NewPHI;
783       if (User.isUseOfPostIncrementedValue) {
784         RewriteOp = IncV;
785         User.Inst->moveBefore(LatchBlock->getTerminator());
786       }
787       SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
788
789       // Clear the SCEVExpander's expression map so that we are guaranteed
790       // to have the code emitted where we expect it.
791       Rewriter.clear();
792      
793       // Now that we know what we need to do, insert code before User for the
794       // immediate and any loop-variant expressions.
795       if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
796         // Add BaseV to the PHI value if needed.
797         RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
798       
799       User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, this);
800
801       // Mark old value we replaced as possibly dead, so that it is elminated
802       // if we just replaced the last use of that value.
803       DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
804
805       UsersToProcess.erase(UsersToProcess.begin());
806       ++NumReduced;
807     }
808     // TODO: Next, find out which base index is the most common, pull it out.
809   }
810
811   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
812   // different starting values, into different PHIs.
813 }
814
815 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
816 // uses in the loop, look to see if we can eliminate some, in favor of using
817 // common indvars for the different uses.
818 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
819   // TODO: implement optzns here.
820
821
822
823
824   // Finally, get the terminating condition for the loop if possible.  If we
825   // can, we want to change it to use a post-incremented version of its
826   // induction variable, to allow coallescing the live ranges for the IV into
827   // one register value.
828   PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
829   BasicBlock  *Preheader = L->getLoopPreheader();
830   BasicBlock *LatchBlock =
831    SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
832   BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
833   if (!TermBr || TermBr->isUnconditional() ||
834       !isa<SetCondInst>(TermBr->getCondition()))
835     return;
836   SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
837
838   // Search IVUsesByStride to find Cond's IVUse if there is one.
839   IVStrideUse *CondUse = 0;
840   const SCEVHandle *CondStride = 0;
841
842   for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator 
843          I = IVUsesByStride.begin(), E = IVUsesByStride.end();
844        I != E && !CondUse; ++I)
845     for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
846            E = I->second.Users.end(); UI != E; ++UI)
847       if (UI->User == Cond) {
848         CondUse = &*UI;
849         CondStride = &I->first;
850         // NOTE: we could handle setcc instructions with multiple uses here, but
851         // InstCombine does it as well for simple uses, it's not clear that it
852         // occurs enough in real life to handle.
853         break;
854       }
855   if (!CondUse) return;  // setcc doesn't use the IV.
856
857   // setcc stride is complex, don't mess with users.
858   // FIXME: Evaluate whether this is a good idea or not.
859   if (!isa<SCEVConstant>(*CondStride)) return;
860
861   // It's possible for the setcc instruction to be anywhere in the loop, and
862   // possible for it to have multiple users.  If it is not immediately before
863   // the latch block branch, move it.
864   if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
865     if (Cond->hasOneUse()) {   // Condition has a single use, just move it.
866       Cond->moveBefore(TermBr);
867     } else {
868       // Otherwise, clone the terminating condition and insert into the loopend.
869       Cond = cast<SetCondInst>(Cond->clone());
870       Cond->setName(L->getHeader()->getName() + ".termcond");
871       LatchBlock->getInstList().insert(TermBr, Cond);
872       
873       // Clone the IVUse, as the old use still exists!
874       IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
875                                          CondUse->OperandValToReplace);
876       CondUse = &IVUsesByStride[*CondStride].Users.back();
877     }
878   }
879
880   // If we get to here, we know that we can transform the setcc instruction to
881   // use the post-incremented version of the IV, allowing us to coallesce the
882   // live ranges for the IV correctly.
883   CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
884   CondUse->isUseOfPostIncrementedValue = true;
885 }
886
887 void LoopStrengthReduce::runOnLoop(Loop *L) {
888   // First step, transform all loops nesting inside of this loop.
889   for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
890     runOnLoop(*I);
891
892   // Next, find all uses of induction variables in this loop, and catagorize
893   // them by stride.  Start by finding all of the PHI nodes in the header for
894   // this loop.  If they are induction variables, inspect their uses.
895   std::set<Instruction*> Processed;   // Don't reprocess instructions.
896   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
897     AddUsersIfInteresting(I, L, Processed);
898
899   // If we have nothing to do, return.
900   if (IVUsesByStride.empty()) return;
901
902   // Optimize induction variables.  Some indvar uses can be transformed to use
903   // strides that will be needed for other purposes.  A common example of this
904   // is the exit test for the loop, which can often be rewritten to use the
905   // computation of some other indvar to decide when to terminate the loop.
906   OptimizeIndvars(L);
907
908
909   // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
910   // doing computation in byte values, promote to 32-bit values if safe.
911
912   // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
913   // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
914   // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.  Need
915   // to be careful that IV's are all the same type.  Only works for intptr_t
916   // indvars.
917
918   // If we only have one stride, we can more aggressively eliminate some things.
919   bool HasOneStride = IVUsesByStride.size() == 1;
920
921   // Note: this processes each stride/type pair individually.  All users passed
922   // into StrengthReduceStridedIVUsers have the same type AND stride.
923   for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI
924         = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
925     StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
926
927   // Clean up after ourselves
928   if (!DeadInsts.empty()) {
929     DeleteTriviallyDeadInstructions(DeadInsts);
930
931     BasicBlock::iterator I = L->getHeader()->begin();
932     PHINode *PN;
933     while ((PN = dyn_cast<PHINode>(I))) {
934       ++I;  // Preincrement iterator to avoid invalidating it when deleting PN.
935       
936       // At this point, we know that we have killed one or more GEP
937       // instructions.  It is worth checking to see if the cann indvar is also
938       // dead, so that we can remove it as well.  The requirements for the cann
939       // indvar to be considered dead are:
940       // 1. the cann indvar has one use
941       // 2. the use is an add instruction
942       // 3. the add has one use
943       // 4. the add is used by the cann indvar
944       // If all four cases above are true, then we can remove both the add and
945       // the cann indvar.
946       // FIXME: this needs to eliminate an induction variable even if it's being
947       // compared against some value to decide loop termination.
948       if (PN->hasOneUse()) {
949         BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
950         if (BO && BO->hasOneUse()) {
951           if (PN == *(BO->use_begin())) {
952             DeadInsts.insert(BO);
953             // Break the cycle, then delete the PHI.
954             PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
955             SE->deleteInstructionFromRecords(PN);
956             PN->eraseFromParent();
957           }
958         }
959       }
960     }
961     DeleteTriviallyDeadInstructions(DeadInsts);
962   }
963
964   CastedPointers.clear();
965   IVUsesByStride.clear();
966   return;
967 }