19e8840320cfc3512b6eadf252ee437241379ca5
[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/Local.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/Debug.h"
33 #include <algorithm>
34 #include <set>
35 using namespace llvm;
36
37 namespace {
38   Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
39   Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
40
41   /// IVStrideUse - Keep track of one use of a strided induction variable, where
42   /// the stride is stored externally.  The Offset member keeps track of the 
43   /// offset from the IV, User is the actual user of the operand, and 'Operand'
44   /// is the operand # of the User that is the use.
45   struct IVStrideUse {
46     SCEVHandle Offset;
47     Instruction *User;
48     Value *OperandValToReplace;
49     
50     IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
51       : Offset(Offs), User(U), OperandValToReplace(O) {}
52   };
53   
54   /// IVUsersOfOneStride - This structure keeps track of all instructions that
55   /// have an operand that is based on the trip count multiplied by some stride.
56   /// The stride for all of these users is common and kept external to this
57   /// structure.
58   struct IVUsersOfOneStride {
59     /// Users - Keep track of all of the users of this stride as well as the
60     /// initial value and the operand that uses the IV.
61     std::vector<IVStrideUse> Users;
62     
63     void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
64       Users.push_back(IVStrideUse(Offset, User, Operand));
65     }
66   };
67
68
69   class LoopStrengthReduce : public FunctionPass {
70     LoopInfo *LI;
71     DominatorSet *DS;
72     ScalarEvolution *SE;
73     const TargetData *TD;
74     const Type *UIntPtrTy;
75     bool Changed;
76
77     /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
78     /// target can handle for free with its addressing modes.
79     unsigned MaxTargetAMSize;
80
81     /// IVUsesByStride - Keep track of all uses of induction variables that we
82     /// are interested in.  The key of the map is the stride of the access.
83     std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
84
85     /// CastedValues - As we need to cast values to uintptr_t, this keeps track
86     /// of the casted version of each value.  This is accessed by
87     /// getCastedVersionOf.
88     std::map<Value*, Value*> CastedPointers;
89
90     /// DeadInsts - Keep track of instructions we may have made dead, so that
91     /// we can remove them after we are done working.
92     std::set<Instruction*> DeadInsts;
93   public:
94     LoopStrengthReduce(unsigned MTAMS = 1)
95       : MaxTargetAMSize(MTAMS) {
96     }
97
98     virtual bool runOnFunction(Function &) {
99       LI = &getAnalysis<LoopInfo>();
100       DS = &getAnalysis<DominatorSet>();
101       SE = &getAnalysis<ScalarEvolution>();
102       TD = &getAnalysis<TargetData>();
103       UIntPtrTy = TD->getIntPtrType();
104       Changed = false;
105
106       for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
107         runOnLoop(*I);
108       
109       return Changed;
110     }
111
112     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113       AU.setPreservesCFG();
114       AU.addRequiredID(LoopSimplifyID);
115       AU.addRequired<LoopInfo>();
116       AU.addRequired<DominatorSet>();
117       AU.addRequired<TargetData>();
118       AU.addRequired<ScalarEvolution>();
119     }
120     
121     /// getCastedVersionOf - Return the specified value casted to uintptr_t.
122     ///
123     Value *getCastedVersionOf(Value *V);
124 private:
125     void runOnLoop(Loop *L);
126     bool AddUsersIfInteresting(Instruction *I, Loop *L,
127                                std::set<Instruction*> &Processed);
128     SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
129
130
131     void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
132                                       Loop *L, bool isOnlyStride);
133     void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
134   };
135   RegisterOpt<LoopStrengthReduce> X("loop-reduce",
136                                     "Strength Reduce GEP Uses of Ind. Vars");
137 }
138
139 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
140   return new LoopStrengthReduce(MaxTargetAMSize);
141 }
142
143 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
144 ///
145 Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
146   if (V->getType() == UIntPtrTy) return V;
147   if (Constant *CB = dyn_cast<Constant>(V))
148     return ConstantExpr::getCast(CB, UIntPtrTy);
149
150   Value *&New = CastedPointers[V];
151   if (New) return New;
152   
153   BasicBlock::iterator InsertPt;
154   if (Argument *Arg = dyn_cast<Argument>(V)) {
155     // Insert into the entry of the function, after any allocas.
156     InsertPt = Arg->getParent()->begin()->begin();
157     while (isa<AllocaInst>(InsertPt)) ++InsertPt;
158   } else {
159     if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
160       InsertPt = II->getNormalDest()->begin();
161     } else {
162       InsertPt = cast<Instruction>(V);
163       ++InsertPt;
164     }
165
166     // Do not insert casts into the middle of PHI node blocks.
167     while (isa<PHINode>(InsertPt)) ++InsertPt;
168   }
169   
170   New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
171   DeadInsts.insert(cast<Instruction>(New));
172   return New;
173 }
174
175
176 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
177 /// specified set are trivially dead, delete them and see if this makes any of
178 /// their operands subsequently dead.
179 void LoopStrengthReduce::
180 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
181   while (!Insts.empty()) {
182     Instruction *I = *Insts.begin();
183     Insts.erase(Insts.begin());
184     if (isInstructionTriviallyDead(I)) {
185       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
186         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
187           Insts.insert(U);
188       SE->deleteInstructionFromRecords(I);
189       I->eraseFromParent();
190       Changed = true;
191     }
192   }
193 }
194
195
196 /// GetExpressionSCEV - Compute and return the SCEV for the specified
197 /// instruction.
198 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
199   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
200   if (!GEP)
201     return SE->getSCEV(Exp);
202     
203   // Analyze all of the subscripts of this getelementptr instruction, looking
204   // for uses that are determined by the trip count of L.  First, skip all
205   // operands the are not dependent on the IV.
206
207   // Build up the base expression.  Insert an LLVM cast of the pointer to
208   // uintptr_t first.
209   SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
210
211   gep_type_iterator GTI = gep_type_begin(GEP);
212   
213   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
214     // If this is a use of a recurrence that we can analyze, and it comes before
215     // Op does in the GEP operand list, we will handle this when we process this
216     // operand.
217     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
218       const StructLayout *SL = TD->getStructLayout(STy);
219       unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
220       uint64_t Offset = SL->MemberOffsets[Idx];
221       GEPVal = SCEVAddExpr::get(GEPVal,
222                                 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
223     } else {
224       Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
225       SCEVHandle Idx = SE->getSCEV(OpVal);
226
227       uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
228       if (TypeSize != 1)
229         Idx = SCEVMulExpr::get(Idx,
230                                SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
231                                                                    TypeSize)));
232       GEPVal = SCEVAddExpr::get(GEPVal, Idx);
233     }
234   }
235
236   return GEPVal;
237 }
238
239 /// getSCEVStartAndStride - Compute the start and stride of this expression,
240 /// returning false if the expression is not a start/stride pair, or true if it
241 /// is.  The stride must be a loop invariant expression, but the start may be
242 /// a mix of loop invariant and loop variant expressions.
243 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
244                                   SCEVHandle &Start, Value *&Stride) {
245   SCEVHandle TheAddRec = Start;   // Initialize to zero.
246
247   // If the outer level is an AddExpr, the operands are all start values except
248   // for a nested AddRecExpr.
249   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
250     for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
251       if (SCEVAddRecExpr *AddRec =
252              dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
253         if (AddRec->getLoop() == L)
254           TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
255         else
256           return false;  // Nested IV of some sort?
257       } else {
258         Start = SCEVAddExpr::get(Start, AE->getOperand(i));
259       }
260         
261   } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
262     TheAddRec = SH;
263   } else {
264     return false;  // not analyzable.
265   }
266   
267   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
268   if (!AddRec || AddRec->getLoop() != L) return false;
269   
270   // FIXME: Generalize to non-affine IV's.
271   if (!AddRec->isAffine()) return false;
272
273   Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
274   
275   // FIXME: generalize to IV's with more complex strides (must emit stride
276   // expression outside of loop!)
277   if (!isa<SCEVConstant>(AddRec->getOperand(1)))
278     return false;
279   
280   SCEVConstant *StrideC = cast<SCEVConstant>(AddRec->getOperand(1));
281   Stride = StrideC->getValue();
282
283   assert(Stride->getType()->isUnsigned() &&
284          "Constants should be canonicalized to unsigned!");
285   return true;
286 }
287
288 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
289 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
290 /// return true.  Otherwise, return false.
291 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
292                                             std::set<Instruction*> &Processed) {
293   if (I->getType() == Type::VoidTy) return false;
294   if (!Processed.insert(I).second)
295     return true;    // Instruction already handled.
296   
297   // Get the symbolic expression for this instruction.
298   SCEVHandle ISE = GetExpressionSCEV(I, L);
299   if (isa<SCEVCouldNotCompute>(ISE)) return false;
300   
301   // Get the start and stride for this expression.
302   SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
303   Value *Stride = 0;
304   if (!getSCEVStartAndStride(ISE, L, Start, Stride))
305     return false;  // Non-reducible symbolic expression, bail out.
306   
307   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
308     Instruction *User = cast<Instruction>(*UI);
309
310     // Do not infinitely recurse on PHI nodes.
311     if (isa<PHINode>(User) && User->getParent() == L->getHeader())
312       continue;
313
314     // If this is an instruction defined in a nested loop, or outside this loop,
315     // don't recurse into it.
316     bool AddUserToIVUsers = false;
317     if (LI->getLoopFor(User->getParent()) != L) {
318       DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
319             << "   OF SCEV: " << *ISE << "\n");
320       AddUserToIVUsers = true;
321     } else if (!AddUsersIfInteresting(User, L, Processed)) {
322       DEBUG(std::cerr << "FOUND USER: " << *User
323             << "   OF SCEV: " << *ISE << "\n");
324       AddUserToIVUsers = true;
325     }
326
327     if (AddUserToIVUsers) {
328       // Okay, we found a user that we cannot reduce.  Analyze the instruction
329       // and decide what to do with it.
330       IVUsesByStride[Stride].addUser(Start, User, I);
331     }
332   }
333   return true;
334 }
335
336 namespace {
337   /// BasedUser - For a particular base value, keep information about how we've
338   /// partitioned the expression so far.
339   struct BasedUser {
340     /// Inst - The instruction using the induction variable.
341     Instruction *Inst;
342
343     /// OperandValToReplace - The operand value of Inst to replace with the
344     /// EmittedBase.
345     Value *OperandValToReplace;
346
347     /// Imm - The immediate value that should be added to the base immediately
348     /// before Inst, because it will be folded into the imm field of the
349     /// instruction.
350     SCEVHandle Imm;
351
352     /// EmittedBase - The actual value* to use for the base value of this
353     /// operation.  This is null if we should just use zero so far.
354     Value *EmittedBase;
355
356     BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM)
357       : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0) {}
358
359     // Once we rewrite the code to insert the new IVs we want, update the
360     // operands of Inst to use the new expression 'NewBase', with 'Imm' added
361     // to it.
362     void RewriteInstructionToUseNewBase(Value *NewBase, SCEVExpander &Rewriter);
363
364     // No need to compare these.
365     bool operator<(const BasedUser &BU) const { return 0; }
366
367     void dump() const;
368   };
369 }
370
371 void BasedUser::dump() const {
372   std::cerr << " Imm=" << *Imm;
373   if (EmittedBase)
374     std::cerr << "  EB=" << *EmittedBase;
375
376   std::cerr << "   Inst: " << *Inst;
377 }
378
379 // Once we rewrite the code to insert the new IVs we want, update the
380 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
381 // to it.
382 void BasedUser::RewriteInstructionToUseNewBase(Value *NewBase,
383                                                SCEVExpander &Rewriter) {
384   if (!isa<PHINode>(Inst)) {
385     SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewBase), Imm);
386     Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
387                                            OperandValToReplace->getType());
388     
389     // Replace the use of the operand Value with the new Phi we just created.
390     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
391     DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
392     return;
393   }
394   
395   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
396   // expression into each operand block that uses it.
397   PHINode *PN = cast<PHINode>(Inst);
398   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
399     if (PN->getIncomingValue(i) == OperandValToReplace) {
400       // FIXME: this should split any critical edges.
401
402       // Insert the code into the end of the predecessor block.
403       BasicBlock::iterator InsertPt = PN->getIncomingBlock(i)->getTerminator();
404       
405       SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewBase), Imm);
406       Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
407                                              OperandValToReplace->getType());
408       
409       // Replace the use of the operand Value with the new Phi we just created.
410       PN->setIncomingValue(i, NewVal);
411       Rewriter.clear();
412     }
413   }
414   DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
415 }
416
417
418 /// isTargetConstant - Return true if the following can be referenced by the
419 /// immediate field of a target instruction.
420 static bool isTargetConstant(const SCEVHandle &V) {
421
422   // FIXME: Look at the target to decide if &GV is a legal constant immediate.
423   if (isa<SCEVConstant>(V)) return true;
424
425   return false;     // ENABLE this for x86
426
427   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
428     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
429       if (CE->getOpcode() == Instruction::Cast)
430         if (isa<GlobalValue>(CE->getOperand(0)))
431           // FIXME: should check to see that the dest is uintptr_t!
432           return true;
433   return false;
434 }
435
436 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
437 /// that can fit into the immediate field of instructions in the target.
438 /// Accumulate these immediate values into the Imm value.
439 static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
440                                 bool isAddress, Loop *L) {
441   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
442     std::vector<SCEVHandle> NewOps;
443     NewOps.reserve(SAE->getNumOperands());
444     
445     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
446       if (isAddress && isTargetConstant(SAE->getOperand(i))) {
447         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
448       } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
449         // If this is a loop-variant expression, it must stay in the immediate
450         // field of the expression.
451         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
452       } else {
453         NewOps.push_back(SAE->getOperand(i));
454       }
455
456     if (NewOps.empty())
457       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
458     else
459       Val = SCEVAddExpr::get(NewOps);
460     return;
461   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
462     // Try to pull immediates out of the start value of nested addrec's.
463     SCEVHandle Start = SARE->getStart();
464     MoveImmediateValues(Start, Imm, isAddress, L);
465     
466     if (Start != SARE->getStart()) {
467       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
468       Ops[0] = Start;
469       Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
470     }
471     return;
472   }
473
474   // Loop-variant expressions must stay in the immediate field of the
475   // expression.
476   if ((isAddress && isTargetConstant(Val)) ||
477       !Val->isLoopInvariant(L)) {
478     Imm = SCEVAddExpr::get(Imm, Val);
479     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
480     return;
481   }
482
483   // Otherwise, no immediates to move.
484 }
485
486 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
487 /// stride of IV.  All of the users may have different starting values, and this
488 /// may not be the only stride (we know it is if isOnlyStride is true).
489 void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
490                                                       IVUsersOfOneStride &Uses,
491                                                       Loop *L,
492                                                       bool isOnlyStride) {
493   // Transform our list of users and offsets to a bit more complex table.  In
494   // this new vector, the first entry for each element is the base of the
495   // strided access, and the second is the BasedUser object for the use.  We
496   // progressively move information from the first to the second entry, until we
497   // eventually emit the object.
498   std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
499   UsersToProcess.reserve(Uses.Users.size());
500
501   SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
502                                               Uses.Users[0].Offset->getType());
503
504   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
505     UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
506                                             BasedUser(Uses.Users[i].User,
507                                              Uses.Users[i].OperandValToReplace,
508                                                       ZeroBase)));
509
510   // First pass, figure out what we can represent in the immediate fields of
511   // instructions.  If we can represent anything there, move it to the imm
512   // fields of the BasedUsers.
513   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
514     // Addressing modes can be folded into loads and stores.  Be careful that
515     // the store is through the expression, not of the expression though.
516     bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst);
517     if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].second.Inst))
518       if (SI->getOperand(1) == UsersToProcess[i].second.OperandValToReplace)
519         isAddress = true;
520           
521     MoveImmediateValues(UsersToProcess[i].first, UsersToProcess[i].second.Imm,
522                         isAddress, L);
523
524     assert(UsersToProcess[i].first->isLoopInvariant(L) &&
525            "Base value is not loop invariant!");
526   }
527
528   SCEVExpander Rewriter(*SE, *LI);
529   BasicBlock  *Preheader = L->getLoopPreheader();
530   Instruction *PreInsertPt = Preheader->getTerminator();
531   Instruction *PhiInsertBefore = L->getHeader()->begin();
532
533   assert(isa<PHINode>(PhiInsertBefore) &&
534          "How could this loop have IV's without any phis?");
535   PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
536   assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
537          "This loop isn't canonicalized right");
538   BasicBlock *LatchBlock =
539    SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
540
541   DEBUG(std::cerr << "INSERTING IVs of STRIDE " << *Stride << ":\n");
542   
543   // FIXME: This loop needs increasing levels of intelligence.
544   // STAGE 0: just emit everything as its own base.
545   // STAGE 1: factor out common vars from bases, and try and push resulting
546   //          constants into Imm field.  <-- We are here
547   // STAGE 2: factor out large constants to try and make more constants
548   //          acceptable for target loads and stores.
549
550   // Sort by the base value, so that all IVs with identical bases are next to
551   // each other.  
552   std::sort(UsersToProcess.begin(), UsersToProcess.end());
553   while (!UsersToProcess.empty()) {
554     SCEVHandle Base = UsersToProcess.front().first;
555
556     DEBUG(std::cerr << "  INSERTING PHI with BASE = " << *Base << ":\n");
557    
558     // Create a new Phi for this base, and stick it in the loop header.
559     const Type *ReplacedTy = Base->getType();
560     PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
561     ++NumInserted;
562
563     // Emit the initial base value into the loop preheader, and add it to the
564     // Phi node.
565     Value *BaseV = Rewriter.expandCodeFor(Base, PreInsertPt, ReplacedTy);
566     NewPHI->addIncoming(BaseV, Preheader);
567
568     // Emit the increment of the base value before the terminator of the loop
569     // latch block, and add it to the Phi node.
570     SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
571                                       SCEVUnknown::get(Stride));
572
573     Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
574                                          ReplacedTy);
575     IncV->setName(NewPHI->getName()+".inc");
576     NewPHI->addIncoming(IncV, LatchBlock);
577
578     // Emit the code to add the immediate offset to the Phi value, just before
579     // the instructions that we identified as using this stride and base.
580     while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) {
581       BasedUser &User = UsersToProcess.front().second;
582
583       // Clear the SCEVExpander's expression map so that we are guaranteed
584       // to have the code emitted where we expect it.
585       Rewriter.clear();
586       
587       // Now that we know what we need to do, insert code before User for the
588       // immediate and any loop-variant expressions.
589       User.RewriteInstructionToUseNewBase(NewPHI, Rewriter);
590
591       // Mark old value we replaced as possibly dead, so that it is elminated
592       // if we just replaced the last use of that value.
593       DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
594
595       UsersToProcess.erase(UsersToProcess.begin());
596       ++NumReduced;
597     }
598     // TODO: Next, find out which base index is the most common, pull it out.
599   }
600
601   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
602   // different starting values, into different PHIs.
603 }
604
605
606 void LoopStrengthReduce::runOnLoop(Loop *L) {
607   // First step, transform all loops nesting inside of this loop.
608   for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
609     runOnLoop(*I);
610
611   // Next, find all uses of induction variables in this loop, and catagorize
612   // them by stride.  Start by finding all of the PHI nodes in the header for
613   // this loop.  If they are induction variables, inspect their uses.
614   std::set<Instruction*> Processed;   // Don't reprocess instructions.
615   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
616     AddUsersIfInteresting(I, L, Processed);
617
618   // If we have nothing to do, return.
619   //if (IVUsesByStride.empty()) return;
620
621   // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
622   // doing computation in byte values, promote to 32-bit values if safe.
623
624   // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
625   // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
626   // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.  Need
627   // to be careful that IV's are all the same type.  Only works for intptr_t
628   // indvars.
629
630   // If we only have one stride, we can more aggressively eliminate some things.
631   bool HasOneStride = IVUsesByStride.size() == 1;
632
633   for (std::map<Value*, IVUsersOfOneStride>::iterator SI
634         = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
635     StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
636
637   // Clean up after ourselves
638   if (!DeadInsts.empty()) {
639     DeleteTriviallyDeadInstructions(DeadInsts);
640
641     BasicBlock::iterator I = L->getHeader()->begin();
642     PHINode *PN;
643     while ((PN = dyn_cast<PHINode>(I))) {
644       ++I;  // Preincrement iterator to avoid invalidating it when deleting PN.
645       
646       // At this point, we know that we have killed one or more GEP instructions.
647       // It is worth checking to see if the cann indvar is also dead, so that we
648       // can remove it as well.  The requirements for the cann indvar to be
649       // considered dead are:
650       // 1. the cann indvar has one use
651       // 2. the use is an add instruction
652       // 3. the add has one use
653       // 4. the add is used by the cann indvar
654       // If all four cases above are true, then we can remove both the add and
655       // the cann indvar.
656       // FIXME: this needs to eliminate an induction variable even if it's being
657       // compared against some value to decide loop termination.
658       if (PN->hasOneUse()) {
659         BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
660         if (BO && BO->hasOneUse()) {
661           if (PN == *(BO->use_begin())) {
662             DeadInsts.insert(BO);
663             // Break the cycle, then delete the PHI.
664             PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
665             SE->deleteInstructionFromRecords(PN);
666             PN->eraseFromParent();
667           }
668         }
669       }
670     }
671     DeleteTriviallyDeadInstructions(DeadInsts);
672   }
673
674   CastedPointers.clear();
675   IVUsesByStride.clear();
676   return;
677 }