1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass implements an idiom recognizer that transforms simple loops into a
11 // non-loop form. In cases that this kicks in, it can be a significant
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "loop-idiom"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/ScalarEvolutionExpander.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/IRBuilder.h"
26 #include "llvm/Support/raw_ostream.h"
29 // TODO: Recognize "N" size array multiplies: replace with call to blas or
33 class LoopIdiomRecognize : public LoopPass {
39 explicit LoopIdiomRecognize() : LoopPass(ID) {
40 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
43 bool runOnLoop(Loop *L, LPPassManager &LPM);
45 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
47 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
49 const SCEVAddRecExpr *Ev,
52 /// This transformation requires natural loop information & requires that
53 /// loop preheaders be inserted into the CFG.
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired<LoopInfo>();
57 AU.addPreserved<LoopInfo>();
58 AU.addRequiredID(LoopSimplifyID);
59 AU.addPreservedID(LoopSimplifyID);
60 AU.addRequiredID(LCSSAID);
61 AU.addPreservedID(LCSSAID);
62 AU.addRequired<ScalarEvolution>();
63 AU.addPreserved<ScalarEvolution>();
64 AU.addPreserved<DominatorTree>();
69 char LoopIdiomRecognize::ID = 0;
70 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
72 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
73 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
74 INITIALIZE_PASS_DEPENDENCY(LCSSA)
75 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
76 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
79 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
81 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
82 /// and zero out all the operands of this instruction. If any of them become
83 /// dead, delete them and the computation tree that feeds them.
85 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
86 SmallVector<Instruction*, 32> NowDeadInsts;
88 NowDeadInsts.push_back(I);
90 // Before we touch this instruction, remove it from SE!
92 Instruction *DeadInst = NowDeadInsts.pop_back_val();
94 // This instruction is dead, zap it, in stages. Start by removing it from
96 SE.forgetValue(DeadInst);
98 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
99 Value *Op = DeadInst->getOperand(op);
100 DeadInst->setOperand(op, 0);
102 // If this operand just became dead, add it to the NowDeadInsts list.
103 if (!Op->use_empty()) continue;
105 if (Instruction *OpI = dyn_cast<Instruction>(Op))
106 if (isInstructionTriviallyDead(OpI))
107 NowDeadInsts.push_back(OpI);
110 DeadInst->eraseFromParent();
112 } while (!NowDeadInsts.empty());
115 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
118 // We only look at trivial single basic block loops.
119 // TODO: eventually support more complex loops, scanning the header.
120 if (L->getBlocks().size() != 1)
123 // The trip count of the loop must be analyzable.
124 SE = &getAnalysis<ScalarEvolution>();
125 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
127 const SCEV *BECount = SE->getBackedgeTakenCount(L);
128 if (isa<SCEVCouldNotCompute>(BECount)) return false;
130 // We require target data for now.
131 TD = getAnalysisIfAvailable<TargetData>();
132 if (TD == 0) return false;
134 BasicBlock *BB = L->getHeader();
135 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
136 << "] Loop %" << BB->getName() << "\n");
138 bool MadeChange = false;
139 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
140 // Look for store instructions, which may be memsets.
141 StoreInst *SI = dyn_cast<StoreInst>(I++);
142 if (SI == 0 || SI->isVolatile()) continue;
145 if (processLoopStore(SI, BECount)) {
146 // If processing the store invalidated our iterator, start over from the
156 /// scanBlock - Look over a block to see if we can promote anything out of it.
157 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
158 Value *StoredVal = SI->getValueOperand();
159 Value *StorePtr = SI->getPointerOperand();
161 // Check to see if the store updates all bits in memory. We don't want to
162 // process things like a store of i3. We also require that the store be a
163 // multiple of a byte.
164 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
165 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0 ||
166 SizeInBits != TD->getTypeStoreSizeInBits(StoredVal->getType()))
169 // See if the pointer expression is an AddRec like {base,+,1} on the current
170 // loop, which indicates a strided store. If we have something else, it's a
171 // random store we can't handle.
172 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
173 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
176 // Check to see if the stride matches the size of the store. If so, then we
177 // know that every byte is touched in the loop.
178 unsigned StoreSize = (unsigned)SizeInBits >> 3;
179 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
180 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
183 // If the stored value is a byte-wise value (like i32 -1), then it may be
184 // turned into a memset of i8 -1, assuming that all the consequtive bytes
185 // are stored. A store of i32 0x01020304 can never be turned into a memset.
186 if (Value *SplatValue = isBytewiseValue(StoredVal))
187 return processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, Ev, BECount);
189 // Handle the memcpy case here.
190 errs() << "Found strided store: " << *Ev << "\n";
196 /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
197 /// If we can transform this into a memset in the loop preheader, do so.
198 bool LoopIdiomRecognize::
199 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
201 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
202 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
203 // this into a memset in the loop preheader now if we want. However, this
204 // would be unsafe to do if there is anything else in the loop that may read
205 // or write to the aliased location. Check for an alias.
207 // FIXME: TODO safety check.
209 // Okay, everything looks good, insert the memset.
210 BasicBlock *Preheader = CurLoop->getLoopPreheader();
212 IRBuilder<> Builder(Preheader->getTerminator());
214 // The trip count of the loop and the base pointer of the addrec SCEV is
215 // guaranteed to be loop invariant, which means that it should dominate the
216 // header. Just insert code for it in the preheader.
217 SCEVExpander Expander(*SE);
219 unsigned AddrSpace = SI->getPointerAddressSpace();
221 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
222 Preheader->getTerminator());
224 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
225 // pointer size if it isn't already.
226 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
227 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
228 if (BESize < TD->getPointerSizeInBits())
229 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
230 else if (BESize > TD->getPointerSizeInBits())
231 BECount = SE->getTruncateExpr(BECount, IntPtr);
233 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
234 true, true /*nooverflow*/);
236 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
237 true, true /*nooverflow*/);
240 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
243 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
245 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
246 << " from store to: " << *Ev << " at: " << *SI << "\n");
248 // Okay, the memset has been formed. Zap the original store and anything that
250 DeleteDeadInstruction(SI, *SE);