1 //===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Nate Begeman and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs a strength reduction on array references inside loops that
11 // have as one or more of their components the loop induction variable. This is
12 // accomplished by creating a new Value to hold the initial value of the array
13 // access for the first iteration, and then creating a new GEP instruction in
14 // the loop to increment the value by the appropriate amount.
16 //===----------------------------------------------------------------------===//
18 #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"
37 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
41 GEPCache() : CachedPHINode(0), Map() {}
43 GEPCache *get(Value *v) {
44 std::map<Value *, GEPCache>::iterator I = Map.find(v);
46 I = Map.insert(std::pair<Value *, GEPCache>(v, GEPCache())).first;
50 PHINode *CachedPHINode;
51 std::map<Value *, GEPCache> Map;
54 /// IVStrideUse - Keep track of one use of a strided induction variable, where
55 /// the stride is stored externally. The Offset member keeps track of the
56 /// offset from the IV, User is the actual user of the operand, and 'Operand'
57 /// is the operand # of the User that is the use.
61 Value *OperandValToReplace;
63 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
64 : Offset(Offs), User(U), OperandValToReplace(O) {}
67 /// IVUsersOfOneStride - This structure keeps track of all instructions that
68 /// have an operand that is based on the trip count multiplied by some stride.
69 /// The stride for all of these users is common and kept external to this
71 struct IVUsersOfOneStride {
72 /// Users - Keep track of all of the users of this stride as well as the
73 /// initial value and the operand that uses the IV.
74 std::vector<IVStrideUse> Users;
76 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
77 Users.push_back(IVStrideUse(Offset, User, Operand));
82 class LoopStrengthReduce : public FunctionPass {
87 const Type *UIntPtrTy;
90 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
91 /// target can handle for free with its addressing modes.
92 unsigned MaxTargetAMSize;
94 /// IVUsesByStride - Keep track of all uses of induction variables that we
95 /// are interested in. The key of the map is the stride of the access.
96 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
98 /// CastedBasePointers - As we need to lower getelementptr instructions, we
99 /// cast the pointer input to uintptr_t. This keeps track of the casted
100 /// values for the pointers we have processed so far.
101 std::map<Value*, Value*> CastedBasePointers;
103 /// DeadInsts - Keep track of instructions we may have made dead, so that
104 /// we can remove them after we are done working.
105 std::set<Instruction*> DeadInsts;
107 LoopStrengthReduce(unsigned MTAMS = 1)
108 : MaxTargetAMSize(MTAMS) {
111 virtual bool runOnFunction(Function &) {
112 LI = &getAnalysis<LoopInfo>();
113 DS = &getAnalysis<DominatorSet>();
114 SE = &getAnalysis<ScalarEvolution>();
115 TD = &getAnalysis<TargetData>();
116 UIntPtrTy = TD->getIntPtrType();
119 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
124 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
125 AU.setPreservesCFG();
126 AU.addRequiredID(LoopSimplifyID);
127 AU.addRequired<LoopInfo>();
128 AU.addRequired<DominatorSet>();
129 AU.addRequired<TargetData>();
130 AU.addRequired<ScalarEvolution>();
133 void runOnLoop(Loop *L);
134 bool AddUsersIfInteresting(Instruction *I, Loop *L);
135 void AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP, Instruction *I,
138 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
139 Loop *L, bool isOnlyStride);
141 void strengthReduceGEP(GetElementPtrInst *GEPI, Loop *L,
143 Instruction *InsertBefore,
144 std::set<Instruction*> &DeadInsts);
145 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
147 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
148 "Strength Reduce GEP Uses of Ind. Vars");
151 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
152 return new LoopStrengthReduce(MaxTargetAMSize);
155 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
156 /// specified set are trivially dead, delete them and see if this makes any of
157 /// their operands subsequently dead.
158 void LoopStrengthReduce::
159 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
160 while (!Insts.empty()) {
161 Instruction *I = *Insts.begin();
162 Insts.erase(Insts.begin());
163 if (isInstructionTriviallyDead(I)) {
164 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
165 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
167 SE->deleteInstructionFromRecords(I);
168 I->eraseFromParent();
175 /// CanReduceSCEV - Return true if we can strength reduce this scalar evolution
176 /// in the specified loop.
177 static bool CanReduceSCEV(const SCEVHandle &SH, Loop *L) {
178 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH);
179 if (!AddRec || AddRec->getLoop() != L) return false;
181 // FIXME: Generalize to non-affine IV's.
182 if (!AddRec->isAffine()) return false;
184 // FIXME: generalize to IV's with more complex strides (must emit stride
185 // expression outside of loop!)
186 if (isa<SCEVConstant>(AddRec->getOperand(1)))
189 // We handle steps by unsigned values, because we know we won't have to insert
191 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(AddRec->getOperand(1)))
192 if (SU->getValue()->getType()->isUnsigned())
195 // Otherwise, no, we can't handle it yet.
200 /// GetAdjustedIndex - Adjust the specified GEP sequential type index to match
201 /// the size of the pointer type, and scale it by the type size.
202 static SCEVHandle GetAdjustedIndex(const SCEVHandle &Idx, uint64_t TySize,
203 const Type *UIntPtrTy) {
204 SCEVHandle Result = Idx;
205 if (Result->getType()->getUnsignedVersion() != UIntPtrTy) {
206 if (UIntPtrTy->getPrimitiveSize() < Result->getType()->getPrimitiveSize())
207 Result = SCEVTruncateExpr::get(Result, UIntPtrTy);
209 Result = SCEVZeroExtendExpr::get(Result, UIntPtrTy);
212 // This index is scaled by the type size being indexed.
214 Result = SCEVMulExpr::get(Result,
215 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
220 /// AnalyzeGetElementPtrUsers - Analyze all of the users of the specified
221 /// getelementptr instruction, adding them to the IVUsesByStride table. Note
222 /// that we only want to analyze a getelementptr instruction once, and it can
223 /// have multiple operands that are uses of the indvar (e.g. A[i][i]). Because
224 /// of this, we only process a GEP instruction if its first recurrent operand is
225 /// "op", otherwise we will either have already processed it or we will sometime
227 void LoopStrengthReduce::AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP,
228 Instruction *Op, Loop *L) {
229 // Analyze all of the subscripts of this getelementptr instruction, looking
230 // for uses that are determined by the trip count of L. First, skip all
231 // operands the are not dependent on the IV.
233 // Build up the base expression. Insert an LLVM cast of the pointer to
236 if (Constant *CB = dyn_cast<Constant>(GEP->getOperand(0)))
237 BasePtr = ConstantExpr::getCast(CB, UIntPtrTy);
239 Value *&BP = CastedBasePointers[GEP->getOperand(0)];
241 BasicBlock::iterator InsertPt;
242 if (isa<Argument>(GEP->getOperand(0))) {
243 InsertPt = GEP->getParent()->getParent()->begin()->begin();
245 InsertPt = cast<Instruction>(GEP->getOperand(0));
246 if (InvokeInst *II = dyn_cast<InvokeInst>(GEP->getOperand(0)))
247 InsertPt = II->getNormalDest()->begin();
252 // Do not insert casts into the middle of PHI node blocks.
253 while (isa<PHINode>(InsertPt)) ++InsertPt;
255 BP = new CastInst(GEP->getOperand(0), UIntPtrTy,
256 GEP->getOperand(0)->getName(), InsertPt);
261 SCEVHandle Base = SCEVUnknown::get(BasePtr);
263 gep_type_iterator GTI = gep_type_begin(GEP);
265 for (; GEP->getOperand(i) != Op; ++i, ++GTI) {
266 // If this is a use of a recurrence that we can analyze, and it comes before
267 // Op does in the GEP operand list, we will handle this when we process this
269 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
270 const StructLayout *SL = TD->getStructLayout(STy);
271 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
272 uint64_t Offset = SL->MemberOffsets[Idx];
273 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
276 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
278 // If this operand is reducible, and it's not the one we are looking at
279 // currently, do not process the GEP at this time.
280 if (CanReduceSCEV(Idx, L))
282 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
283 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
287 // Get the index, convert it to intptr_t.
288 SCEVHandle GEPIndexExpr =
289 GetAdjustedIndex(SE->getSCEV(Op), TD->getTypeSize(GTI.getIndexedType()),
292 // Process all remaining subscripts in the GEP instruction.
293 for (++i, ++GTI; i != GEP->getNumOperands(); ++i, ++GTI)
294 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
295 const StructLayout *SL = TD->getStructLayout(STy);
296 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
297 uint64_t Offset = SL->MemberOffsets[Idx];
298 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
301 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
302 if (CanReduceSCEV(Idx, L)) { // Another IV subscript
303 GEPIndexExpr = SCEVAddExpr::get(GEPIndexExpr,
304 GetAdjustedIndex(Idx, TD->getTypeSize(GTI.getIndexedType()),
306 assert(CanReduceSCEV(GEPIndexExpr, L) &&
307 "Cannot reduce the sum of two reducible SCEV's??");
309 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
310 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
314 assert(CanReduceSCEV(GEPIndexExpr, L) && "Non reducible idx??");
316 // FIXME: If the base is not loop invariant, we currently cannot emit this.
317 if (!Base->isLoopInvariant(L)) {
318 DEBUG(std::cerr << "IGNORING GEP due to non-invaiant base: "
323 Base = SCEVAddExpr::get(Base, cast<SCEVAddRecExpr>(GEPIndexExpr)->getStart());
324 SCEVHandle Stride = cast<SCEVAddRecExpr>(GEPIndexExpr)->getOperand(1);
326 DEBUG(std::cerr << "GEP BASE : " << *Base << "\n");
327 DEBUG(std::cerr << "GEP STRIDE: " << *Stride << "\n");
329 Value *Step = 0; // Step of ISE.
330 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride))
331 /// Always get the step value as an unsigned value.
332 Step = ConstantExpr::getCast(SC->getValue(),
333 SC->getValue()->getType()->getUnsignedVersion());
335 Step = cast<SCEVUnknown>(Stride)->getValue();
336 assert(Step->getType()->isUnsigned() && "Bad step value!");
339 // Now that we know the base and stride contributed by the GEP instruction,
340 // process all users.
341 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
343 Instruction *User = cast<Instruction>(*UI);
345 // Do not infinitely recurse on PHI nodes.
346 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
349 // If this is an instruction defined in a nested loop, or outside this loop,
350 // don't mess with it.
351 if (LI->getLoopFor(User->getParent()) != L)
354 DEBUG(std::cerr << "FOUND USER: " << *User
355 << " OF STRIDE: " << *Step << " BASE = " << *Base << "\n");
357 // Okay, we found a user that we cannot reduce. Analyze the instruction
358 // and decide what to do with it.
359 IVUsesByStride[Step].addUser(Base, User, GEP);
363 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
364 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
365 /// return true. Otherwise, return false.
366 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L) {
367 if (I->getType() == Type::VoidTy) return false;
368 SCEVHandle ISE = SE->getSCEV(I);
369 if (!CanReduceSCEV(ISE, L)) return false;
371 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ISE);
372 SCEVHandle Start = AR->getStart();
374 // Get the step value, canonicalizing to an unsigned integer type so that
375 // lookups in the map will match.
376 Value *Step = 0; // Step of ISE.
377 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(AR->getOperand(1)))
378 /// Always get the step value as an unsigned value.
379 Step = ConstantExpr::getCast(SC->getValue(),
380 SC->getValue()->getType()->getUnsignedVersion());
382 Step = cast<SCEVUnknown>(AR->getOperand(1))->getValue();
383 assert(Step->getType()->isUnsigned() && "Bad step value!");
385 std::set<GetElementPtrInst*> AnalyzedGEPs;
387 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
388 Instruction *User = cast<Instruction>(*UI);
390 // Do not infinitely recurse on PHI nodes.
391 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
394 // If this is an instruction defined in a nested loop, or outside this loop,
395 // don't mess with it.
396 if (LI->getLoopFor(User->getParent()) != L)
399 // Next, see if this user is analyzable itself!
400 if (!AddUsersIfInteresting(User, L)) {
401 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
402 // If this is a getelementptr instruction, figure out what linear
403 // expression of induction variable is actually being used.
405 if (AnalyzedGEPs.insert(GEP).second) // Not already analyzed?
406 AnalyzeGetElementPtrUsers(GEP, I, L);
408 DEBUG(std::cerr << "FOUND USER: " << *User
409 << " OF SCEV: " << *ISE << "\n");
411 // Okay, we found a user that we cannot reduce. Analyze the instruction
412 // and decide what to do with it.
413 IVUsesByStride[Step].addUser(Start, User, I);
421 /// BasedUser - For a particular base value, keep information about how we've
422 /// partitioned the expression so far.
424 /// Inst - The instruction using the induction variable.
427 /// OperandValToReplace - The operand value of Inst to replace with the
429 Value *OperandValToReplace;
431 /// Imm - The immediate value that should be added to the base immediately
432 /// before Inst, because it will be folded into the imm field of the
436 /// EmittedBase - The actual value* to use for the base value of this
437 /// operation. This is null if we should just use zero so far.
440 BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM)
441 : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0) {}
444 // No need to compare these.
445 bool operator<(const BasedUser &BU) const { return 0; }
451 void BasedUser::dump() const {
452 std::cerr << " Imm=" << *Imm;
454 std::cerr << " EB=" << *EmittedBase;
456 std::cerr << " Inst: " << *Inst;
459 /// isTargetConstant - Return true if the following can be referenced by the
460 /// immediate field of a target instruction.
461 static bool isTargetConstant(const SCEVHandle &V) {
463 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
464 if (isa<SCEVConstant>(V)) return true;
466 return false; // ENABLE this for x86
468 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
469 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
470 if (CE->getOpcode() == Instruction::Cast)
471 if (isa<GlobalValue>(CE->getOperand(0)))
472 // FIXME: should check to see that the dest is uintptr_t!
477 /// GetImmediateValues - Look at Val, and pull out any additions of constants
478 /// that can fit into the immediate field of instructions in the target.
479 static SCEVHandle GetImmediateValues(SCEVHandle Val, bool isAddress) {
481 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
482 if (isTargetConstant(Val))
485 SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val);
488 for (; i != SAE->getNumOperands(); ++i)
489 if (isTargetConstant(SAE->getOperand(i))) {
490 SCEVHandle ImmVal = SAE->getOperand(i);
492 // If there are any other immediates that we can handle here, pull them
494 for (++i; i != SAE->getNumOperands(); ++i)
495 if (isTargetConstant(SAE->getOperand(i)))
496 ImmVal = SCEVAddExpr::get(ImmVal, SAE->getOperand(i));
501 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
504 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
505 /// stride of IV. All of the users may have different starting values, and this
506 /// may not be the only stride (we know it is if isOnlyStride is true).
507 void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
508 IVUsersOfOneStride &Uses,
511 // Transform our list of users and offsets to a bit more complex table. In
512 // this new vector, the first entry for each element is the base of the
513 // strided access, and the second is the BasedUser object for the use. We
514 // progressively move information from the first to the second entry, until we
515 // eventually emit the object.
516 std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
517 UsersToProcess.reserve(Uses.Users.size());
519 SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
520 Uses.Users[0].Offset->getType());
522 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
523 UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
524 BasedUser(Uses.Users[i].User,
525 Uses.Users[i].OperandValToReplace,
528 // First pass, figure out what we can represent in the immediate fields of
529 // instructions. If we can represent anything there, move it to the imm
530 // fields of the BasedUsers.
531 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
532 bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst) ||
533 isa<StoreInst>(UsersToProcess[i].second.Inst);
534 UsersToProcess[i].second.Imm = GetImmediateValues(UsersToProcess[i].first,
536 UsersToProcess[i].first = SCEV::getMinusSCEV(UsersToProcess[i].first,
537 UsersToProcess[i].second.Imm);
539 DEBUG(std::cerr << "BASE: " << *UsersToProcess[i].first);
540 DEBUG(UsersToProcess[i].second.dump());
543 SCEVExpander Rewriter(*SE, *LI);
544 BasicBlock *Preheader = L->getLoopPreheader();
545 Instruction *PreInsertPt = Preheader->getTerminator();
546 Instruction *PhiInsertBefore = L->getHeader()->begin();
548 assert(isa<PHINode>(PhiInsertBefore) &&
549 "How could this loop have IV's without any phis?");
550 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
551 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
552 "This loop isn't canonicalized right");
553 BasicBlock *LatchBlock =
554 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
556 // FIXME: This loop needs increasing levels of intelligence.
557 // STAGE 0: just emit everything as its own base. <-- We are here
558 // STAGE 1: factor out common vars from bases, and try and push resulting
559 // constants into Imm field.
560 // STAGE 2: factor out large constants to try and make more constants
561 // acceptable for target loads and stores.
562 std::sort(UsersToProcess.begin(), UsersToProcess.end());
564 while (!UsersToProcess.empty()) {
565 // Create a new Phi for this base, and stick it in the loop header.
566 Value *Replaced = UsersToProcess.front().second.OperandValToReplace;
567 const Type *ReplacedTy = Replaced->getType();
568 PHINode *NewPHI = new PHINode(ReplacedTy, Replaced->getName()+".str",
571 // Emit the initial base value into the loop preheader, and add it to the
573 Value *BaseV = Rewriter.expandCodeFor(UsersToProcess.front().first,
574 PreInsertPt, ReplacedTy);
575 NewPHI->addIncoming(BaseV, Preheader);
577 // Emit the increment of the base value before the terminator of the loop
578 // latch block, and add it to the Phi node.
579 SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
580 SCEVUnknown::get(Stride));
582 Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
584 IncV->setName(NewPHI->getName()+".inc");
585 NewPHI->addIncoming(IncV, LatchBlock);
587 // Emit the code to add the immediate offset to the Phi value, just before
588 // the instruction that we identified as using this stride and base.
589 // First, empty the SCEVExpander's expression map so that we are guaranteed
590 // to have the code emitted where we expect it.
592 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
593 UsersToProcess.front().second.Imm);
594 Value *newVal = Rewriter.expandCodeFor(NewValSCEV,
595 UsersToProcess.front().second.Inst,
598 // Replace the use of the operand Value with the new Phi we just created.
599 DEBUG(std::cerr << "REPLACING: " << *Replaced << "IN: " <<
600 *UsersToProcess.front().second.Inst << "WITH: "<< *newVal << '\n');
601 UsersToProcess.front().second.Inst->replaceUsesOfWith(Replaced, newVal);
603 // Mark old value we replaced as possibly dead, so that it is elminated
604 // if we just replaced the last use of that value.
605 DeadInsts.insert(cast<Instruction>(Replaced));
607 UsersToProcess.erase(UsersToProcess.begin());
610 // TODO: Next, find out which base index is the most common, pull it out.
613 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
614 // different starting values, into different PHIs.
616 // BEFORE writing this, it's probably useful to handle GEP's.
618 // NOTE: pull all constants together, for REG+IMM addressing, include &GV in
619 // 'IMM' if the target supports it.
623 void LoopStrengthReduce::runOnLoop(Loop *L) {
624 // First step, transform all loops nesting inside of this loop.
625 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
628 // Next, find all uses of induction variables in this loop, and catagorize
629 // them by stride. Start by finding all of the PHI nodes in the header for
630 // this loop. If they are induction variables, inspect their uses.
631 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
632 AddUsersIfInteresting(I, L);
634 // If we have nothing to do, return.
635 //if (IVUsesByStride.empty()) return;
637 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
638 // doing computation in byte values, promote to 32-bit values if safe.
640 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
641 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
642 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
643 // to be careful that IV's are all the same type. Only works for intptr_t
646 // If we only have one stride, we can more aggressively eliminate some things.
647 bool HasOneStride = IVUsesByStride.size() == 1;
649 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
650 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
651 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
653 // Clean up after ourselves
654 if (!DeadInsts.empty()) {
655 DeleteTriviallyDeadInstructions(DeadInsts);
657 BasicBlock::iterator I = L->getHeader()->begin();
659 while ((PN = dyn_cast<PHINode>(I))) {
660 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
662 // At this point, we know that we have killed one or more GEP instructions.
663 // It is worth checking to see if the cann indvar is also dead, so that we
664 // can remove it as well. The requirements for the cann indvar to be
665 // considered dead are:
666 // 1. the cann indvar has one use
667 // 2. the use is an add instruction
668 // 3. the add has one use
669 // 4. the add is used by the cann indvar
670 // If all four cases above are true, then we can remove both the add and
672 // FIXME: this needs to eliminate an induction variable even if it's being
673 // compared against some value to decide loop termination.
674 if (PN->hasOneUse()) {
675 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
676 if (BO && BO->hasOneUse()) {
677 if (PN == *(BO->use_begin())) {
678 DeadInsts.insert(BO);
679 // Break the cycle, then delete the PHI.
680 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
681 SE->deleteInstructionFromRecords(PN);
682 PN->eraseFromParent();
687 DeleteTriviallyDeadInstructions(DeadInsts);
690 IVUsesByStride.clear();
691 CastedBasePointers.clear();