blob: 7b42559ddebe819839b758bd70a82dcfc3435210 [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:
Benjamin Kramerd11c5d02012-10-27 14:25:51 +000019// memcmp, strlen, etc.
Chris Lattnerbdce5722011-01-02 18:32:09 +000020// 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 Kramer96c87352012-10-27 14:25:44 +000051#include "llvm/Analysis/DependenceAnalysis.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
Benjamin Kramerd11c5d02012-10-27 14:25:51 +000063STATISTIC(NumMemSet, "Number of memsets formed from loop stores");
64STATISTIC(NumMemCpy, "Number of memcpys formed from loop load+stores");
65STATISTIC(NumMemMove, "Number of memmoves formed from loop load+stores");
Chris Lattnere6bb6492010-12-26 19:39:38 +000066
67namespace {
68 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000069 Loop *CurLoop;
Micah Villmow3574eca2012-10-08 16:38:25 +000070 const DataLayout *TD;
Chris Lattner62c50fd2011-01-02 19:01:03 +000071 DominatorTree *DT;
Chris Lattner22920b52010-12-26 20:45:45 +000072 ScalarEvolution *SE;
Chris Lattnerc19175c2011-02-18 22:22:15 +000073 TargetLibraryInfo *TLI;
Chris Lattnere6bb6492010-12-26 19:39:38 +000074 public:
75 static char ID;
76 explicit LoopIdiomRecognize() : LoopPass(ID) {
77 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
78 }
79
80 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner62c50fd2011-01-02 19:01:03 +000081 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
82 SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattnere6bb6492010-12-26 19:39:38 +000083
Chris Lattner22920b52010-12-26 20:45:45 +000084 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +000085 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
Andrew Trickd99b39e2011-03-14 16:48:10 +000086
Chris Lattner3a393722011-02-19 19:31:39 +000087 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
88 unsigned StoreAlignment,
89 Value *SplatValue, Instruction *TheStore,
90 const SCEVAddRecExpr *Ev,
91 const SCEV *BECount);
Chris Lattnere2c43922011-01-02 03:37:56 +000092 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
93 const SCEVAddRecExpr *StoreEv,
94 const SCEVAddRecExpr *LoadEv,
95 const SCEV *BECount);
Andrew Trickd99b39e2011-03-14 16:48:10 +000096
Chris Lattnere6bb6492010-12-26 19:39:38 +000097 /// This transformation requires natural loop information & requires that
98 /// loop preheaders be inserted into the CFG.
99 ///
100 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.addRequired<LoopInfo>();
102 AU.addPreserved<LoopInfo>();
103 AU.addRequiredID(LoopSimplifyID);
104 AU.addPreservedID(LoopSimplifyID);
105 AU.addRequiredID(LCSSAID);
106 AU.addPreservedID(LCSSAID);
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000107 AU.addRequired<AliasAnalysis>();
108 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000109 AU.addRequired<ScalarEvolution>();
110 AU.addPreserved<ScalarEvolution>();
Benjamin Kramer96c87352012-10-27 14:25:44 +0000111 AU.addRequired<DependenceAnalysis>();
112 AU.addPreserved<DependenceAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000113 AU.addPreserved<DominatorTree>();
Chris Lattner62c50fd2011-01-02 19:01:03 +0000114 AU.addRequired<DominatorTree>();
Chris Lattnerc19175c2011-02-18 22:22:15 +0000115 AU.addRequired<TargetLibraryInfo>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000116 }
117 };
118}
119
120char LoopIdiomRecognize::ID = 0;
121INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
122 false, false)
123INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chris Lattner62c50fd2011-01-02 19:01:03 +0000124INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000125INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
126INITIALIZE_PASS_DEPENDENCY(LCSSA)
127INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattnerc19175c2011-02-18 22:22:15 +0000128INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Benjamin Kramer96c87352012-10-27 14:25:44 +0000129INITIALIZE_PASS_DEPENDENCY(DependenceAnalysis)
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000130INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000131INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
132 false, false)
133
134Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
135
Chris Lattner4f81b542011-05-22 17:39:56 +0000136/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattner9f391882010-12-27 00:03:23 +0000137/// and zero out all the operands of this instruction. If any of them become
138/// dead, delete them and the computation tree that feeds them.
139///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000140static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE,
141 const TargetLibraryInfo *TLI) {
Chris Lattner9f391882010-12-27 00:03:23 +0000142 SmallVector<Instruction*, 32> NowDeadInsts;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000143
Chris Lattner9f391882010-12-27 00:03:23 +0000144 NowDeadInsts.push_back(I);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000145
Chris Lattner9f391882010-12-27 00:03:23 +0000146 // Before we touch this instruction, remove it from SE!
147 do {
148 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000149
Chris Lattner9f391882010-12-27 00:03:23 +0000150 // This instruction is dead, zap it, in stages. Start by removing it from
151 // SCEV.
152 SE.forgetValue(DeadInst);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000153
Chris Lattner9f391882010-12-27 00:03:23 +0000154 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
155 Value *Op = DeadInst->getOperand(op);
156 DeadInst->setOperand(op, 0);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000157
Chris Lattner9f391882010-12-27 00:03:23 +0000158 // If this operand just became dead, add it to the NowDeadInsts list.
159 if (!Op->use_empty()) continue;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000160
Chris Lattner9f391882010-12-27 00:03:23 +0000161 if (Instruction *OpI = dyn_cast<Instruction>(Op))
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000162 if (isInstructionTriviallyDead(OpI, TLI))
Chris Lattner9f391882010-12-27 00:03:23 +0000163 NowDeadInsts.push_back(OpI);
164 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000165
Chris Lattner9f391882010-12-27 00:03:23 +0000166 DeadInst->eraseFromParent();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000167
Chris Lattner9f391882010-12-27 00:03:23 +0000168 } while (!NowDeadInsts.empty());
169}
170
Chris Lattnere6bb6492010-12-26 19:39:38 +0000171bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000172 CurLoop = L;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000173
Benjamin Kramer28aff842012-09-21 17:27:23 +0000174 // If the loop could not be converted to canonical form, it must have an
175 // indirectbr in it, just give up.
176 if (!L->getLoopPreheader())
177 return false;
178
Nadav Rotema94d6e82012-07-24 10:51:42 +0000179 // Disable loop idiom recognition if the function's name is a common idiom.
Chad Rosier71400b62011-07-15 18:25:04 +0000180 StringRef Name = L->getHeader()->getParent()->getName();
Benjamin Kramerbadffcf2012-10-27 15:18:28 +0000181 if (Name == "memset" || Name == "memcpy" || Name == "memmove")
Chad Rosier71400b62011-07-15 18:25:04 +0000182 return false;
183
Chris Lattner22920b52010-12-26 20:45:45 +0000184 // The trip count of the loop must be analyzable.
185 SE = &getAnalysis<ScalarEvolution>();
186 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
187 return false;
188 const SCEV *BECount = SE->getBackedgeTakenCount(L);
189 if (isa<SCEVCouldNotCompute>(BECount)) return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000190
Chris Lattner8e08e732011-01-02 20:24:21 +0000191 // If this loop executes exactly one time, then it should be peeled, not
192 // optimized by this pass.
193 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
194 if (BECst->getValue()->getValue() == 0)
195 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000196
Chris Lattner22920b52010-12-26 20:45:45 +0000197 // We require target data for now.
Micah Villmow3574eca2012-10-08 16:38:25 +0000198 TD = getAnalysisIfAvailable<DataLayout>();
Chris Lattner22920b52010-12-26 20:45:45 +0000199 if (TD == 0) return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000200
Chris Lattner62c50fd2011-01-02 19:01:03 +0000201 DT = &getAnalysis<DominatorTree>();
202 LoopInfo &LI = getAnalysis<LoopInfo>();
Chris Lattnerc19175c2011-02-18 22:22:15 +0000203 TLI = &getAnalysis<TargetLibraryInfo>();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000204
Chris Lattner62c50fd2011-01-02 19:01:03 +0000205 SmallVector<BasicBlock*, 8> ExitBlocks;
206 CurLoop->getUniqueExitBlocks(ExitBlocks);
207
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000208 DEBUG(dbgs() << "loop-idiom Scanning: F["
209 << L->getHeader()->getParent()->getName()
210 << "] Loop %" << L->getHeader()->getName() << "\n");
Andrew Trickd99b39e2011-03-14 16:48:10 +0000211
Chris Lattner62c50fd2011-01-02 19:01:03 +0000212 bool MadeChange = false;
213 // Scan all the blocks in the loop that are not in subloops.
214 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
215 ++BI) {
216 // Ignore blocks in subloops.
217 if (LI.getLoopFor(*BI) != CurLoop)
218 continue;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000219
Chris Lattner62c50fd2011-01-02 19:01:03 +0000220 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
221 }
222 return MadeChange;
223}
224
225/// runOnLoopBlock - Process the specified block, which lives in a counted loop
226/// with the specified backedge count. This block is known to be in the current
227/// loop and not in any subloops.
228bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
229 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
230 // We can only promote stores in this block if they are unconditionally
231 // executed in the loop. For a block to be unconditionally executed, it has
232 // to dominate all the exit blocks of the loop. Verify this now.
233 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
234 if (!DT->dominates(BB, ExitBlocks[i]))
235 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000236
Chris Lattner22920b52010-12-26 20:45:45 +0000237 bool MadeChange = false;
238 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000239 Instruction *Inst = I++;
240 // Look for store instructions, which may be optimized to memset/memcpy.
241 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000242 WeakVH InstPtr(I);
243 if (!processLoopStore(SI, BECount)) continue;
244 MadeChange = true;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000245
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000246 // If processing the store invalidated our iterator, start over from the
Chris Lattnere41d3c02011-01-04 07:46:33 +0000247 // top of the block.
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000248 if (InstPtr == 0)
249 I = BB->begin();
250 continue;
251 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000252
Chris Lattnere41d3c02011-01-04 07:46:33 +0000253 // Look for memset instructions, which may be optimized to a larger memset.
254 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
255 WeakVH InstPtr(I);
256 if (!processLoopMemSet(MSI, BECount)) continue;
257 MadeChange = true;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000258
Chris Lattnere41d3c02011-01-04 07:46:33 +0000259 // If processing the memset invalidated our iterator, start over from the
260 // top of the block.
261 if (InstPtr == 0)
262 I = BB->begin();
263 continue;
264 }
Chris Lattner22920b52010-12-26 20:45:45 +0000265 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000266
Chris Lattner22920b52010-12-26 20:45:45 +0000267 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000268}
269
Chris Lattner62c50fd2011-01-02 19:01:03 +0000270
Chris Lattnere41d3c02011-01-04 07:46:33 +0000271/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner22920b52010-12-26 20:45:45 +0000272bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Eli Friedman2bc3d522011-09-12 20:23:13 +0000273 if (!SI->isSimple()) return false;
Chris Lattnere41d3c02011-01-04 07:46:33 +0000274
Chris Lattner22920b52010-12-26 20:45:45 +0000275 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000276 Value *StorePtr = SI->getPointerOperand();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000277
Chris Lattner95ae6762010-12-28 18:53:48 +0000278 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner22920b52010-12-26 20:45:45 +0000279 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000280 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000281 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000282
Chris Lattner22920b52010-12-26 20:45:45 +0000283 // See if the pointer expression is an AddRec like {base,+,1} on the current
284 // loop, which indicates a strided store. If we have something else, it's a
285 // random store we can't handle.
Chris Lattnere2c43922011-01-02 03:37:56 +0000286 const SCEVAddRecExpr *StoreEv =
287 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
288 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner22920b52010-12-26 20:45:45 +0000289 return false;
290
291 // Check to see if the stride matches the size of the store. If so, then we
292 // know that every byte is touched in the loop.
Andrew Trickd99b39e2011-03-14 16:48:10 +0000293 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattnere2c43922011-01-02 03:37:56 +0000294 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trickd99b39e2011-03-14 16:48:10 +0000295
Chris Lattner408b5342011-02-21 02:08:54 +0000296 if (Stride == 0 || StoreSize != Stride->getValue()->getValue()) {
297 // TODO: Could also handle negative stride here someday, that will require
298 // the validity check in mayLoopAccessLocation to be updated though.
299 // Enable this to print exact negative strides.
Chris Lattner0e68cee2011-02-21 17:02:55 +0000300 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattner408b5342011-02-21 02:08:54 +0000301 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
302 dbgs() << "BB: " << *SI->getParent();
303 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000304
Chris Lattner22920b52010-12-26 20:45:45 +0000305 return false;
Chris Lattner408b5342011-02-21 02:08:54 +0000306 }
Chris Lattner3a393722011-02-19 19:31:39 +0000307
308 // See if we can optimize just this store in isolation.
309 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
310 StoredVal, SI, StoreEv, BECount))
311 return true;
Chris Lattnera92ff912010-12-26 23:42:51 +0000312
Chris Lattnere2c43922011-01-02 03:37:56 +0000313 // If the stored value is a strided load in the same loop with the same stride
314 // this this may be transformable into a memcpy. This kicks in for stuff like
315 // for (i) A[i] = B[i];
316 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
317 const SCEVAddRecExpr *LoadEv =
318 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
319 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman2bc3d522011-09-12 20:23:13 +0000320 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattnere2c43922011-01-02 03:37:56 +0000321 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
322 return true;
323 }
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000324 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000325
Chris Lattnere6bb6492010-12-26 19:39:38 +0000326 return false;
327}
328
Chris Lattnere41d3c02011-01-04 07:46:33 +0000329/// processLoopMemSet - See if this memset can be promoted to a large memset.
330bool LoopIdiomRecognize::
331processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
332 // We can only handle non-volatile memsets with a constant size.
333 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
334
Chris Lattnerc19175c2011-02-18 22:22:15 +0000335 // If we're not allowed to hack on memset, we fail.
336 if (!TLI->has(LibFunc::memset))
337 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000338
Chris Lattnere41d3c02011-01-04 07:46:33 +0000339 Value *Pointer = MSI->getDest();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000340
Chris Lattnere41d3c02011-01-04 07:46:33 +0000341 // See if the pointer expression is an AddRec like {base,+,1} on the current
342 // loop, which indicates a strided store. If we have something else, it's a
343 // random store we can't handle.
344 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
345 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
346 return false;
347
348 // Reject memsets that are so large that they overflow an unsigned.
349 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
350 if ((SizeInBytes >> 32) != 0)
351 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000352
Chris Lattnere41d3c02011-01-04 07:46:33 +0000353 // Check to see if the stride matches the size of the memset. If so, then we
354 // know that every byte is touched in the loop.
355 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trickd99b39e2011-03-14 16:48:10 +0000356
Chris Lattnere41d3c02011-01-04 07:46:33 +0000357 // TODO: Could also handle negative stride here someday, that will require the
358 // validity check in mayLoopAccessLocation to be updated though.
359 if (Stride == 0 || MSI->getLength() != Stride->getValue())
360 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000361
Chris Lattner3a393722011-02-19 19:31:39 +0000362 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
363 MSI->getAlignment(), MSI->getValue(),
364 MSI, Ev, BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +0000365}
366
Chris Lattner3a393722011-02-19 19:31:39 +0000367/// getMemSetPatternValue - If a strided store of the specified value is safe to
368/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
369/// be passed in. Otherwise, return null.
370///
371/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
372/// just replicate their input array and then pass on to memset_pattern16.
Micah Villmow3574eca2012-10-08 16:38:25 +0000373static Constant *getMemSetPatternValue(Value *V, const DataLayout &TD) {
Chris Lattner3a393722011-02-19 19:31:39 +0000374 // If the value isn't a constant, we can't promote it to being in a constant
375 // array. We could theoretically do a store to an alloca or something, but
376 // that doesn't seem worthwhile.
377 Constant *C = dyn_cast<Constant>(V);
378 if (C == 0) return 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000379
Chris Lattner3a393722011-02-19 19:31:39 +0000380 // Only handle simple values that are a power of two bytes in size.
381 uint64_t Size = TD.getTypeSizeInBits(V->getType());
382 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
383 return 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000384
Chris Lattner80e8b502011-02-19 19:56:44 +0000385 // Don't care enough about darwin/ppc to implement this.
386 if (TD.isBigEndian())
387 return 0;
Chris Lattner3a393722011-02-19 19:31:39 +0000388
389 // Convert to size in bytes.
390 Size /= 8;
Chris Lattner3a393722011-02-19 19:31:39 +0000391
Chris Lattner3a393722011-02-19 19:31:39 +0000392 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner80e8b502011-02-19 19:56:44 +0000393 // if the top and bottom are the same (e.g. for vectors and large integers).
Chris Lattner3a393722011-02-19 19:31:39 +0000394 if (Size > 16) return 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000395
Chris Lattner80e8b502011-02-19 19:56:44 +0000396 // If the constant is exactly 16 bytes, just use it.
397 if (Size == 16) return C;
Chris Lattner3a393722011-02-19 19:31:39 +0000398
Chris Lattner80e8b502011-02-19 19:56:44 +0000399 // Otherwise, we'll use an array of the constants.
400 unsigned ArraySize = 16/Size;
401 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
402 return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
Chris Lattner3a393722011-02-19 19:31:39 +0000403}
404
405
406/// processLoopStridedStore - We see a strided store of some value. If we can
407/// transform this into a memset or memset_pattern in the loop preheader, do so.
408bool LoopIdiomRecognize::
409processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
410 unsigned StoreAlignment, Value *StoredVal,
411 Instruction *TheStore, const SCEVAddRecExpr *Ev,
412 const SCEV *BECount) {
Andrew Trickd99b39e2011-03-14 16:48:10 +0000413
Chris Lattner3a393722011-02-19 19:31:39 +0000414 // If the stored value is a byte-wise value (like i32 -1), then it may be
415 // turned into a memset of i8 -1, assuming that all the consecutive bytes
416 // are stored. A store of i32 0x01020304 can never be turned into a memset,
417 // but it can be turned into memset_pattern if the target supports it.
418 Value *SplatValue = isBytewiseValue(StoredVal);
419 Constant *PatternValue = 0;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000420
Chris Lattner3a393722011-02-19 19:31:39 +0000421 // If we're allowed to form a memset, and the stored value would be acceptable
422 // for memset, use it.
423 if (SplatValue && TLI->has(LibFunc::memset) &&
424 // Verify that the stored value is loop invariant. If not, we can't
425 // promote the memset.
426 CurLoop->isLoopInvariant(SplatValue)) {
427 // Keep and use SplatValue.
428 PatternValue = 0;
429 } else if (TLI->has(LibFunc::memset_pattern16) &&
430 (PatternValue = getMemSetPatternValue(StoredVal, *TD))) {
431 // It looks like we can use PatternValue!
432 SplatValue = 0;
433 } else {
434 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedman5ac7c7d2011-09-13 00:44:16 +0000435 // do anything with a 3-byte store.
Chris Lattnerbafa1172011-01-01 20:12:04 +0000436 return false;
Chris Lattner3a393722011-02-19 19:31:39 +0000437 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000438
Benjamin Kramer96c87352012-10-27 14:25:44 +0000439 // Make sure the store has no dependencies (i.e. other loads and stores) in
440 // the loop.
441 DependenceAnalysis &DA = getAnalysis<DependenceAnalysis>();
442 for (Loop::block_iterator BI = CurLoop->block_begin(),
443 BE = CurLoop->block_end(); BI != BE; ++BI)
444 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
445 if (&*I != TheStore && I->mayReadOrWriteMemory()) {
446 OwningPtr<Dependence> D(DA.depends(TheStore, I, true));
447 if (D)
448 return false;
449 }
450
Chris Lattner4f81b542011-05-22 17:39:56 +0000451 // The trip count of the loop and the base pointer of the addrec SCEV is
452 // guaranteed to be loop invariant, which means that it should dominate the
453 // header. This allows us to insert code for it in the preheader.
454 BasicBlock *Preheader = CurLoop->getLoopPreheader();
455 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick5e7645b2011-06-28 05:07:32 +0000456 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Tricka5d950f2011-06-28 05:04:16 +0000457
Chris Lattnera92ff912010-12-26 23:42:51 +0000458 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramer3740e792012-10-21 19:31:16 +0000459 // this into a memset in the loop preheader now if we want. However, this
460 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000461 // or write to the aliased location. Check for any overlap by generating the
462 // base pointer and checking the region.
463 unsigned AddrSpace = cast<PointerType>(DestPtr->getType())->getAddressSpace();
Andrew Trickd99b39e2011-03-14 16:48:10 +0000464 Value *BasePtr =
Chris Lattnera92ff912010-12-26 23:42:51 +0000465 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
466 Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000467
Chris Lattner4f81b542011-05-22 17:39:56 +0000468
Chris Lattner4f81b542011-05-22 17:39:56 +0000469 // Okay, everything looks good, insert the memset.
470
Chris Lattnera92ff912010-12-26 23:42:51 +0000471 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
472 // pointer size if it isn't already.
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000473 Type *IntPtr = TD->getIntPtrType(DestPtr->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +0000474 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000475
Chris Lattnera92ff912010-12-26 23:42:51 +0000476 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick3228cc22011-03-14 16:50:06 +0000477 SCEV::FlagNUW);
Chris Lattnera92ff912010-12-26 23:42:51 +0000478 if (StoreSize != 1)
479 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick3228cc22011-03-14 16:50:06 +0000480 SCEV::FlagNUW);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000481
482 Value *NumBytes =
Chris Lattnera92ff912010-12-26 23:42:51 +0000483 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000484
Devang Patelcd77a502011-03-07 22:43:45 +0000485 CallInst *NewCall;
Chris Lattner3a393722011-02-19 19:31:39 +0000486 if (SplatValue)
487 NewCall = Builder.CreateMemSet(BasePtr, SplatValue,NumBytes,StoreAlignment);
488 else {
489 Module *M = TheStore->getParent()->getParent()->getParent();
490 Value *MSP = M->getOrInsertFunction("memset_pattern16",
491 Builder.getVoidTy(),
Andrew Trickd99b39e2011-03-14 16:48:10 +0000492 Builder.getInt8PtrTy(),
Chris Lattner3a393722011-02-19 19:31:39 +0000493 Builder.getInt8PtrTy(), IntPtr,
494 (void*)0);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000495
Chris Lattner3a393722011-02-19 19:31:39 +0000496 // Otherwise we should form a memset_pattern16. PatternValue is known to be
497 // an constant array of 16-bytes. Plop the value into a mergable global.
498 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
499 GlobalValue::InternalLinkage,
500 PatternValue, ".memset_pattern");
501 GV->setUnnamedAddr(true); // Ok to merge these.
502 GV->setAlignment(16);
Chris Lattner80e8b502011-02-19 19:56:44 +0000503 Value *PatternPtr = ConstantExpr::getBitCast(GV, Builder.getInt8PtrTy());
Chris Lattner3a393722011-02-19 19:31:39 +0000504 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
505 }
Andrew Trickd99b39e2011-03-14 16:48:10 +0000506
Chris Lattnera92ff912010-12-26 23:42:51 +0000507 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattnere41d3c02011-01-04 07:46:33 +0000508 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Patelcd77a502011-03-07 22:43:45 +0000509 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000510
Chris Lattner9f391882010-12-27 00:03:23 +0000511 // Okay, the memset has been formed. Zap the original store and anything that
512 // feeds into it.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000513 deleteDeadInstruction(TheStore, *SE, TLI);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000514 ++NumMemSet;
Chris Lattnera92ff912010-12-26 23:42:51 +0000515 return true;
516}
517
Chris Lattnere2c43922011-01-02 03:37:56 +0000518/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
519/// same-strided load.
520bool LoopIdiomRecognize::
521processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
522 const SCEVAddRecExpr *StoreEv,
523 const SCEVAddRecExpr *LoadEv,
524 const SCEV *BECount) {
Chris Lattnerc19175c2011-02-18 22:22:15 +0000525 // If we're not allowed to form memcpy, we fail.
Benjamin Kramerbadffcf2012-10-27 15:18:28 +0000526 if (!TLI->has(LibFunc::memcpy) || !TLI->has(LibFunc::memmove))
Chris Lattnerc19175c2011-02-18 22:22:15 +0000527 return false;
Andrew Trickd99b39e2011-03-14 16:48:10 +0000528
Chris Lattnere2c43922011-01-02 03:37:56 +0000529 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000530
Benjamin Kramer96c87352012-10-27 14:25:44 +0000531 // Make sure the load and the store have no dependencies (i.e. other loads and
532 // stores) in the loop. We ignore the direct dependency between SI and LI here
533 // and check it later.
534 DependenceAnalysis &DA = getAnalysis<DependenceAnalysis>();
Benjamin Kramerd11c5d02012-10-27 14:25:51 +0000535 bool isMemcpySafe = true;
Benjamin Kramer96c87352012-10-27 14:25:44 +0000536 for (Loop::block_iterator BI = CurLoop->block_begin(),
537 BE = CurLoop->block_end(); BI != BE; ++BI)
538 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
539 if (&*I != SI && &*I != LI && I->mayReadOrWriteMemory()) {
540 // First, check if there is a dependence of the store.
541 OwningPtr<Dependence> DS(DA.depends(SI, I, true));
542 if (DS)
543 return false;
544 // If the scanned instructon may modify memory then we also have to
545 // check for dependencys on the load.
546 if (I->mayWriteToMemory()) {
547 OwningPtr<Dependence> DL(DA.depends(I, LI, true));
548 if (DL)
549 return false;
550 }
551 }
552
553 // Now check the dependency between SI and LI. If there is no dependency we
554 // can safely emit a memcpy.
555 OwningPtr<Dependence> Dep(DA.depends(SI, LI, true));
Benjamin Kramerd11c5d02012-10-27 14:25:51 +0000556 if (Dep) {
Benjamin Kramer415f8692012-10-30 19:49:39 +0000557 // If there is a dependence but the direction is positive (or none) we can
558 // still safely turn this into memmove.
559 unsigned Direction = Dep->getDirection(Dep->getLevels());
560 if (Direction != Dependence::DVEntry::NONE &&
561 Direction != Dependence::DVEntry::GT)
Benjamin Kramerd11c5d02012-10-27 14:25:51 +0000562 return false;
563 isMemcpySafe = false;
564 }
Benjamin Kramer96c87352012-10-27 14:25:44 +0000565
Chris Lattner4f81b542011-05-22 17:39:56 +0000566 // The trip count of the loop and the base pointer of the addrec SCEV is
567 // guaranteed to be loop invariant, which means that it should dominate the
568 // header. This allows us to insert code for it in the preheader.
569 BasicBlock *Preheader = CurLoop->getLoopPreheader();
570 IRBuilder<> Builder(Preheader->getTerminator());
Andrew Trick5e7645b2011-06-28 05:07:32 +0000571 SCEVExpander Expander(*SE, "loop-idiom");
Andrew Tricka5d950f2011-06-28 05:04:16 +0000572
Chris Lattnere2c43922011-01-02 03:37:56 +0000573 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Benjamin Kramer96c87352012-10-27 14:25:44 +0000574 // this into a memcpy in the loop preheader now if we want.
Andrew Trickd99b39e2011-03-14 16:48:10 +0000575 Value *StoreBasePtr =
Chris Lattnere2c43922011-01-02 03:37:56 +0000576 Expander.expandCodeFor(StoreEv->getStart(),
577 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
578 Preheader->getTerminator());
Chris Lattner4f81b542011-05-22 17:39:56 +0000579 Value *LoadBasePtr =
580 Expander.expandCodeFor(LoadEv->getStart(),
581 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
582 Preheader->getTerminator());
583
Chris Lattner4f81b542011-05-22 17:39:56 +0000584 // Okay, everything is safe, we can transform this!
Andrew Tricka5d950f2011-06-28 05:04:16 +0000585
Andrew Trickd99b39e2011-03-14 16:48:10 +0000586
Chris Lattnere2c43922011-01-02 03:37:56 +0000587 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
588 // pointer size if it isn't already.
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000589 Type *IntPtr = TD->getIntPtrType(SI->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +0000590 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000591
Chris Lattnere2c43922011-01-02 03:37:56 +0000592 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Andrew Trick3228cc22011-03-14 16:50:06 +0000593 SCEV::FlagNUW);
Chris Lattnere2c43922011-01-02 03:37:56 +0000594 if (StoreSize != 1)
595 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick3228cc22011-03-14 16:50:06 +0000596 SCEV::FlagNUW);
Andrew Trickd99b39e2011-03-14 16:48:10 +0000597
Chris Lattnere2c43922011-01-02 03:37:56 +0000598 Value *NumBytes =
599 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000600
Benjamin Kramerd11c5d02012-10-27 14:25:51 +0000601 CallInst *NewCall;
602 unsigned Align = std::min(SI->getAlignment(), LI->getAlignment());
603 if (isMemcpySafe) {
604 NewCall = Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, Align);
605 ++NumMemCpy;
606 } else {
607 NewCall = Builder.CreateMemMove(StoreBasePtr, LoadBasePtr, NumBytes, Align);
608 ++NumMemMove;
609 }
Devang Patelaf358412011-05-04 21:37:05 +0000610 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trickd99b39e2011-03-14 16:48:10 +0000611
Benjamin Kramerd11c5d02012-10-27 14:25:51 +0000612 DEBUG(dbgs() << " Formed " << (isMemcpySafe ? "memcpy: " : "memmove: ")
613 << *NewCall << "\n"
Chris Lattnere2c43922011-01-02 03:37:56 +0000614 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
615 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Tricka5d950f2011-06-28 05:04:16 +0000616
Andrew Trickd99b39e2011-03-14 16:48:10 +0000617
Chris Lattnere2c43922011-01-02 03:37:56 +0000618 // Okay, the memset has been formed. Zap the original store and anything that
619 // feeds into it.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000620 deleteDeadInstruction(SI, *SE, TLI);
Chris Lattnere2c43922011-01-02 03:37:56 +0000621 return true;
622}