9143f56d4d7c26c94bd0c7e82127dd22d19f3ab1
[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, Loop *L,
396                                         Pass *P);
397
398     // Sort by the Base field.
399     bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
400
401     void dump() const;
402   };
403 }
404
405 void BasedUser::dump() const {
406   std::cerr << " Base=" << *Base;
407   std::cerr << " Imm=" << *Imm;
408   if (EmittedBase)
409     std::cerr << "  EB=" << *EmittedBase;
410
411   std::cerr << "   Inst: " << *Inst;
412 }
413
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
416 // to it.
417 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
418                                                SCEVExpander &Rewriter,
419                                                Loop *L, Pass *P) {
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);
427     return;
428   }
429   
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.
441       if (e != 1 &&
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);
449             
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());
458             }
459             break;
460           }
461         }
462       }
463
464       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
465       if (!Code) {
466         // Insert the code into the end of the predecessor block.
467         BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
468       
469         SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
470         Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
471                                       OperandValToReplace->getType());
472       }
473       
474       // Replace the use of the operand Value with the new Phi we just created.
475       PN->setIncomingValue(i, Code);
476       Rewriter.clear();
477     }
478   }
479   DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
480 }
481
482
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) {
486
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)
492       return true;
493     return false;
494   }
495
496   return false;     // ENABLE this for x86
497
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!
503           return true;
504   return false;
505 }
506
507 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
508 /// loop varying to the Imm operand.
509 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
510                                             Loop *L) {
511   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
512   
513   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
514     std::vector<SCEVHandle> NewOps;
515     NewOps.reserve(SAE->getNumOperands());
516     
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));
522       } else {
523         NewOps.push_back(SAE->getOperand(i));
524       }
525
526     if (NewOps.empty())
527       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
528     else
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);
534     
535     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
536     Ops[0] = Start;
537     Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
538   } else {
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());
542   }
543 }
544
545
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());
554     
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));
562       } else {
563         NewOps.push_back(SAE->getOperand(i));
564       }
565
566     if (NewOps.empty())
567       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
568     else
569       Val = SCEVAddExpr::get(NewOps);
570     return;
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);
575     
576     if (Start != SARE->getStart()) {
577       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
578       Ops[0] = Start;
579       Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
580     }
581     return;
582   }
583
584   // Loop-variant expressions must stay in the immediate field of the
585   // expression.
586   if ((isAddress && isTargetConstant(Val)) ||
587       !Val->isLoopInvariant(L)) {
588     Imm = SCEVAddExpr::get(Imm, Val);
589     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
590     return;
591   }
592
593   // Otherwise, no immediates to move.
594 }
595
596
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,
601                              SCEVHandle Expr) {
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);
609     } else {
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()));
614       
615
616       SeparateSubExprs(SubExprs, SARE->getOperand(0));
617     }
618   } else if (!isa<SCEVConstant>(Expr) ||
619              !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
620     // Do not add zero.
621     SubExprs.push_back(Expr);
622   }
623 }
624
625
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.
630 static SCEVHandle 
631 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
632   unsigned NumUses = Uses.size();
633
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;
637   if (NumUses == 1) {
638     std::swap(Result, Uses[0].Base);
639     return Result;
640   }
641
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;
645   
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
649     // CSEs we can find.
650     if (Uses[i].Base == Zero) return Zero;
651
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]]++;
657     SubExprs.clear();
658   }
659
660
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();
664        I != E; )
665     if (I->second == NumUses) {  // Found CSE!
666       Result = SCEVAddExpr::get(Result, I->first);
667       ++I;
668     } else {
669       // Remove non-cse's from SubExpressionUseCounts.
670       SubExpressionUseCounts.erase(I++);
671     }
672   
673   // If we found no CSE's, return now.
674   if (Result == Zero) return Result;
675   
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);
680
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);
685         --j; --e;
686       }
687     
688     // Finally, the non-shared expressions together.
689     if (SubExprs.empty())
690       Uses[i].Base = Zero;
691     else
692       Uses[i].Base = SCEVAddExpr::get(SubExprs);
693     SubExprs.clear();
694   }
695  
696   return Result;
697 }
698
699
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,
705                                                       Loop *L,
706                                                       bool isOnlyStride) {
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]);
716     
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
719     // computed.
720     MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
721                                     UsersToProcess.back().Imm, L);
722     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
723            "Base value is not loop invariant!");
724   }
725   
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);
734   
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)
745         isAddress = true;
746     
747     MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
748                         isAddress, L);
749   }
750  
751   // Now that we know what we need to do, insert the PHI node itself.
752   //
753   DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
754         << *CommonExprs << " :\n");
755     
756   SCEVExpander Rewriter(*SE, *LI);
757   SCEVExpander PreheaderRewriter(*SE, *LI);
758   
759   BasicBlock  *Preheader = L->getLoopPreheader();
760   Instruction *PreInsertPt = Preheader->getTerminator();
761   Instruction *PhiInsertBefore = L->getHeader()->begin();
762   
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);
770   
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);
774   ++NumInserted;
775   
776   // Insert the stride into the preheader.
777   Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
778                                                    ReplacedTy);
779   if (!isa<ConstantInt>(StrideV)) ++NumVariable;
780
781
782   // Emit the initial base value into the loop preheader, and add it to the
783   // Phi node.
784   Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
785                                                     ReplacedTy);
786   NewPHI->addIncoming(PHIBaseV, Preheader);
787   
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));
792   
793   Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
794                                        ReplacedTy);
795   IncV->setName(NewPHI->getName()+".inc");
796   NewPHI->addIncoming(IncV, LatchBlock);
797
798   // Sort by the base value, so that all IVs with identical bases are next to
799   // each other.
800   std::sort(UsersToProcess.begin(), UsersToProcess.end());
801   while (!UsersToProcess.empty()) {
802     SCEVHandle Base = UsersToProcess.front().Base;
803
804     DEBUG(std::cerr << "  INSERTING code for BASE = " << *Base << ":\n");
805    
806     // Emit the code for Base into the preheader.
807     Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
808                                                    ReplacedTy);
809     
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
813     // case.
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",
818                              PreInsertPt);       
819       }
820     
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();
825
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) {
830         RewriteOp = IncV;
831         User.Inst->moveBefore(LatchBlock->getTerminator());
832       }
833       SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
834
835       // Clear the SCEVExpander's expression map so that we are guaranteed
836       // to have the code emitted where we expect it.
837       Rewriter.clear();
838      
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));
844       
845       User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
846
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));
850
851       UsersToProcess.erase(UsersToProcess.begin());
852       ++NumReduced;
853     }
854     // TODO: Next, find out which base index is the most common, pull it out.
855   }
856
857   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
858   // different starting values, into different PHIs.
859 }
860
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.
866
867
868
869
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()))
881     return;
882   SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
883
884   // Search IVUsesByStride to find Cond's IVUse if there is one.
885   IVStrideUse *CondUse = 0;
886   const SCEVHandle *CondStride = 0;
887
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) {
894         CondUse = &*UI;
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.
899         break;
900       }
901   if (!CondUse) return;  // setcc doesn't use the IV.
902
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;
906
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);
913     } else {
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);
918       
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();
923     }
924   }
925
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;
931 }
932
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)
936     runOnLoop(*I);
937
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);
944
945   // If we have nothing to do, return.
946   if (IVUsesByStride.empty()) return;
947
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.
952   OptimizeIndvars(L);
953
954
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.
957
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
962   // indvars.
963
964   // If we only have one stride, we can more aggressively eliminate some things.
965   bool HasOneStride = IVUsesByStride.size() == 1;
966
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);
972
973   // Clean up after ourselves
974   if (!DeadInsts.empty()) {
975     DeleteTriviallyDeadInstructions(DeadInsts);
976
977     BasicBlock::iterator I = L->getHeader()->begin();
978     PHINode *PN;
979     while ((PN = dyn_cast<PHINode>(I))) {
980       ++I;  // Preincrement iterator to avoid invalidating it when deleting PN.
981       
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
991       // the cann indvar.
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();
1003           }
1004         }
1005       }
1006     }
1007     DeleteTriviallyDeadInstructions(DeadInsts);
1008   }
1009
1010   CastedPointers.clear();
1011   IVUsesByStride.clear();
1012   return;
1013 }