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 #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"
38 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
42 GEPCache() : CachedPHINode(0), Map() {}
44 GEPCache *get(Value *v) {
45 std::map<Value *, GEPCache>::iterator I = Map.find(v);
47 I = Map.insert(std::pair<Value *, GEPCache>(v, GEPCache())).first;
51 PHINode *CachedPHINode;
52 std::map<Value *, GEPCache> Map;
55 /// IVStrideUse - Keep track of one use of a strided induction variable, where
56 /// the stride is stored externally. The Offset member keeps track of the
57 /// offset from the IV, User is the actual user of the operand, and 'Operand'
58 /// is the operand # of the User that is the use.
62 Value *OperandValToReplace;
64 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
65 : Offset(Offs), User(U), OperandValToReplace(O) {}
68 /// IVUsersOfOneStride - This structure keeps track of all instructions that
69 /// have an operand that is based on the trip count multiplied by some stride.
70 /// The stride for all of these users is common and kept external to this
72 struct IVUsersOfOneStride {
73 /// Users - Keep track of all of the users of this stride as well as the
74 /// initial value and the operand that uses the IV.
75 std::vector<IVStrideUse> Users;
77 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
78 Users.push_back(IVStrideUse(Offset, User, Operand));
83 class LoopStrengthReduce : public FunctionPass {
88 const Type *UIntPtrTy;
91 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
92 /// target can handle for free with its addressing modes.
93 unsigned MaxTargetAMSize;
95 /// IVUsesByStride - Keep track of all uses of induction variables that we
96 /// are interested in. The key of the map is the stride of the access.
97 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
99 /// CastedBasePointers - As we need to lower getelementptr instructions, we
100 /// cast the pointer input to uintptr_t. This keeps track of the casted
101 /// values for the pointers we have processed so far.
102 std::map<Value*, Value*> CastedBasePointers;
104 /// DeadInsts - Keep track of instructions we may have made dead, so that
105 /// we can remove them after we are done working.
106 std::set<Instruction*> DeadInsts;
108 LoopStrengthReduce(unsigned MTAMS = 1)
109 : MaxTargetAMSize(MTAMS) {
112 virtual bool runOnFunction(Function &) {
113 LI = &getAnalysis<LoopInfo>();
114 DS = &getAnalysis<DominatorSet>();
115 SE = &getAnalysis<ScalarEvolution>();
116 TD = &getAnalysis<TargetData>();
117 UIntPtrTy = TD->getIntPtrType();
120 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
125 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
126 AU.setPreservesCFG();
127 AU.addRequiredID(LoopSimplifyID);
128 AU.addRequired<LoopInfo>();
129 AU.addRequired<DominatorSet>();
130 AU.addRequired<TargetData>();
131 AU.addRequired<ScalarEvolution>();
134 void runOnLoop(Loop *L);
135 bool AddUsersIfInteresting(Instruction *I, Loop *L);
136 void AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP, Instruction *I,
139 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
140 Loop *L, bool isOnlyStride);
142 void strengthReduceGEP(GetElementPtrInst *GEPI, Loop *L,
144 Instruction *InsertBefore,
145 std::set<Instruction*> &DeadInsts);
146 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
148 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
149 "Strength Reduce GEP Uses of Ind. Vars");
152 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
153 return new LoopStrengthReduce(MaxTargetAMSize);
156 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
157 /// specified set are trivially dead, delete them and see if this makes any of
158 /// their operands subsequently dead.
159 void LoopStrengthReduce::
160 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
161 while (!Insts.empty()) {
162 Instruction *I = *Insts.begin();
163 Insts.erase(Insts.begin());
164 if (isInstructionTriviallyDead(I)) {
165 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
166 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
168 SE->deleteInstructionFromRecords(I);
169 I->eraseFromParent();
176 /// CanReduceSCEV - Return true if we can strength reduce this scalar evolution
177 /// in the specified loop.
178 static bool CanReduceSCEV(const SCEVHandle &SH, Loop *L) {
179 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH);
180 if (!AddRec || AddRec->getLoop() != L) return false;
182 // FIXME: Generalize to non-affine IV's.
183 if (!AddRec->isAffine()) return false;
185 // FIXME: generalize to IV's with more complex strides (must emit stride
186 // expression outside of loop!)
187 if (isa<SCEVConstant>(AddRec->getOperand(1)))
190 // We handle steps by unsigned values, because we know we won't have to insert
192 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(AddRec->getOperand(1)))
193 if (SU->getValue()->getType()->isUnsigned())
196 // Otherwise, no, we can't handle it yet.
201 /// GetAdjustedIndex - Adjust the specified GEP sequential type index to match
202 /// the size of the pointer type, and scale it by the type size.
203 static SCEVHandle GetAdjustedIndex(const SCEVHandle &Idx, uint64_t TySize,
204 const Type *UIntPtrTy) {
205 SCEVHandle Result = Idx;
206 if (Result->getType()->getUnsignedVersion() != UIntPtrTy) {
207 if (UIntPtrTy->getPrimitiveSize() < Result->getType()->getPrimitiveSize())
208 Result = SCEVTruncateExpr::get(Result, UIntPtrTy);
210 Result = SCEVZeroExtendExpr::get(Result, UIntPtrTy);
213 // This index is scaled by the type size being indexed.
215 Result = SCEVMulExpr::get(Result,
216 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
221 /// AnalyzeGetElementPtrUsers - Analyze all of the users of the specified
222 /// getelementptr instruction, adding them to the IVUsesByStride table. Note
223 /// that we only want to analyze a getelementptr instruction once, and it can
224 /// have multiple operands that are uses of the indvar (e.g. A[i][i]). Because
225 /// of this, we only process a GEP instruction if its first recurrent operand is
226 /// "op", otherwise we will either have already processed it or we will sometime
228 void LoopStrengthReduce::AnalyzeGetElementPtrUsers(GetElementPtrInst *GEP,
229 Instruction *Op, Loop *L) {
230 // Analyze all of the subscripts of this getelementptr instruction, looking
231 // for uses that are determined by the trip count of L. First, skip all
232 // operands the are not dependent on the IV.
234 // Build up the base expression. Insert an LLVM cast of the pointer to
237 if (Constant *CB = dyn_cast<Constant>(GEP->getOperand(0)))
238 BasePtr = ConstantExpr::getCast(CB, UIntPtrTy);
240 Value *&BP = CastedBasePointers[GEP->getOperand(0)];
242 BasicBlock::iterator InsertPt;
243 if (isa<Argument>(GEP->getOperand(0))) {
244 InsertPt = GEP->getParent()->getParent()->begin()->begin();
246 InsertPt = cast<Instruction>(GEP->getOperand(0));
247 if (InvokeInst *II = dyn_cast<InvokeInst>(GEP->getOperand(0)))
248 InsertPt = II->getNormalDest()->begin();
253 // Do not insert casts into the middle of PHI node blocks.
254 while (isa<PHINode>(InsertPt)) ++InsertPt;
256 BP = new CastInst(GEP->getOperand(0), UIntPtrTy,
257 GEP->getOperand(0)->getName(), InsertPt);
262 SCEVHandle Base = SCEVUnknown::get(BasePtr);
264 gep_type_iterator GTI = gep_type_begin(GEP);
266 for (; GEP->getOperand(i) != Op; ++i, ++GTI) {
267 // If this is a use of a recurrence that we can analyze, and it comes before
268 // Op does in the GEP operand list, we will handle this when we process this
270 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
271 const StructLayout *SL = TD->getStructLayout(STy);
272 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
273 uint64_t Offset = SL->MemberOffsets[Idx];
274 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
277 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
279 // If this operand is reducible, and it's not the one we are looking at
280 // currently, do not process the GEP at this time.
281 if (CanReduceSCEV(Idx, L))
283 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
284 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
288 // Get the index, convert it to intptr_t.
289 SCEVHandle GEPIndexExpr =
290 GetAdjustedIndex(SE->getSCEV(Op), TD->getTypeSize(GTI.getIndexedType()),
293 // Process all remaining subscripts in the GEP instruction.
294 for (++i, ++GTI; i != GEP->getNumOperands(); ++i, ++GTI)
295 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
296 const StructLayout *SL = TD->getStructLayout(STy);
297 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
298 uint64_t Offset = SL->MemberOffsets[Idx];
299 Base = SCEVAddExpr::get(Base, SCEVUnknown::getIntegerSCEV(Offset,
302 SCEVHandle Idx = SE->getSCEV(GEP->getOperand(i));
303 if (CanReduceSCEV(Idx, L)) { // Another IV subscript
304 GEPIndexExpr = SCEVAddExpr::get(GEPIndexExpr,
305 GetAdjustedIndex(Idx, TD->getTypeSize(GTI.getIndexedType()),
307 assert(CanReduceSCEV(GEPIndexExpr, L) &&
308 "Cannot reduce the sum of two reducible SCEV's??");
310 Base = SCEVAddExpr::get(Base, GetAdjustedIndex(Idx,
311 TD->getTypeSize(GTI.getIndexedType()), UIntPtrTy));
315 assert(CanReduceSCEV(GEPIndexExpr, L) && "Non reducible idx??");
317 // FIXME: If the base is not loop invariant, we currently cannot emit this.
318 if (!Base->isLoopInvariant(L)) {
319 DEBUG(std::cerr << "IGNORING GEP due to non-invaiant base: "
324 Base = SCEVAddExpr::get(Base, cast<SCEVAddRecExpr>(GEPIndexExpr)->getStart());
325 SCEVHandle Stride = cast<SCEVAddRecExpr>(GEPIndexExpr)->getOperand(1);
327 DEBUG(std::cerr << "GEP BASE : " << *Base << "\n");
328 DEBUG(std::cerr << "GEP STRIDE: " << *Stride << "\n");
330 Value *Step = 0; // Step of ISE.
331 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride))
332 /// Always get the step value as an unsigned value.
333 Step = ConstantExpr::getCast(SC->getValue(),
334 SC->getValue()->getType()->getUnsignedVersion());
336 Step = cast<SCEVUnknown>(Stride)->getValue();
337 assert(Step->getType()->isUnsigned() && "Bad step value!");
340 // Now that we know the base and stride contributed by the GEP instruction,
341 // process all users.
342 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
344 Instruction *User = cast<Instruction>(*UI);
346 // Do not infinitely recurse on PHI nodes.
347 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
350 // If this is an instruction defined in a nested loop, or outside this loop,
351 // don't mess with it.
352 if (LI->getLoopFor(User->getParent()) != L)
355 DEBUG(std::cerr << "FOUND USER: " << *User
356 << " OF STRIDE: " << *Step << " BASE = " << *Base << "\n");
358 // Okay, we found a user that we cannot reduce. Analyze the instruction
359 // and decide what to do with it.
360 IVUsesByStride[Step].addUser(Base, User, GEP);
364 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
365 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
366 /// return true. Otherwise, return false.
367 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L) {
368 if (I->getType() == Type::VoidTy) return false;
369 SCEVHandle ISE = SE->getSCEV(I);
370 if (!CanReduceSCEV(ISE, L)) return false;
372 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ISE);
373 SCEVHandle Start = AR->getStart();
375 // Get the step value, canonicalizing to an unsigned integer type so that
376 // lookups in the map will match.
377 Value *Step = 0; // Step of ISE.
378 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(AR->getOperand(1)))
379 /// Always get the step value as an unsigned value.
380 Step = ConstantExpr::getCast(SC->getValue(),
381 SC->getValue()->getType()->getUnsignedVersion());
383 Step = cast<SCEVUnknown>(AR->getOperand(1))->getValue();
384 assert(Step->getType()->isUnsigned() && "Bad step value!");
386 std::set<GetElementPtrInst*> AnalyzedGEPs;
388 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
389 Instruction *User = cast<Instruction>(*UI);
391 // Do not infinitely recurse on PHI nodes.
392 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
395 // If this is an instruction defined in a nested loop, or outside this loop,
396 // don't mess with it.
397 if (LI->getLoopFor(User->getParent()) != L)
400 // Next, see if this user is analyzable itself!
401 if (!AddUsersIfInteresting(User, L)) {
402 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
403 // If this is a getelementptr instruction, figure out what linear
404 // expression of induction variable is actually being used.
406 if (AnalyzedGEPs.insert(GEP).second) // Not already analyzed?
407 AnalyzeGetElementPtrUsers(GEP, I, L);
409 DEBUG(std::cerr << "FOUND USER: " << *User
410 << " OF SCEV: " << *ISE << "\n");
412 // Okay, we found a user that we cannot reduce. Analyze the instruction
413 // and decide what to do with it.
414 IVUsesByStride[Step].addUser(Start, User, I);
422 /// BasedUser - For a particular base value, keep information about how we've
423 /// partitioned the expression so far.
425 /// Inst - The instruction using the induction variable.
428 /// OperandValToReplace - The operand value of Inst to replace with the
430 Value *OperandValToReplace;
432 /// Imm - The immediate value that should be added to the base immediately
433 /// before Inst, because it will be folded into the imm field of the
437 /// EmittedBase - The actual value* to use for the base value of this
438 /// operation. This is null if we should just use zero so far.
441 BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM)
442 : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0) {}
445 // No need to compare these.
446 bool operator<(const BasedUser &BU) const { return 0; }
452 void BasedUser::dump() const {
453 std::cerr << " Imm=" << *Imm;
455 std::cerr << " EB=" << *EmittedBase;
457 std::cerr << " Inst: " << *Inst;
460 /// isTargetConstant - Return true if the following can be referenced by the
461 /// immediate field of a target instruction.
462 static bool isTargetConstant(const SCEVHandle &V) {
464 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
465 if (isa<SCEVConstant>(V)) return true;
467 return false; // ENABLE this for x86
469 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
470 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
471 if (CE->getOpcode() == Instruction::Cast)
472 if (isa<GlobalValue>(CE->getOperand(0)))
473 // FIXME: should check to see that the dest is uintptr_t!
478 /// GetImmediateValues - Look at Val, and pull out any additions of constants
479 /// that can fit into the immediate field of instructions in the target.
480 static SCEVHandle GetImmediateValues(SCEVHandle Val, bool isAddress) {
482 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
483 if (isTargetConstant(Val))
486 if (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));
499 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
500 // Try to pull immediates out of the start value of nested addrec's.
501 return GetImmediateValues(SARE->getStart(), isAddress);
504 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
507 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
508 /// stride of IV. All of the users may have different starting values, and this
509 /// may not be the only stride (we know it is if isOnlyStride is true).
510 void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
511 IVUsersOfOneStride &Uses,
514 // Transform our list of users and offsets to a bit more complex table. In
515 // this new vector, the first entry for each element is the base of the
516 // strided access, and the second is the BasedUser object for the use. We
517 // progressively move information from the first to the second entry, until we
518 // eventually emit the object.
519 std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
520 UsersToProcess.reserve(Uses.Users.size());
522 SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
523 Uses.Users[0].Offset->getType());
525 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
526 UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
527 BasedUser(Uses.Users[i].User,
528 Uses.Users[i].OperandValToReplace,
531 // First pass, figure out what we can represent in the immediate fields of
532 // instructions. If we can represent anything there, move it to the imm
533 // fields of the BasedUsers.
534 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
535 bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst) ||
536 isa<StoreInst>(UsersToProcess[i].second.Inst);
537 UsersToProcess[i].second.Imm = GetImmediateValues(UsersToProcess[i].first,
539 UsersToProcess[i].first = SCEV::getMinusSCEV(UsersToProcess[i].first,
540 UsersToProcess[i].second.Imm);
542 DEBUG(std::cerr << "BASE: " << *UsersToProcess[i].first);
543 DEBUG(UsersToProcess[i].second.dump());
546 SCEVExpander Rewriter(*SE, *LI);
547 BasicBlock *Preheader = L->getLoopPreheader();
548 Instruction *PreInsertPt = Preheader->getTerminator();
549 Instruction *PhiInsertBefore = L->getHeader()->begin();
551 assert(isa<PHINode>(PhiInsertBefore) &&
552 "How could this loop have IV's without any phis?");
553 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
554 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
555 "This loop isn't canonicalized right");
556 BasicBlock *LatchBlock =
557 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
559 DEBUG(std::cerr << "INSERTING IVs of STRIDE " << *Stride << ":\n");
561 // FIXME: This loop needs increasing levels of intelligence.
562 // STAGE 0: just emit everything as its own base.
563 // STAGE 1: factor out common vars from bases, and try and push resulting
564 // constants into Imm field. <-- We are here
565 // STAGE 2: factor out large constants to try and make more constants
566 // acceptable for target loads and stores.
568 // Sort by the base value, so that all IVs with identical bases are next to
570 std::sort(UsersToProcess.begin(), UsersToProcess.end());
571 while (!UsersToProcess.empty()) {
572 SCEVHandle Base = UsersToProcess.front().first;
574 DEBUG(std::cerr << " INSERTING PHI with BASE = " << *Base << ":\n");
576 // Create a new Phi for this base, and stick it in the loop header.
577 const Type *ReplacedTy = Base->getType();
578 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
580 // Emit the initial base value into the loop preheader, and add it to the
582 Value *BaseV = Rewriter.expandCodeFor(Base, PreInsertPt, ReplacedTy);
583 NewPHI->addIncoming(BaseV, Preheader);
585 // Emit the increment of the base value before the terminator of the loop
586 // latch block, and add it to the Phi node.
587 SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
588 SCEVUnknown::get(Stride));
590 Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
592 IncV->setName(NewPHI->getName()+".inc");
593 NewPHI->addIncoming(IncV, LatchBlock);
595 // Emit the code to add the immediate offset to the Phi value, just before
596 // the instructions that we identified as using this stride and base.
597 while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) {
598 BasedUser &User = UsersToProcess.front().second;
600 // Clear the SCEVExpander's expression map so that we are guaranteed
601 // to have the code emitted where we expect it.
603 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
605 Value *Replaced = User.OperandValToReplace;
606 Value *newVal = Rewriter.expandCodeFor(NewValSCEV, User.Inst,
607 Replaced->getType());
609 // Replace the use of the operand Value with the new Phi we just created.
610 User.Inst->replaceUsesOfWith(Replaced, newVal);
611 DEBUG(std::cerr << " CHANGED: IMM =" << *User.Imm << " Inst = "
614 // Mark old value we replaced as possibly dead, so that it is elminated
615 // if we just replaced the last use of that value.
616 DeadInsts.insert(cast<Instruction>(Replaced));
618 UsersToProcess.erase(UsersToProcess.begin());
621 // TODO: Next, find out which base index is the most common, pull it out.
624 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
625 // different starting values, into different PHIs.
627 // BEFORE writing this, it's probably useful to handle GEP's.
629 // NOTE: pull all constants together, for REG+IMM addressing, include &GV in
630 // 'IMM' if the target supports it.
634 void LoopStrengthReduce::runOnLoop(Loop *L) {
635 // First step, transform all loops nesting inside of this loop.
636 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
639 // Next, find all uses of induction variables in this loop, and catagorize
640 // them by stride. Start by finding all of the PHI nodes in the header for
641 // this loop. If they are induction variables, inspect their uses.
642 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
643 AddUsersIfInteresting(I, L);
645 // If we have nothing to do, return.
646 //if (IVUsesByStride.empty()) return;
648 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
649 // doing computation in byte values, promote to 32-bit values if safe.
651 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
652 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
653 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
654 // to be careful that IV's are all the same type. Only works for intptr_t
657 // If we only have one stride, we can more aggressively eliminate some things.
658 bool HasOneStride = IVUsesByStride.size() == 1;
660 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
661 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
662 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
664 // Clean up after ourselves
665 if (!DeadInsts.empty()) {
666 DeleteTriviallyDeadInstructions(DeadInsts);
668 BasicBlock::iterator I = L->getHeader()->begin();
670 while ((PN = dyn_cast<PHINode>(I))) {
671 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
673 // At this point, we know that we have killed one or more GEP instructions.
674 // It is worth checking to see if the cann indvar is also dead, so that we
675 // can remove it as well. The requirements for the cann indvar to be
676 // considered dead are:
677 // 1. the cann indvar has one use
678 // 2. the use is an add instruction
679 // 3. the add has one use
680 // 4. the add is used by the cann indvar
681 // If all four cases above are true, then we can remove both the add and
683 // FIXME: this needs to eliminate an induction variable even if it's being
684 // compared against some value to decide loop termination.
685 if (PN->hasOneUse()) {
686 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
687 if (BO && BO->hasOneUse()) {
688 if (PN == *(BO->use_begin())) {
689 DeadInsts.insert(BO);
690 // Break the cycle, then delete the PHI.
691 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
692 SE->deleteInstructionFromRecords(PN);
693 PN->eraseFromParent();
698 DeleteTriviallyDeadInstructions(DeadInsts);
701 IVUsesByStride.clear();
702 CastedBasePointers.clear();