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