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");
40 /// IVStrideUse - Keep track of one use of a strided induction variable, where
41 /// the stride is stored externally. The Offset member keeps track of the
42 /// offset from the IV, User is the actual user of the operand, and 'Operand'
43 /// is the operand # of the User that is the use.
47 Value *OperandValToReplace;
49 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
50 : Offset(Offs), User(U), OperandValToReplace(O) {}
53 /// IVUsersOfOneStride - This structure keeps track of all instructions that
54 /// have an operand that is based on the trip count multiplied by some stride.
55 /// The stride for all of these users is common and kept external to this
57 struct IVUsersOfOneStride {
58 /// Users - Keep track of all of the users of this stride as well as the
59 /// initial value and the operand that uses the IV.
60 std::vector<IVStrideUse> Users;
62 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
63 Users.push_back(IVStrideUse(Offset, User, Operand));
68 class LoopStrengthReduce : public FunctionPass {
73 const Type *UIntPtrTy;
76 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
77 /// target can handle for free with its addressing modes.
78 unsigned MaxTargetAMSize;
80 /// IVUsesByStride - Keep track of all uses of induction variables that we
81 /// are interested in. The key of the map is the stride of the access.
82 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
84 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
85 /// of the casted version of each value. This is accessed by
86 /// getCastedVersionOf.
87 std::map<Value*, Value*> CastedPointers;
89 /// DeadInsts - Keep track of instructions we may have made dead, so that
90 /// we can remove them after we are done working.
91 std::set<Instruction*> DeadInsts;
93 LoopStrengthReduce(unsigned MTAMS = 1)
94 : MaxTargetAMSize(MTAMS) {
97 virtual bool runOnFunction(Function &) {
98 LI = &getAnalysis<LoopInfo>();
99 DS = &getAnalysis<DominatorSet>();
100 SE = &getAnalysis<ScalarEvolution>();
101 TD = &getAnalysis<TargetData>();
102 UIntPtrTy = TD->getIntPtrType();
105 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
108 CastedPointers.clear();
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>();
121 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
123 Value *getCastedVersionOf(Value *V);
125 void runOnLoop(Loop *L);
126 bool AddUsersIfInteresting(Instruction *I, Loop *L,
127 std::set<Instruction*> &Processed);
128 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
131 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
132 Loop *L, bool isOnlyStride);
133 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
135 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
136 "Strength Reduce GEP Uses of Ind. Vars");
139 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
140 return new LoopStrengthReduce(MaxTargetAMSize);
143 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
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);
150 Value *&New = CastedPointers[V];
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;
159 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
160 InsertPt = II->getNormalDest()->begin();
162 InsertPt = cast<Instruction>(V);
166 // Do not insert casts into the middle of PHI node blocks.
167 while (isa<PHINode>(InsertPt)) ++InsertPt;
170 return New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
174 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
175 /// specified set are trivially dead, delete them and see if this makes any of
176 /// their operands subsequently dead.
177 void LoopStrengthReduce::
178 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
179 while (!Insts.empty()) {
180 Instruction *I = *Insts.begin();
181 Insts.erase(Insts.begin());
182 if (isInstructionTriviallyDead(I)) {
183 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
184 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
186 SE->deleteInstructionFromRecords(I);
187 I->eraseFromParent();
194 /// CanReduceSCEV - Return true if we can strength reduce this scalar evolution
195 /// in the specified loop.
196 static bool CanReduceSCEV(const SCEVHandle &SH, Loop *L) {
197 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH);
198 if (!AddRec || AddRec->getLoop() != L) return false;
200 // FIXME: Generalize to non-affine IV's.
201 if (!AddRec->isAffine()) return false;
203 // FIXME: generalize to IV's with more complex strides (must emit stride
204 // expression outside of loop!)
205 if (isa<SCEVConstant>(AddRec->getOperand(1)))
208 // We handle steps by unsigned values, because we know we won't have to insert
210 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(AddRec->getOperand(1)))
211 if (SU->getValue()->getType()->isUnsigned())
214 // Otherwise, no, we can't handle it yet.
218 /// GetExpressionSCEV - Compute and return the SCEV for the specified
220 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
221 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
223 return SE->getSCEV(Exp);
225 // Analyze all of the subscripts of this getelementptr instruction, looking
226 // for uses that are determined by the trip count of L. First, skip all
227 // operands the are not dependent on the IV.
229 // Build up the base expression. Insert an LLVM cast of the pointer to
231 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
233 gep_type_iterator GTI = gep_type_begin(GEP);
235 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
236 // If this is a use of a recurrence that we can analyze, and it comes before
237 // Op does in the GEP operand list, we will handle this when we process this
239 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
240 const StructLayout *SL = TD->getStructLayout(STy);
241 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
242 uint64_t Offset = SL->MemberOffsets[Idx];
243 GEPVal = SCEVAddExpr::get(GEPVal,
244 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
246 SCEVHandle Idx = SE->getSCEV(getCastedVersionOf(GEP->getOperand(i)));
247 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
249 Idx = SCEVMulExpr::get(Idx,
250 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
252 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
256 //assert(CanReduceSCEV(GEPVal, L) && "Cannot reduce this use of IV?");
260 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
261 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
262 /// return true. Otherwise, return false.
263 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
264 std::set<Instruction*> &Processed) {
265 if (I->getType() == Type::VoidTy) return false;
266 if (!Processed.insert(I).second)
267 return true; // Instruction already handled.
269 SCEVHandle ISE = GetExpressionSCEV(I, L);
270 if (!CanReduceSCEV(ISE, L))
271 return false; // Non-analyzable expression, e.g. a rem instr.
273 // NOT SAFE with generalized EXPRS
274 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(ISE);
275 SCEVHandle Start = AR->getStart();
277 // Get the step value, canonicalizing to an unsigned integer type so that
278 // lookups in the map will match.
279 Value *Step = 0; // Step of ISE.
280 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(AR->getOperand(1)))
281 /// Always get the step value as an unsigned value.
282 Step = ConstantExpr::getCast(SC->getValue(),
283 SC->getValue()->getType()->getUnsignedVersion());
285 Step = cast<SCEVUnknown>(AR->getOperand(1))->getValue();
286 assert(Step->getType()->isUnsigned() && "Bad step value!");
288 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
289 Instruction *User = cast<Instruction>(*UI);
291 // Do not infinitely recurse on PHI nodes.
292 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
295 // If this is an instruction defined in a nested loop, or outside this loop,
296 // don't recurse into it.
297 if (LI->getLoopFor(User->getParent()) != L) {
298 DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
299 << " OF SCEV: " << *ISE << "\n");
301 // Okay, we found a user that we cannot reduce. Analyze the instruction
302 // and decide what to do with it.
303 IVUsesByStride[Step].addUser(Start, User, I);
304 } else if (!AddUsersIfInteresting(User, L, Processed)) {
305 DEBUG(std::cerr << "FOUND USER: " << *User
306 << " OF SCEV: " << *ISE << "\n");
308 // Okay, we found a user that we cannot reduce. Analyze the instruction
309 // and decide what to do with it.
310 IVUsesByStride[Step].addUser(Start, User, I);
317 /// BasedUser - For a particular base value, keep information about how we've
318 /// partitioned the expression so far.
320 /// Inst - The instruction using the induction variable.
323 /// OperandValToReplace - The operand value of Inst to replace with the
325 Value *OperandValToReplace;
327 /// Imm - The immediate value that should be added to the base immediately
328 /// before Inst, because it will be folded into the imm field of the
332 /// EmittedBase - The actual value* to use for the base value of this
333 /// operation. This is null if we should just use zero so far.
336 BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM)
337 : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0) {}
340 // No need to compare these.
341 bool operator<(const BasedUser &BU) const { return 0; }
347 void BasedUser::dump() const {
348 std::cerr << " Imm=" << *Imm;
350 std::cerr << " EB=" << *EmittedBase;
352 std::cerr << " Inst: " << *Inst;
355 /// isTargetConstant - Return true if the following can be referenced by the
356 /// immediate field of a target instruction.
357 static bool isTargetConstant(const SCEVHandle &V) {
359 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
360 if (isa<SCEVConstant>(V)) return true;
362 return false; // ENABLE this for x86
364 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
365 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
366 if (CE->getOpcode() == Instruction::Cast)
367 if (isa<GlobalValue>(CE->getOperand(0)))
368 // FIXME: should check to see that the dest is uintptr_t!
373 /// GetImmediateValues - Look at Val, and pull out any additions of constants
374 /// that can fit into the immediate field of instructions in the target.
375 static SCEVHandle GetImmediateValues(SCEVHandle Val, bool isAddress) {
377 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
378 if (isTargetConstant(Val))
381 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
383 for (; i != SAE->getNumOperands(); ++i)
384 if (isTargetConstant(SAE->getOperand(i))) {
385 SCEVHandle ImmVal = SAE->getOperand(i);
387 // If there are any other immediates that we can handle here, pull them
389 for (++i; i != SAE->getNumOperands(); ++i)
390 if (isTargetConstant(SAE->getOperand(i)))
391 ImmVal = SCEVAddExpr::get(ImmVal, SAE->getOperand(i));
394 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
395 // Try to pull immediates out of the start value of nested addrec's.
396 return GetImmediateValues(SARE->getStart(), isAddress);
399 return SCEVUnknown::getIntegerSCEV(0, Val->getType());
402 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
403 /// stride of IV. All of the users may have different starting values, and this
404 /// may not be the only stride (we know it is if isOnlyStride is true).
405 void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
406 IVUsersOfOneStride &Uses,
409 // Transform our list of users and offsets to a bit more complex table. In
410 // this new vector, the first entry for each element is the base of the
411 // strided access, and the second is the BasedUser object for the use. We
412 // progressively move information from the first to the second entry, until we
413 // eventually emit the object.
414 std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
415 UsersToProcess.reserve(Uses.Users.size());
417 SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
418 Uses.Users[0].Offset->getType());
420 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
421 UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
422 BasedUser(Uses.Users[i].User,
423 Uses.Users[i].OperandValToReplace,
426 // First pass, figure out what we can represent in the immediate fields of
427 // instructions. If we can represent anything there, move it to the imm
428 // fields of the BasedUsers.
429 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
430 bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst) ||
431 isa<StoreInst>(UsersToProcess[i].second.Inst);
432 UsersToProcess[i].second.Imm = GetImmediateValues(UsersToProcess[i].first,
434 UsersToProcess[i].first = SCEV::getMinusSCEV(UsersToProcess[i].first,
435 UsersToProcess[i].second.Imm);
437 DEBUG(std::cerr << "BASE: " << *UsersToProcess[i].first);
438 DEBUG(UsersToProcess[i].second.dump());
441 SCEVExpander Rewriter(*SE, *LI);
442 BasicBlock *Preheader = L->getLoopPreheader();
443 Instruction *PreInsertPt = Preheader->getTerminator();
444 Instruction *PhiInsertBefore = L->getHeader()->begin();
446 assert(isa<PHINode>(PhiInsertBefore) &&
447 "How could this loop have IV's without any phis?");
448 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
449 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
450 "This loop isn't canonicalized right");
451 BasicBlock *LatchBlock =
452 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
454 DEBUG(std::cerr << "INSERTING IVs of STRIDE " << *Stride << ":\n");
456 // FIXME: This loop needs increasing levels of intelligence.
457 // STAGE 0: just emit everything as its own base.
458 // STAGE 1: factor out common vars from bases, and try and push resulting
459 // constants into Imm field. <-- We are here
460 // STAGE 2: factor out large constants to try and make more constants
461 // acceptable for target loads and stores.
463 // Sort by the base value, so that all IVs with identical bases are next to
465 std::sort(UsersToProcess.begin(), UsersToProcess.end());
466 while (!UsersToProcess.empty()) {
467 SCEVHandle Base = UsersToProcess.front().first;
469 DEBUG(std::cerr << " INSERTING PHI with BASE = " << *Base << ":\n");
471 // Create a new Phi for this base, and stick it in the loop header.
472 const Type *ReplacedTy = Base->getType();
473 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
475 // Emit the initial base value into the loop preheader, and add it to the
477 Value *BaseV = Rewriter.expandCodeFor(Base, PreInsertPt, ReplacedTy);
478 NewPHI->addIncoming(BaseV, Preheader);
480 // Emit the increment of the base value before the terminator of the loop
481 // latch block, and add it to the Phi node.
482 SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
483 SCEVUnknown::get(Stride));
485 Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
487 IncV->setName(NewPHI->getName()+".inc");
488 NewPHI->addIncoming(IncV, LatchBlock);
490 // Emit the code to add the immediate offset to the Phi value, just before
491 // the instructions that we identified as using this stride and base.
492 while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) {
493 BasedUser &User = UsersToProcess.front().second;
495 // Clear the SCEVExpander's expression map so that we are guaranteed
496 // to have the code emitted where we expect it.
498 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
500 Value *Replaced = User.OperandValToReplace;
501 Value *newVal = Rewriter.expandCodeFor(NewValSCEV, User.Inst,
502 Replaced->getType());
504 // Replace the use of the operand Value with the new Phi we just created.
505 User.Inst->replaceUsesOfWith(Replaced, newVal);
506 DEBUG(std::cerr << " CHANGED: IMM =" << *User.Imm << " Inst = "
509 // Mark old value we replaced as possibly dead, so that it is elminated
510 // if we just replaced the last use of that value.
511 DeadInsts.insert(cast<Instruction>(Replaced));
513 UsersToProcess.erase(UsersToProcess.begin());
516 // TODO: Next, find out which base index is the most common, pull it out.
519 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
520 // different starting values, into different PHIs.
522 // BEFORE writing this, it's probably useful to handle GEP's.
524 // NOTE: pull all constants together, for REG+IMM addressing, include &GV in
525 // 'IMM' if the target supports it.
529 void LoopStrengthReduce::runOnLoop(Loop *L) {
530 // First step, transform all loops nesting inside of this loop.
531 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
534 // Next, find all uses of induction variables in this loop, and catagorize
535 // them by stride. Start by finding all of the PHI nodes in the header for
536 // this loop. If they are induction variables, inspect their uses.
537 std::set<Instruction*> Processed; // Don't reprocess instructions.
538 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
539 AddUsersIfInteresting(I, L, Processed);
541 // If we have nothing to do, return.
542 //if (IVUsesByStride.empty()) return;
544 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
545 // doing computation in byte values, promote to 32-bit values if safe.
547 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
548 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
549 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
550 // to be careful that IV's are all the same type. Only works for intptr_t
553 // If we only have one stride, we can more aggressively eliminate some things.
554 bool HasOneStride = IVUsesByStride.size() == 1;
556 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
557 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
558 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
560 // Clean up after ourselves
561 if (!DeadInsts.empty()) {
562 DeleteTriviallyDeadInstructions(DeadInsts);
564 BasicBlock::iterator I = L->getHeader()->begin();
566 while ((PN = dyn_cast<PHINode>(I))) {
567 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
569 // At this point, we know that we have killed one or more GEP instructions.
570 // It is worth checking to see if the cann indvar is also dead, so that we
571 // can remove it as well. The requirements for the cann indvar to be
572 // considered dead are:
573 // 1. the cann indvar has one use
574 // 2. the use is an add instruction
575 // 3. the add has one use
576 // 4. the add is used by the cann indvar
577 // If all four cases above are true, then we can remove both the add and
579 // FIXME: this needs to eliminate an induction variable even if it's being
580 // compared against some value to decide loop termination.
581 if (PN->hasOneUse()) {
582 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
583 if (BO && BO->hasOneUse()) {
584 if (PN == *(BO->use_begin())) {
585 DeadInsts.insert(BO);
586 // Break the cycle, then delete the PHI.
587 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
588 SE->deleteInstructionFromRecords(PN);
589 PN->eraseFromParent();
594 DeleteTriviallyDeadInstructions(DeadInsts);
597 IVUsesByStride.clear();