blob: f6dcfb88b30e84a1d4e12a48211f38912fb91169 [file] [log] [blame]
Chris Lattnere6bb6492010-12-26 19:39:38 +00001//===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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
12// performance win.
13//
14//===----------------------------------------------------------------------===//
Chris Lattnerbdce5722011-01-02 18:32:09 +000015//
16// TODO List:
17//
18// Future loop memory idioms to recognize:
19// memcmp, memmove, strlen, etc.
20// Future floating point idioms to recognize in -ffast-math mode:
21// fpowi
22// Future integer operation idioms to recognize:
23// ctpop, ctlz, cttz
24//
25// Beware that isel's default lowering for ctpop is highly inefficient for
26// i64 and larger types when i64 is legal and the value has few bits set. It
27// would be good to enhance isel to emit a loop for ctpop in this case.
28//
29// We should enhance the memset/memcpy recognition to handle multiple stores in
30// the loop. This would handle things like:
31// void foo(_Complex float *P)
32// for (i) { __real__(*P) = 0; __imag__(*P) = 0; }
33// this is also "Example 2" from http://blog.regehr.org/archives/320
Chris Lattner91139cc2011-01-02 23:19:45 +000034//
Chris Lattnerd957c712011-01-03 01:10:08 +000035// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner91139cc2011-01-02 23:19:45 +000036// replace them with calls to BLAS (if linked in??).
37//
Chris Lattnerbdce5722011-01-02 18:32:09 +000038//===----------------------------------------------------------------------===//
Chris Lattnere6bb6492010-12-26 19:39:38 +000039
40#define DEBUG_TYPE "loop-idiom"
41#include "llvm/Transforms/Scalar.h"
Chris Lattnere41d3c02011-01-04 07:46:33 +000042#include "llvm/IntrinsicInst.h"
Chris Lattner2e12f1a2010-12-27 18:39:08 +000043#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000044#include "llvm/Analysis/LoopPass.h"
45#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner22920b52010-12-26 20:45:45 +000047#include "llvm/Analysis/ValueTracking.h"
48#include "llvm/Target/TargetData.h"
Chris Lattner9f391882010-12-27 00:03:23 +000049#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000050#include "llvm/Support/Debug.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000051#include "llvm/Support/IRBuilder.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000052#include "llvm/Support/raw_ostream.h"
Chris Lattner4ce31fb2011-01-02 07:36:44 +000053#include "llvm/ADT/Statistic.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000054using namespace llvm;
55
Chris Lattner4ce31fb2011-01-02 07:36:44 +000056STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
57STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattnere6bb6492010-12-26 19:39:38 +000058
59namespace {
60 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000061 Loop *CurLoop;
62 const TargetData *TD;
Chris Lattner62c50fd2011-01-02 19:01:03 +000063 DominatorTree *DT;
Chris Lattner22920b52010-12-26 20:45:45 +000064 ScalarEvolution *SE;
Chris Lattnere6bb6492010-12-26 19:39:38 +000065 public:
66 static char ID;
67 explicit LoopIdiomRecognize() : LoopPass(ID) {
68 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
69 }
70
71 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner62c50fd2011-01-02 19:01:03 +000072 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
73 SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattnere6bb6492010-12-26 19:39:38 +000074
Chris Lattner22920b52010-12-26 20:45:45 +000075 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +000076 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
Chris Lattnere6bb6492010-12-26 19:39:38 +000077
Chris Lattnere41d3c02011-01-04 07:46:33 +000078 bool processLoopStoreOfSplatValue(Value *DestPtr, unsigned StoreSize,
79 unsigned StoreAlignment,
80 Value *SplatValue, Instruction *TheStore,
Chris Lattnera92ff912010-12-26 23:42:51 +000081 const SCEVAddRecExpr *Ev,
82 const SCEV *BECount);
Chris Lattnere2c43922011-01-02 03:37:56 +000083 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
84 const SCEVAddRecExpr *StoreEv,
85 const SCEVAddRecExpr *LoadEv,
86 const SCEV *BECount);
87
Chris Lattnere6bb6492010-12-26 19:39:38 +000088 /// This transformation requires natural loop information & requires that
89 /// loop preheaders be inserted into the CFG.
90 ///
91 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addRequired<LoopInfo>();
93 AU.addPreserved<LoopInfo>();
94 AU.addRequiredID(LoopSimplifyID);
95 AU.addPreservedID(LoopSimplifyID);
96 AU.addRequiredID(LCSSAID);
97 AU.addPreservedID(LCSSAID);
Chris Lattner2e12f1a2010-12-27 18:39:08 +000098 AU.addRequired<AliasAnalysis>();
99 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000100 AU.addRequired<ScalarEvolution>();
101 AU.addPreserved<ScalarEvolution>();
102 AU.addPreserved<DominatorTree>();
Chris Lattner62c50fd2011-01-02 19:01:03 +0000103 AU.addRequired<DominatorTree>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000104 }
105 };
106}
107
108char LoopIdiomRecognize::ID = 0;
109INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
110 false, false)
111INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chris Lattner62c50fd2011-01-02 19:01:03 +0000112INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000113INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
114INITIALIZE_PASS_DEPENDENCY(LCSSA)
115INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000116INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000117INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
118 false, false)
119
120Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
121
Chris Lattner9f391882010-12-27 00:03:23 +0000122/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
123/// and zero out all the operands of this instruction. If any of them become
124/// dead, delete them and the computation tree that feeds them.
125///
126static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
127 SmallVector<Instruction*, 32> NowDeadInsts;
128
129 NowDeadInsts.push_back(I);
130
131 // Before we touch this instruction, remove it from SE!
132 do {
133 Instruction *DeadInst = NowDeadInsts.pop_back_val();
134
135 // This instruction is dead, zap it, in stages. Start by removing it from
136 // SCEV.
137 SE.forgetValue(DeadInst);
138
139 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
140 Value *Op = DeadInst->getOperand(op);
141 DeadInst->setOperand(op, 0);
142
143 // If this operand just became dead, add it to the NowDeadInsts list.
144 if (!Op->use_empty()) continue;
145
146 if (Instruction *OpI = dyn_cast<Instruction>(Op))
147 if (isInstructionTriviallyDead(OpI))
148 NowDeadInsts.push_back(OpI);
149 }
150
151 DeadInst->eraseFromParent();
152
153 } while (!NowDeadInsts.empty());
154}
155
Chris Lattnere6bb6492010-12-26 19:39:38 +0000156bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000157 CurLoop = L;
158
Chris Lattner22920b52010-12-26 20:45:45 +0000159 // The trip count of the loop must be analyzable.
160 SE = &getAnalysis<ScalarEvolution>();
161 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
162 return false;
163 const SCEV *BECount = SE->getBackedgeTakenCount(L);
164 if (isa<SCEVCouldNotCompute>(BECount)) return false;
165
Chris Lattner8e08e732011-01-02 20:24:21 +0000166 // If this loop executes exactly one time, then it should be peeled, not
167 // optimized by this pass.
168 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
169 if (BECst->getValue()->getValue() == 0)
170 return false;
171
Chris Lattner22920b52010-12-26 20:45:45 +0000172 // We require target data for now.
173 TD = getAnalysisIfAvailable<TargetData>();
174 if (TD == 0) return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000175
Chris Lattner62c50fd2011-01-02 19:01:03 +0000176 DT = &getAnalysis<DominatorTree>();
177 LoopInfo &LI = getAnalysis<LoopInfo>();
178
179 SmallVector<BasicBlock*, 8> ExitBlocks;
180 CurLoop->getUniqueExitBlocks(ExitBlocks);
181
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000182 DEBUG(dbgs() << "loop-idiom Scanning: F["
183 << L->getHeader()->getParent()->getName()
184 << "] Loop %" << L->getHeader()->getName() << "\n");
185
Chris Lattner62c50fd2011-01-02 19:01:03 +0000186 bool MadeChange = false;
187 // Scan all the blocks in the loop that are not in subloops.
188 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
189 ++BI) {
190 // Ignore blocks in subloops.
191 if (LI.getLoopFor(*BI) != CurLoop)
192 continue;
193
194 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
195 }
196 return MadeChange;
197}
198
199/// runOnLoopBlock - Process the specified block, which lives in a counted loop
200/// with the specified backedge count. This block is known to be in the current
201/// loop and not in any subloops.
202bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
203 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
204 // We can only promote stores in this block if they are unconditionally
205 // executed in the loop. For a block to be unconditionally executed, it has
206 // to dominate all the exit blocks of the loop. Verify this now.
207 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
208 if (!DT->dominates(BB, ExitBlocks[i]))
209 return false;
210
Chris Lattner22920b52010-12-26 20:45:45 +0000211 bool MadeChange = false;
212 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000213 Instruction *Inst = I++;
214 // Look for store instructions, which may be optimized to memset/memcpy.
215 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000216 WeakVH InstPtr(I);
217 if (!processLoopStore(SI, BECount)) continue;
218 MadeChange = true;
219
220 // If processing the store invalidated our iterator, start over from the
Chris Lattnere41d3c02011-01-04 07:46:33 +0000221 // top of the block.
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000222 if (InstPtr == 0)
223 I = BB->begin();
224 continue;
225 }
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000226
Chris Lattnere41d3c02011-01-04 07:46:33 +0000227 // Look for memset instructions, which may be optimized to a larger memset.
228 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
229 WeakVH InstPtr(I);
230 if (!processLoopMemSet(MSI, BECount)) continue;
231 MadeChange = true;
232
233 // If processing the memset invalidated our iterator, start over from the
234 // top of the block.
235 if (InstPtr == 0)
236 I = BB->begin();
237 continue;
238 }
Chris Lattner22920b52010-12-26 20:45:45 +0000239 }
240
241 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000242}
243
Chris Lattner62c50fd2011-01-02 19:01:03 +0000244
Chris Lattnere41d3c02011-01-04 07:46:33 +0000245/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner22920b52010-12-26 20:45:45 +0000246bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Chris Lattnere41d3c02011-01-04 07:46:33 +0000247 if (SI->isVolatile()) return false;
248
Chris Lattner22920b52010-12-26 20:45:45 +0000249 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000250 Value *StorePtr = SI->getPointerOperand();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000251
Chris Lattner95ae6762010-12-28 18:53:48 +0000252 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner22920b52010-12-26 20:45:45 +0000253 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000254 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000255 return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000256
Chris Lattner22920b52010-12-26 20:45:45 +0000257 // See if the pointer expression is an AddRec like {base,+,1} on the current
258 // loop, which indicates a strided store. If we have something else, it's a
259 // random store we can't handle.
Chris Lattnere2c43922011-01-02 03:37:56 +0000260 const SCEVAddRecExpr *StoreEv =
261 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
262 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner22920b52010-12-26 20:45:45 +0000263 return false;
264
265 // Check to see if the stride matches the size of the store. If so, then we
266 // know that every byte is touched in the loop.
267 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattnere2c43922011-01-02 03:37:56 +0000268 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Chris Lattner30980b62011-01-01 19:39:01 +0000269
270 // TODO: Could also handle negative stride here someday, that will require the
Owen Anderson6f96b272011-01-03 23:51:56 +0000271 // validity check in mayLoopAccessLocation to be updated though.
Chris Lattner22920b52010-12-26 20:45:45 +0000272 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
273 return false;
274
Chris Lattner22920b52010-12-26 20:45:45 +0000275 // If the stored value is a byte-wise value (like i32 -1), then it may be
Duncan Sandsab4c3662011-02-15 09:23:02 +0000276 // turned into a memset of i8 -1, assuming that all the consecutive bytes
Chris Lattner22920b52010-12-26 20:45:45 +0000277 // are stored. A store of i32 0x01020304 can never be turned into a memset.
Chris Lattnera92ff912010-12-26 23:42:51 +0000278 if (Value *SplatValue = isBytewiseValue(StoredVal))
Chris Lattnere41d3c02011-01-04 07:46:33 +0000279 if (processLoopStoreOfSplatValue(StorePtr, StoreSize, SI->getAlignment(),
280 SplatValue, SI, StoreEv, BECount))
Chris Lattnere2c43922011-01-02 03:37:56 +0000281 return true;
Chris Lattnera92ff912010-12-26 23:42:51 +0000282
Chris Lattnere2c43922011-01-02 03:37:56 +0000283 // If the stored value is a strided load in the same loop with the same stride
284 // this this may be transformable into a memcpy. This kicks in for stuff like
285 // for (i) A[i] = B[i];
286 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
287 const SCEVAddRecExpr *LoadEv =
288 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
289 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
290 StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
291 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
292 return true;
293 }
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000294 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000295
Chris Lattnere6bb6492010-12-26 19:39:38 +0000296 return false;
297}
298
Chris Lattnere41d3c02011-01-04 07:46:33 +0000299/// processLoopMemSet - See if this memset can be promoted to a large memset.
300bool LoopIdiomRecognize::
301processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
302 // We can only handle non-volatile memsets with a constant size.
303 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
304
305 Value *Pointer = MSI->getDest();
306
307 // See if the pointer expression is an AddRec like {base,+,1} on the current
308 // loop, which indicates a strided store. If we have something else, it's a
309 // random store we can't handle.
310 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
311 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
312 return false;
313
314 // Reject memsets that are so large that they overflow an unsigned.
315 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
316 if ((SizeInBytes >> 32) != 0)
317 return false;
318
319 // Check to see if the stride matches the size of the memset. If so, then we
320 // know that every byte is touched in the loop.
321 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
322
323 // TODO: Could also handle negative stride here someday, that will require the
324 // validity check in mayLoopAccessLocation to be updated though.
325 if (Stride == 0 || MSI->getLength() != Stride->getValue())
326 return false;
327
328 return processLoopStoreOfSplatValue(Pointer, (unsigned)SizeInBytes,
329 MSI->getAlignment(), MSI->getValue(),
330 MSI, Ev, BECount);
331}
332
333
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000334/// mayLoopAccessLocation - Return true if the specified loop might access the
335/// specified pointer location, which is a loop-strided access. The 'Access'
336/// argument specifies what the verboten forms of access are (read or write).
337static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
338 Loop *L, const SCEV *BECount,
Chris Lattnere2c43922011-01-02 03:37:56 +0000339 unsigned StoreSize, AliasAnalysis &AA,
Chris Lattnere41d3c02011-01-04 07:46:33 +0000340 Instruction *IgnoredStore) {
Chris Lattner30980b62011-01-01 19:39:01 +0000341 // Get the location that may be stored across the loop. Since the access is
342 // strided positively through memory, we say that the modified location starts
343 // at the pointer and has infinite size.
Chris Lattnera64cbf02011-01-01 19:54:22 +0000344 uint64_t AccessSize = AliasAnalysis::UnknownSize;
345
346 // If the loop iterates a fixed number of times, we can refine the access size
347 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
348 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
349 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
350
351 // TODO: For this to be really effective, we have to dive into the pointer
352 // operand in the store. Store to &A[i] of 100 will always return may alias
353 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
354 // which will then no-alias a store to &A[100].
Chris Lattnere2c43922011-01-02 03:37:56 +0000355 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
Chris Lattner30980b62011-01-01 19:39:01 +0000356
357 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
358 ++BI)
359 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Chris Lattnere2c43922011-01-02 03:37:56 +0000360 if (&*I != IgnoredStore &&
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000361 (AA.getModRefInfo(I, StoreLoc) & Access))
Chris Lattner30980b62011-01-01 19:39:01 +0000362 return true;
363
364 return false;
365}
366
Chris Lattnera92ff912010-12-26 23:42:51 +0000367/// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
368/// If we can transform this into a memset in the loop preheader, do so.
369bool LoopIdiomRecognize::
Chris Lattnere41d3c02011-01-04 07:46:33 +0000370processLoopStoreOfSplatValue(Value *DestPtr, unsigned StoreSize,
371 unsigned StoreAlignment, Value *SplatValue,
372 Instruction *TheStore,
Chris Lattnera92ff912010-12-26 23:42:51 +0000373 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
Chris Lattnerbafa1172011-01-01 20:12:04 +0000374 // Verify that the stored value is loop invariant. If not, we can't promote
375 // the memset.
376 if (!CurLoop->isLoopInvariant(SplatValue))
377 return false;
378
Chris Lattnera92ff912010-12-26 23:42:51 +0000379 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
380 // this into a memset in the loop preheader now if we want. However, this
381 // would be unsafe to do if there is anything else in the loop that may read
382 // or write to the aliased location. Check for an alias.
Chris Lattnere41d3c02011-01-04 07:46:33 +0000383 if (mayLoopAccessLocation(DestPtr, AliasAnalysis::ModRef,
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000384 CurLoop, BECount,
Chris Lattnere41d3c02011-01-04 07:46:33 +0000385 StoreSize, getAnalysis<AliasAnalysis>(), TheStore))
Chris Lattnere2c43922011-01-02 03:37:56 +0000386 return false;
Chris Lattnera92ff912010-12-26 23:42:51 +0000387
388 // Okay, everything looks good, insert the memset.
389 BasicBlock *Preheader = CurLoop->getLoopPreheader();
390
391 IRBuilder<> Builder(Preheader->getTerminator());
392
393 // The trip count of the loop and the base pointer of the addrec SCEV is
394 // guaranteed to be loop invariant, which means that it should dominate the
395 // header. Just insert code for it in the preheader.
396 SCEVExpander Expander(*SE);
397
Chris Lattnere41d3c02011-01-04 07:46:33 +0000398 unsigned AddrSpace = cast<PointerType>(DestPtr->getType())->getAddressSpace();
Chris Lattnera92ff912010-12-26 23:42:51 +0000399 Value *BasePtr =
400 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
401 Preheader->getTerminator());
402
403 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
404 // pointer size if it isn't already.
Chris Lattnere41d3c02011-01-04 07:46:33 +0000405 const Type *IntPtr = TD->getIntPtrType(SplatValue->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +0000406 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Chris Lattnera92ff912010-12-26 23:42:51 +0000407
408 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Chris Lattner7c90b902011-01-04 00:06:55 +0000409 true /*no unsigned overflow*/);
Chris Lattnera92ff912010-12-26 23:42:51 +0000410 if (StoreSize != 1)
411 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Chris Lattner7c90b902011-01-04 00:06:55 +0000412 true /*no unsigned overflow*/);
Chris Lattnera92ff912010-12-26 23:42:51 +0000413
414 Value *NumBytes =
415 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
416
417 Value *NewCall =
Chris Lattnere41d3c02011-01-04 07:46:33 +0000418 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Chris Lattnera92ff912010-12-26 23:42:51 +0000419
420 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattnere41d3c02011-01-04 07:46:33 +0000421 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Duncan Sands7922d342010-12-28 09:41:15 +0000422 (void)NewCall;
Chris Lattnera92ff912010-12-26 23:42:51 +0000423
Chris Lattner9f391882010-12-27 00:03:23 +0000424 // Okay, the memset has been formed. Zap the original store and anything that
425 // feeds into it.
Chris Lattnere41d3c02011-01-04 07:46:33 +0000426 DeleteDeadInstruction(TheStore, *SE);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000427 ++NumMemSet;
Chris Lattnera92ff912010-12-26 23:42:51 +0000428 return true;
429}
430
Chris Lattnere2c43922011-01-02 03:37:56 +0000431/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
432/// same-strided load.
433bool LoopIdiomRecognize::
434processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
435 const SCEVAddRecExpr *StoreEv,
436 const SCEVAddRecExpr *LoadEv,
437 const SCEV *BECount) {
438 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
439
440 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chris Lattnerbdce5722011-01-02 18:32:09 +0000441 // this into a memcpy in the loop preheader now if we want. However, this
Chris Lattnere2c43922011-01-02 03:37:56 +0000442 // would be unsafe to do if there is anything else in the loop that may read
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000443 // or write to the stored location (including the load feeding the stores).
Chris Lattnere2c43922011-01-02 03:37:56 +0000444 // Check for an alias.
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000445 if (mayLoopAccessLocation(SI->getPointerOperand(), AliasAnalysis::ModRef,
446 CurLoop, BECount, StoreSize,
447 getAnalysis<AliasAnalysis>(), SI))
448 return false;
449
450 // For a memcpy, we have to make sure that the input array is not being
451 // mutated by the loop.
452 if (mayLoopAccessLocation(LI->getPointerOperand(), AliasAnalysis::Mod,
453 CurLoop, BECount, StoreSize,
454 getAnalysis<AliasAnalysis>(), SI))
Chris Lattnere2c43922011-01-02 03:37:56 +0000455 return false;
456
457 // Okay, everything looks good, insert the memcpy.
458 BasicBlock *Preheader = CurLoop->getLoopPreheader();
459
460 IRBuilder<> Builder(Preheader->getTerminator());
461
462 // The trip count of the loop and the base pointer of the addrec SCEV is
463 // guaranteed to be loop invariant, which means that it should dominate the
464 // header. Just insert code for it in the preheader.
465 SCEVExpander Expander(*SE);
466
467 Value *LoadBasePtr =
468 Expander.expandCodeFor(LoadEv->getStart(),
469 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
470 Preheader->getTerminator());
471 Value *StoreBasePtr =
472 Expander.expandCodeFor(StoreEv->getStart(),
473 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
474 Preheader->getTerminator());
475
476 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
477 // pointer size if it isn't already.
478 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +0000479 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Chris Lattnere2c43922011-01-02 03:37:56 +0000480
481 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Chris Lattner7c90b902011-01-04 00:06:55 +0000482 true /*no unsigned overflow*/);
Chris Lattnere2c43922011-01-02 03:37:56 +0000483 if (StoreSize != 1)
484 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Chris Lattner7c90b902011-01-04 00:06:55 +0000485 true /*no unsigned overflow*/);
Chris Lattnere2c43922011-01-02 03:37:56 +0000486
487 Value *NumBytes =
488 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
489
490 Value *NewCall =
491 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
492 std::min(SI->getAlignment(), LI->getAlignment()));
493
494 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
495 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
496 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
497 (void)NewCall;
498
499 // Okay, the memset has been formed. Zap the original store and anything that
500 // feeds into it.
501 DeleteDeadInstruction(SI, *SE);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000502 ++NumMemCpy;
Chris Lattnere2c43922011-01-02 03:37:56 +0000503 return true;
504}