blob: 5c398a8b693327a7cd864c4fe2441527b01ea272 [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; }
Chris Lattner91139cc2011-01-02 23:19:45 +000033//
Chris Lattner408b5342011-02-21 02:08:54 +000034// We should enhance this to handle negative strides through memory.
35// Alternatively (and perhaps better) we could rely on an earlier pass to force
36// forward iteration through memory, which is generally better for cache
37// behavior. Negative strides *do* happen for memset/memcpy loops.
38//
Chris Lattnerd957c712011-01-03 01:10:08 +000039// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner91139cc2011-01-02 23:19:45 +000040// replace them with calls to BLAS (if linked in??).
41//
Chris Lattnerbdce5722011-01-02 18:32:09 +000042//===----------------------------------------------------------------------===//
Chris Lattnere6bb6492010-12-26 19:39:38 +000043
44#define DEBUG_TYPE "loop-idiom"
45#include "llvm/Transforms/Scalar.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000046#include "llvm/IRBuilder.h"
Chris Lattnere41d3c02011-01-04 07:46:33 +000047#include "llvm/IntrinsicInst.h"
Chris Lattner3a393722011-02-19 19:31:39 +000048#include "llvm/Module.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000049#include "llvm/ADT/Statistic.h"
Chris Lattner2e12f1a2010-12-27 18:39:08 +000050#include "llvm/Analysis/AliasAnalysis.h"
Benjamin Kramer5c6e9ae2012-10-21 15:03:07 +000051#include "llvm/Analysis/LoopDependenceAnalysis.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000052#include "llvm/Analysis/LoopPass.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000053#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000054#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner22920b52010-12-26 20:45:45 +000055#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000056#include "llvm/Support/Debug.h"
57#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000058#include "llvm/DataLayout.h"
Chris Lattnerc19175c2011-02-18 22:22:15 +000059#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner9f391882010-12-27 00:03:23 +000060#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000061using namespace llvm;
62
Chris Lattner4ce31fb2011-01-02 07:36:44 +000063STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
64STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattnere6bb6492010-12-26 19:39:38 +000065
66namespace {
67 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000068 Loop *CurLoop;
Micah Villmow3574eca2012-10-08 16:38:25 +000069 const DataLayout *TD;
Chris Lattner62c50fd2011-01-02 19:01:03 +000070 DominatorTree *DT;
Chris Lattner22920b52010-12-26 20:45:45 +000071 ScalarEvolution *SE;
Chris Lattnerc19175c2011-02-18 22:22:15 +000072 TargetLibraryInfo *TLI;
Chris Lattnere6bb6492010-12-26 19:39:38 +000073 public:
74 static char ID;
75 explicit LoopIdiomRecognize() : LoopPass(ID) {
76 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
77 }
78
79 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner62c50fd2011-01-02 19:01:03 +000080 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
81 SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattnere6bb6492010-12-26 19:39:38 +000082
Chris Lattner22920b52010-12-26 20:45:45 +000083 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +000084 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
Andrew Trickd99b39e2011-03-14 16:48:10 +000085
Chris Lattner3a393722011-02-19 19:31:39 +000086 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
87 unsigned StoreAlignment,
88 Value *SplatValue, Instruction *TheStore,
89 const SCEVAddRecExpr *Ev,
90 const SCEV *BECount);
Chris Lattnere2c43922011-01-02 03:37:56 +000091 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
92 const SCEVAddRecExpr *StoreEv,
93 const SCEVAddRecExpr *LoadEv,
94 const SCEV *BECount);
Andrew Trickd99b39e2011-03-14 16:48:10 +000095
Chris Lattnere6bb6492010-12-26 19:39:38 +000096 /// This transformation requires natural loop information & requires that
97 /// loop preheaders be inserted into the CFG.
98 ///
99 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.addRequired<LoopInfo>();
101 AU.addPreserved<LoopInfo>();
102 AU.addRequiredID(LoopSimplifyID);
103 AU.addPreservedID(LoopSimplifyID);
104 AU.addRequiredID(LCSSAID);
105 AU.addPreservedID(LCSSAID);
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000106 AU.addRequired<AliasAnalysis>();
107 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000108 AU.addRequired<ScalarEvolution>();
109 AU.addPreserved<ScalarEvolution>();
Benjamin Kramer5c6e9ae2012-10-21 15:03:07 +0000110 AU.addRequired<LoopDependenceAnalysis>();
111 AU.addPreserved<LoopDependenceAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000112 AU.addPreserved<DominatorTree>();
Chris Lattner62c50fd2011-01-02 19:01:03 +0000113 AU.addRequired<DominatorTree>();
Chris Lattnerc19175c2011-02-18 22:22:15 +0000114 AU.addRequired<TargetLibraryInfo>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000115 }
116 };
117}
118
119char LoopIdiomRecognize::ID = 0;
120INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
121 false, false)
122INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chris Lattner62c50fd2011-01-02 19:01:03 +0000123INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000124INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
125INITIALIZE_PASS_DEPENDENCY(LCSSA)
126INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattnerc19175c2011-02-18 22:22:15 +0000127INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Benjamin Kramer5c6e9ae2012-10-21 15:03:07 +0000128INITIALIZE_PASS_DEPENDENCY(LoopDependenceAnalysis)
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000129INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000130INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
131 false, false)
132
133Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
134
Chris Lattner4f81b542011-05-22 17:39:56 +0000135/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattner9f391882010-12-27 00:03:23 +0000136/// and zero out all the operands of this instruction. If any of them become
137/// dead, delete them and the computation tree that feeds them.
138///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000139static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE,
140 const TargetLibraryInfo *TLI) {
Chris Lattner9f391882010-12-27 00:03:23 +0000141 SmallVector<Instruction*, 32> NowDeadInsts;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000142
Chris Lattner9f391882010-12-27 00:03:23 +0000143 NowDeadInsts.push_back(I);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000144
Chris Lattner9f391882010-12-27 00:03:23 +0000145 // Before we touch this instruction, remove it from SE!
146 do {
147 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000148
Chris Lattner9f391882010-12-27 00:03:23 +0000149 // This instruction is dead, zap it, in stages. Start by removing it from
150 // SCEV.
151 SE.forgetValue(DeadInst);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000152
Chris Lattner9f391882010-12-27 00:03:23 +0000153 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
154 Value *Op = DeadInst->getOperand(op);
155 DeadInst->setOperand(op, 0);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000156
Chris Lattner9f391882010-12-27 00:03:23 +0000157 // If this operand just became dead, add it to the NowDeadInsts list.
158 if (!Op->use_empty()) continue;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000159
Chris Lattner9f391882010-12-27 00:03:23 +0000160 if (Instruction *OpI = dyn_cast<Instruction>(Op))
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000161 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattner9f391882010-12-27 00:03:23 +0000162 NowDeadInsts.push_back(OpI);
163 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000164
Chris Lattner9f391882010-12-27 00:03:23 +0000165 DeadInst->eraseFromParent();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000166
Chris Lattner9f391882010-12-27 00:03:23 +0000167 } while (!NowDeadInsts.empty());
168}
169
Chris Lattnere6bb6492010-12-26 19:39:38 +0000170bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000171 CurLoop = L;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000172
Benjamin Kramer28aff842012-09-21 17:27:23 +0000173 // If the loop could not be converted to canonical form, it must have an
174 // indirectbr in it, just give up.
175 if (!L->getLoopPreheader())
176 return false;
177
Nadav Rotema94d6e82012-07-24 10:51:42 +0000178 // Disable loop idiom recognition if the function's name is a common idiom.
Chad Rosier71400b62011-07-15 18:25:04 +0000179 StringRef Name = L->getHeader()->getParent()->getName();
180 if (Name == "memset" || Name == "memcpy")
181 return false;
182
Chris Lattner22920b52010-12-26 20:45:45 +0000183 // The trip count of the loop must be analyzable.
184 SE = &getAnalysis<ScalarEvolution>();
185 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
186 return false;
187 const SCEV *BECount = SE->getBackedgeTakenCount(L);
188 if (isa<SCEVCouldNotCompute>(BECount)) return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000189
Chris Lattner8e08e732011-01-02 20:24:21 +0000190 // If this loop executes exactly one time, then it should be peeled, not
191 // optimized by this pass.
192 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
193 if (BECst->getValue()->getValue() == 0)
194 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000195
Chris Lattner22920b52010-12-26 20:45:45 +0000196 // We require target data for now.
Micah Villmow3574eca2012-10-08 16:38:25 +0000197 TD = getAnalysisIfAvailable<DataLayout>();
Chris Lattner22920b52010-12-26 20:45:45 +0000198 if (TD == 0) return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000199
Chris Lattner62c50fd2011-01-02 19:01:03 +0000200 DT = &getAnalysis<DominatorTree>();
201 LoopInfo &LI = getAnalysis<LoopInfo>();
Chris Lattnerc19175c2011-02-18 22:22:15 +0000202 TLI = &getAnalysis<TargetLibraryInfo>();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000203
Chris Lattner62c50fd2011-01-02 19:01:03 +0000204 SmallVector<BasicBlock*, 8> ExitBlocks;
205 CurLoop->getUniqueExitBlocks(ExitBlocks);
206
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000207 DEBUG(dbgs() << "loop-idiom Scanning: F["
208 << L->getHeader()->getParent()->getName()
209 << "] Loop %" << L->getHeader()->getName() << "\n");
Andrew Trickd99b39e2011-03-14 16:48:10 +0000210
Chris Lattner62c50fd2011-01-02 19:01:03 +0000211 bool MadeChange = false;
212 // Scan all the blocks in the loop that are not in subloops.
213 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
214 ++BI) {
215 // Ignore blocks in subloops.
216 if (LI.getLoopFor(*BI) != CurLoop)
217 continue;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000218
Chris Lattner62c50fd2011-01-02 19:01:03 +0000219 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
220 }
221 return MadeChange;
222}
223
224/// runOnLoopBlock - Process the specified block, which lives in a counted loop
225/// with the specified backedge count. This block is known to be in the current
226/// loop and not in any subloops.
227bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
228 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
229 // We can only promote stores in this block if they are unconditionally
230 // executed in the loop. For a block to be unconditionally executed, it has
231 // to dominate all the exit blocks of the loop. Verify this now.
232 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
233 if (!DT->dominates(BB, ExitBlocks[i]))
234 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000235
Chris Lattner22920b52010-12-26 20:45:45 +0000236 bool MadeChange = false;
237 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000238 Instruction *Inst = I++;
239 // Look for store instructions, which may be optimized to memset/memcpy.
240 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000241 WeakVH InstPtr(I);
242 if (!processLoopStore(SI, BECount)) continue;
243 MadeChange = true;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000244
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000245 // If processing the store invalidated our iterator, start over from the
Chris Lattnere41d3c02011-01-04 07:46:33 +0000246 // top of the block.
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000247 if (InstPtr == 0)
248 I = BB->begin();
249 continue;
250 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000251
Chris Lattnere41d3c02011-01-04 07:46:33 +0000252 // Look for memset instructions, which may be optimized to a larger memset.
253 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
254 WeakVH InstPtr(I);
255 if (!processLoopMemSet(MSI, BECount)) continue;
256 MadeChange = true;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000257
Chris Lattnere41d3c02011-01-04 07:46:33 +0000258 // If processing the memset invalidated our iterator, start over from the
259 // top of the block.
260 if (InstPtr == 0)
261 I = BB->begin();
262 continue;
263 }
Chris Lattner22920b52010-12-26 20:45:45 +0000264 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000265
Chris Lattner22920b52010-12-26 20:45:45 +0000266 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000267}
268
Chris Lattner62c50fd2011-01-02 19:01:03 +0000269
Chris Lattnere41d3c02011-01-04 07:46:33 +0000270/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner22920b52010-12-26 20:45:45 +0000271bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Eli Friedman2bc3d522011-09-12 20:23:13 +0000272 if (!SI->isSimple()) return false;
Chris Lattnere41d3c02011-01-04 07:46:33 +0000273
Chris Lattner22920b52010-12-26 20:45:45 +0000274 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000275 Value *StorePtr = SI->getPointerOperand();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000276
Chris Lattner95ae6762010-12-28 18:53:48 +0000277 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner22920b52010-12-26 20:45:45 +0000278 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000279 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000280 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000281
Chris Lattner22920b52010-12-26 20:45:45 +0000282 // See if the pointer expression is an AddRec like {base,+,1} on the current
283 // loop, which indicates a strided store. If we have something else, it's a
284 // random store we can't handle.
Chris Lattnere2c43922011-01-02 03:37:56 +0000285 const SCEVAddRecExpr *StoreEv =
286 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
287 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner22920b52010-12-26 20:45:45 +0000288 return false;
289
290 // Check to see if the stride matches the size of the store. If so, then we
291 // know that every byte is touched in the loop.
Andrew Trickd99b39e2011-03-14 16:48:10 +0000292 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattnere2c43922011-01-02 03:37:56 +0000293 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trickd99b39e2011-03-14 16:48:10 +0000294
Chris Lattner408b5342011-02-21 02:08:54 +0000295 if (Stride == 0 || StoreSize != Stride->getValue()->getValue()) {
296 // TODO: Could also handle negative stride here someday, that will require
297 // the validity check in mayLoopAccessLocation to be updated though.
298 // Enable this to print exact negative strides.
Chris Lattner0e68cee2011-02-21 17:02:55 +0000299 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattner408b5342011-02-21 02:08:54 +0000300 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
301 dbgs() << "BB: " << *SI->getParent();
302 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000303
Chris Lattner22920b52010-12-26 20:45:45 +0000304 return false;
Chris Lattner408b5342011-02-21 02:08:54 +0000305 }
Chris Lattner3a393722011-02-19 19:31:39 +0000306
307 // See if we can optimize just this store in isolation.
308 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
309 StoredVal, SI, StoreEv, BECount))
310 return true;
Chris Lattnera92ff912010-12-26 23:42:51 +0000311
Chris Lattnere2c43922011-01-02 03:37:56 +0000312 // If the stored value is a strided load in the same loop with the same stride
313 // this this may be transformable into a memcpy. This kicks in for stuff like
314 // for (i) A[i] = B[i];
315 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
316 const SCEVAddRecExpr *LoadEv =
317 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
318 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman2bc3d522011-09-12 20:23:13 +0000319 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattnere2c43922011-01-02 03:37:56 +0000320 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
321 return true;
322 }
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000323 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000324
Chris Lattnere6bb6492010-12-26 19:39:38 +0000325 return false;
326}
327
Chris Lattnere41d3c02011-01-04 07:46:33 +0000328/// processLoopMemSet - See if this memset can be promoted to a large memset.
329bool LoopIdiomRecognize::
330processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
331 // We can only handle non-volatile memsets with a constant size.
332 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
333
Chris Lattnerc19175c2011-02-18 22:22:15 +0000334 // If we're not allowed to hack on memset, we fail.
335 if (!TLI->has(LibFunc::memset))
336 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000337
Chris Lattnere41d3c02011-01-04 07:46:33 +0000338 Value *Pointer = MSI->getDest();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000339
Chris Lattnere41d3c02011-01-04 07:46:33 +0000340 // See if the pointer expression is an AddRec like {base,+,1} on the current
341 // loop, which indicates a strided store. If we have something else, it's a
342 // random store we can't handle.
343 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
344 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
345 return false;
346
347 // Reject memsets that are so large that they overflow an unsigned.
348 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
349 if ((SizeInBytes >> 32) != 0)
350 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000351
Chris Lattnere41d3c02011-01-04 07:46:33 +0000352 // Check to see if the stride matches the size of the memset. If so, then we
353 // know that every byte is touched in the loop.
354 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trickd99b39e2011-03-14 16:48:10 +0000355
Chris Lattnere41d3c02011-01-04 07:46:33 +0000356 // TODO: Could also handle negative stride here someday, that will require the
357 // validity check in mayLoopAccessLocation to be updated though.
358 if (Stride == 0 || MSI->getLength() != Stride->getValue())
359 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000360
Chris Lattner3a393722011-02-19 19:31:39 +0000361 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
362 MSI->getAlignment(), MSI->getValue(),
363 MSI, Ev, BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +0000364}
365
Benjamin Kramer5c6e9ae2012-10-21 15:03:07 +0000366/// hasDependence - Uses the LoopDependenceAnalysis to determine whether 'Inst'
367/// depends on any other value in the Loop 'L'.
368static bool hasDependence(Instruction *Inst, Loop *L,
369 LoopDependenceAnalysis &LDA) {
Chris Lattner30980b62011-01-01 19:39:01 +0000370 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
371 ++BI)
372 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Benjamin Kramer5c6e9ae2012-10-21 15:03:07 +0000373 if (&*I != Inst && I->mayReadOrWriteMemory() &&
374 (I->mayWriteToMemory() || Inst->mayWriteToMemory()) &&
375 LDA.depends(Inst, I))
Chris Lattner30980b62011-01-01 19:39:01 +0000376 return true;
377
378 return false;
379}
380
Chris Lattner3a393722011-02-19 19:31:39 +0000381/// getMemSetPatternValue - If a strided store of the specified value is safe to
382/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
383/// be passed in. Otherwise, return null.
384///
385/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
386/// just replicate their input array and then pass on to memset_pattern16.
Micah Villmow3574eca2012-10-08 16:38:25 +0000387static Constant *getMemSetPatternValue(Value *V, const DataLayout &TD) {
Chris Lattner3a393722011-02-19 19:31:39 +0000388 // If the value isn't a constant, we can't promote it to being in a constant
389 // array. We could theoretically do a store to an alloca or something, but
390 // that doesn't seem worthwhile.
391 Constant *C = dyn_cast<Constant>(V);
392 if (C == 0) return 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000393
Chris Lattner3a393722011-02-19 19:31:39 +0000394 // Only handle simple values that are a power of two bytes in size.
395 uint64_t Size = TD.getTypeSizeInBits(V->getType());
396 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
397 return 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000398
Chris Lattner80e8b502011-02-19 19:56:44 +0000399 // Don't care enough about darwin/ppc to implement this.
400 if (TD.isBigEndian())
401 return 0;
Chris Lattner3a393722011-02-19 19:31:39 +0000402
403 // Convert to size in bytes.
404 Size /= 8;
Chris Lattner3a393722011-02-19 19:31:39 +0000405
Chris Lattner3a393722011-02-19 19:31:39 +0000406 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner80e8b502011-02-19 19:56:44 +0000407 // if the top and bottom are the same (e.g. for vectors and large integers).
Chris Lattner3a393722011-02-19 19:31:39 +0000408 if (Size > 16) return 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000409
Chris Lattner80e8b502011-02-19 19:56:44 +0000410 // If the constant is exactly 16 bytes, just use it.
411 if (Size == 16) return C;
Chris Lattner3a393722011-02-19 19:31:39 +0000412
Chris Lattner80e8b502011-02-19 19:56:44 +0000413 // Otherwise, we'll use an array of the constants.
414 unsigned ArraySize = 16/Size;
415 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
416 return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
Chris Lattner3a393722011-02-19 19:31:39 +0000417}
418
419
420/// processLoopStridedStore - We see a strided store of some value. If we can
421/// transform this into a memset or memset_pattern in the loop preheader, do so.
422bool LoopIdiomRecognize::
423processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
424 unsigned StoreAlignment, Value *StoredVal,
425 Instruction *TheStore, const SCEVAddRecExpr *Ev,
426 const SCEV *BECount) {
Andrew Trickd99b39e2011-03-14 16:48:10 +0000427
Chris Lattner3a393722011-02-19 19:31:39 +0000428 // If the stored value is a byte-wise value (like i32 -1), then it may be
429 // turned into a memset of i8 -1, assuming that all the consecutive bytes
430 // are stored. A store of i32 0x01020304 can never be turned into a memset,
431 // but it can be turned into memset_pattern if the target supports it.
432 Value *SplatValue = isBytewiseValue(StoredVal);
433 Constant *PatternValue = 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000434
Chris Lattner3a393722011-02-19 19:31:39 +0000435 // If we're allowed to form a memset, and the stored value would be acceptable
436 // for memset, use it.
437 if (SplatValue && TLI->has(LibFunc::memset) &&
438 // Verify that the stored value is loop invariant. If not, we can't
439 // promote the memset.
440 CurLoop->isLoopInvariant(SplatValue)) {
441 // Keep and use SplatValue.
442 PatternValue = 0;
443 } else if (TLI->has(LibFunc::memset_pattern16) &&
444 (PatternValue = getMemSetPatternValue(StoredVal, *TD))) {
445 // It looks like we can use PatternValue!
446 SplatValue = 0;
447 } else {
448 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedman5ac7c7d2011-09-13 00:44:16 +0000449 // do anything with a 3-byte store.
Chris Lattnerbafa1172011-01-01 20:12:04 +0000450 return false;
Chris Lattner3a393722011-02-19 19:31:39 +0000451 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000452
Benjamin Kramer5c6e9ae2012-10-21 15:03:07 +0000453 // Make sure the store has no dependencies (i.e. other loads and stores) in
454 // the loop.
455 if (hasDependence(TheStore, CurLoop, getAnalysis<LoopDependenceAnalysis>()))
456 return false;
457
Chris Lattner4f81b542011-05-22 17:39:56 +0000458 // The trip count of the loop and the base pointer of the addrec SCEV is
459 // guaranteed to be loop invariant, which means that it should dominate the
460 // header. This allows us to insert code for it in the preheader.
461 BasicBlock *Preheader = CurLoop->getLoopPreheader();
462 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick5e7645b2011-06-28 05:07:32 +0000463 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Tricka5d950f2011-06-28 05:04:16 +0000464
Chris Lattnera92ff912010-12-26 23:42:51 +0000465 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramer5c6e9ae2012-10-21 15:03:07 +0000466 // this into a memset in the loop preheader now if we want.
Chris Lattnere41d3c02011-01-04 07:46:33 +0000467 unsigned AddrSpace = cast<PointerType>(DestPtr->getType())->getAddressSpace();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000468 Value *BasePtr =
Chris Lattnera92ff912010-12-26 23:42:51 +0000469 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
470 Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000471
Chris Lattner4f81b542011-05-22 17:39:56 +0000472
Chris Lattner4f81b542011-05-22 17:39:56 +0000473 // Okay, everything looks good, insert the memset.
474
Chris Lattnera92ff912010-12-26 23:42:51 +0000475 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
476 // pointer size if it isn't already.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000477 Type *IntPtr = TD->getIntPtrType(DestPtr->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +0000478 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000479
Chris Lattnera92ff912010-12-26 23:42:51 +0000480 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick3228cc22011-03-14 16:50:06 +0000481 SCEV::FlagNUW);
Chris Lattnera92ff912010-12-26 23:42:51 +0000482 if (StoreSize != 1)
483 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick3228cc22011-03-14 16:50:06 +0000484 SCEV::FlagNUW);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000485
486 Value *NumBytes =
Chris Lattnera92ff912010-12-26 23:42:51 +0000487 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000488
Devang Patelcd77a502011-03-07 22:43:45 +0000489 CallInst *NewCall;
Chris Lattner3a393722011-02-19 19:31:39 +0000490 if (SplatValue)
491 NewCall = Builder.CreateMemSet(BasePtr, SplatValue,NumBytes,StoreAlignment);
492 else {
493 Module *M = TheStore->getParent()->getParent()->getParent();
494 Value *MSP = M->getOrInsertFunction("memset_pattern16",
495 Builder.getVoidTy(),
Andrew Trickd99b39e2011-03-14 16:48:10 +0000496 Builder.getInt8PtrTy(),
Chris Lattner3a393722011-02-19 19:31:39 +0000497 Builder.getInt8PtrTy(), IntPtr,
498 (void*)0);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000499
Chris Lattner3a393722011-02-19 19:31:39 +0000500 // Otherwise we should form a memset_pattern16. PatternValue is known to be
501 // an constant array of 16-bytes. Plop the value into a mergable global.
502 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
503 GlobalValue::InternalLinkage,
504 PatternValue, ".memset_pattern");
505 GV->setUnnamedAddr(true); // Ok to merge these.
506 GV->setAlignment(16);
Chris Lattner80e8b502011-02-19 19:56:44 +0000507 Value *PatternPtr = ConstantExpr::getBitCast(GV, Builder.getInt8PtrTy());
Chris Lattner3a393722011-02-19 19:31:39 +0000508 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
509 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000510
Chris Lattnera92ff912010-12-26 23:42:51 +0000511 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattnere41d3c02011-01-04 07:46:33 +0000512 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Patelcd77a502011-03-07 22:43:45 +0000513 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000514
Chris Lattner9f391882010-12-27 00:03:23 +0000515 // Okay, the memset has been formed. Zap the original store and anything that
516 // feeds into it.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000517 deleteDeadInstruction(TheStore, *SE, TLI);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000518 ++NumMemSet;
Chris Lattnera92ff912010-12-26 23:42:51 +0000519 return true;
520}
521
Chris Lattnere2c43922011-01-02 03:37:56 +0000522/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
523/// same-strided load.
524bool LoopIdiomRecognize::
525processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
526 const SCEVAddRecExpr *StoreEv,
527 const SCEVAddRecExpr *LoadEv,
528 const SCEV *BECount) {
Chris Lattnerc19175c2011-02-18 22:22:15 +0000529 // If we're not allowed to form memcpy, we fail.
530 if (!TLI->has(LibFunc::memcpy))
531 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000532
Chris Lattnere2c43922011-01-02 03:37:56 +0000533 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000534
Benjamin Kramer5c6e9ae2012-10-21 15:03:07 +0000535 // Make sure the load and the store have no dependencies (i.e. other loads and
536 // stores) in the loop.
537 // FIXME: If we want to form a memmove SI and LI can be dependent but the
538 // distance must be positive. LDA doesn't provide that info currently.
539 LoopDependenceAnalysis &LDA = getAnalysis<LoopDependenceAnalysis>();
540 if (hasDependence(SI, CurLoop, LDA) || hasDependence(LI, CurLoop, LDA))
541 return false;
542
Chris Lattner4f81b542011-05-22 17:39:56 +0000543 // The trip count of the loop and the base pointer of the addrec SCEV is
544 // guaranteed to be loop invariant, which means that it should dominate the
545 // header. This allows us to insert code for it in the preheader.
546 BasicBlock *Preheader = CurLoop->getLoopPreheader();
547 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick5e7645b2011-06-28 05:07:32 +0000548 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Tricka5d950f2011-06-28 05:04:16 +0000549
Chris Lattnere2c43922011-01-02 03:37:56 +0000550 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Benjamin Kramer5c6e9ae2012-10-21 15:03:07 +0000551 // this into a memcpy in the loop preheader now if we want.
Andrew Trickd99b39e2011-03-14 16:48:10 +0000552 Value *StoreBasePtr =
Chris Lattnere2c43922011-01-02 03:37:56 +0000553 Expander.expandCodeFor(StoreEv->getStart(),
554 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
555 Preheader->getTerminator());
Chris Lattner4f81b542011-05-22 17:39:56 +0000556 Value *LoadBasePtr =
557 Expander.expandCodeFor(LoadEv->getStart(),
558 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
559 Preheader->getTerminator());
560
Chris Lattner4f81b542011-05-22 17:39:56 +0000561 // Okay, everything is safe, we can transform this!
Andrew Tricka5d950f2011-06-28 05:04:16 +0000562
Andrew Trickd99b39e2011-03-14 16:48:10 +0000563
Chris Lattnere2c43922011-01-02 03:37:56 +0000564 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
565 // pointer size if it isn't already.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000566 Type *IntPtr = TD->getIntPtrType(SI->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +0000567 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000568
Chris Lattnere2c43922011-01-02 03:37:56 +0000569 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick3228cc22011-03-14 16:50:06 +0000570 SCEV::FlagNUW);
Chris Lattnere2c43922011-01-02 03:37:56 +0000571 if (StoreSize != 1)
572 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick3228cc22011-03-14 16:50:06 +0000573 SCEV::FlagNUW);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000574
Chris Lattnere2c43922011-01-02 03:37:56 +0000575 Value *NumBytes =
576 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000577
Devang Patelaf358412011-05-04 21:37:05 +0000578 CallInst *NewCall =
Chris Lattnere2c43922011-01-02 03:37:56 +0000579 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
580 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patelaf358412011-05-04 21:37:05 +0000581 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000582
Chris Lattnere2c43922011-01-02 03:37:56 +0000583 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
584 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
585 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Tricka5d950f2011-06-28 05:04:16 +0000586
Andrew Trickd99b39e2011-03-14 16:48:10 +0000587
Chris Lattnere2c43922011-01-02 03:37:56 +0000588 // Okay, the memset has been formed. Zap the original store and anything that
589 // feeds into it.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000590 deleteDeadInstruction(SI, *SE, TLI);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000591 ++NumMemCpy;
Chris Lattnere2c43922011-01-02 03:37:56 +0000592 return true;
593}