blob: b2cc66852d5db1a1e3de7609b6c8b230f9954eac [file] [log] [blame]
Chris Lattner81ae3f22010-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 Lattner0469e012011-01-02 18:32:09 +000015//
16// TODO List:
17//
18// Future loop memory idioms to recognize:
Chandler Carruth099f5cb02012-11-02 08:33:25 +000019// memcmp, memmove, strlen, etc.
Chris Lattner0469e012011-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 Lattner8fac5db2011-01-02 23:19:45 +000033//
Chris Lattner02a97762011-01-03 01:10:08 +000034// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000035// replace them with calls to BLAS (if linked in??).
36//
Chris Lattner0469e012011-01-02 18:32:09 +000037//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000038
Chris Lattner81ae3f22010-12-26 19:39:38 +000039#include "llvm/Transforms/Scalar.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000040#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000041#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000042#include "llvm/Analysis/BasicAliasAnalysis.h"
43#include "llvm/Analysis/GlobalsModRef.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000044#include "llvm/Analysis/LoopPass.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000045#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chad Rosiera15b4b62015-11-23 21:09:13 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000048#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000049#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000050#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000052#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/IRBuilder.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000056#include "llvm/Support/Debug.h"
57#include "llvm/Support/raw_ostream.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000058#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000059using namespace llvm;
60
Chandler Carruth964daaa2014-04-22 02:55:47 +000061#define DEBUG_TYPE "loop-idiom"
62
Chandler Carruth099f5cb02012-11-02 08:33:25 +000063STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
64STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +000065
66namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000067
Chandler Carruthbad690e2015-08-12 23:06:37 +000068class LoopIdiomRecognize : public LoopPass {
69 Loop *CurLoop;
Chandler Carruthbf143e22015-08-14 00:21:10 +000070 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +000071 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +000072 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +000073 ScalarEvolution *SE;
74 TargetLibraryInfo *TLI;
75 const TargetTransformInfo *TTI;
Chad Rosier43f9b482015-11-06 16:33:57 +000076 const DataLayout *DL;
Chris Lattner81ae3f22010-12-26 19:39:38 +000077
Chandler Carruthbad690e2015-08-12 23:06:37 +000078public:
79 static char ID;
80 explicit LoopIdiomRecognize() : LoopPass(ID) {
81 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
Chandler Carruthbad690e2015-08-12 23:06:37 +000082 }
Chris Lattner81ae3f22010-12-26 19:39:38 +000083
Chandler Carruthbad690e2015-08-12 23:06:37 +000084 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Shuxin Yang95de7c32012-12-09 03:12:46 +000085
Chandler Carruthbad690e2015-08-12 23:06:37 +000086 /// This transformation requires natural loop information & requires that
87 /// loop preheaders be inserted into the CFG.
88 ///
89 void getAnalysisUsage(AnalysisUsage &AU) const override {
90 AU.addRequired<LoopInfoWrapperPass>();
91 AU.addPreserved<LoopInfoWrapperPass>();
92 AU.addRequiredID(LoopSimplifyID);
93 AU.addPreservedID(LoopSimplifyID);
94 AU.addRequiredID(LCSSAID);
95 AU.addPreservedID(LCSSAID);
Chandler Carruth7b560d42015-09-09 17:55:00 +000096 AU.addRequired<AAResultsWrapperPass>();
97 AU.addPreserved<AAResultsWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000098 AU.addRequired<ScalarEvolutionWrapperPass>();
99 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000100 AU.addPreserved<SCEVAAWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000101 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000102 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000103 AU.addRequired<TargetLibraryInfoWrapperPass>();
104 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000105 AU.addPreserved<BasicAAWrapperPass>();
106 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000107 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000108
Chandler Carruthbad690e2015-08-12 23:06:37 +0000109private:
Chad Rosiercc9030b2015-11-11 23:00:59 +0000110 typedef SmallVector<StoreInst *, 8> StoreList;
111 StoreList StoreRefs;
112
Chandler Carruthd9c60702015-08-13 00:10:03 +0000113 /// \name Countable Loop Idiom Handling
114 /// @{
115
Chandler Carruthbad690e2015-08-12 23:06:37 +0000116 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000117 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
118 SmallVectorImpl<BasicBlock *> &ExitBlocks);
119
Chad Rosiercc9030b2015-11-11 23:00:59 +0000120 void collectStores(BasicBlock *BB);
Chad Rosiera548fe52015-11-12 19:09:16 +0000121 bool isLegalStore(StoreInst *SI);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000122 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
123 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
124
125 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
126 unsigned StoreAlignment, Value *SplatValue,
127 Instruction *TheStore, const SCEVAddRecExpr *Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000128 const SCEV *BECount, bool NegStride);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000129 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
130 const SCEVAddRecExpr *StoreEv,
Chad Rosiercc299b62015-11-13 21:51:02 +0000131 const SCEV *BECount, bool NegStride);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000132
133 /// @}
134 /// \name Noncountable Loop Idiom Handling
135 /// @{
136
137 bool runOnNoncountableLoop();
138
Chandler Carruth8219a502015-08-13 00:44:29 +0000139 bool recognizePopcount();
140 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
141 PHINode *CntPhi, Value *Var);
142
Chandler Carruthd9c60702015-08-13 00:10:03 +0000143 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000144};
145
146} // End anonymous namespace.
Chris Lattner81ae3f22010-12-26 19:39:38 +0000147
148char LoopIdiomRecognize::ID = 0;
149INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
150 false, false)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000151INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000152INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000153INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
154INITIALIZE_PASS_DEPENDENCY(LCSSA)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000155INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000156INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000157INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
158INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
159INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
160INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000161INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000162INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
163 false, false)
164
165Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
166
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000167/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000168/// and zero out all the operands of this instruction. If any of them become
169/// dead, delete them and the computation tree that feeds them.
170///
Benjamin Kramerf094d772015-02-07 21:37:08 +0000171static void deleteDeadInstruction(Instruction *I,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000172 const TargetLibraryInfo *TLI) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000173 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
174 I->replaceAllUsesWith(UndefValue::get(I->getType()));
175 I->eraseFromParent();
176 for (Value *Op : Operands)
177 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000178}
179
Shuxin Yang95de7c32012-12-09 03:12:46 +0000180//===----------------------------------------------------------------------===//
181//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000182// Implementation of LoopIdiomRecognize
183//
184//===----------------------------------------------------------------------===//
185
Chandler Carruthd9c60702015-08-13 00:10:03 +0000186bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
187 if (skipOptnoneFunction(L))
188 return false;
189
190 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000191 // If the loop could not be converted to canonical form, it must have an
192 // indirectbr in it, just give up.
193 if (!L->getLoopPreheader())
194 return false;
195
196 // Disable loop idiom recognition if the function's name is a common idiom.
197 StringRef Name = L->getHeader()->getParent()->getName();
198 if (Name == "memset" || Name == "memcpy")
199 return false;
200
Chandler Carruth7b560d42015-09-09 17:55:00 +0000201 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruthdc298322015-08-13 01:03:26 +0000202 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth18c26692015-08-13 09:27:01 +0000203 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000204 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthdc298322015-08-13 01:03:26 +0000205 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
206 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
207 *CurLoop->getHeader()->getParent());
Chad Rosier43f9b482015-11-06 16:33:57 +0000208 DL = &CurLoop->getHeader()->getModule()->getDataLayout();
Chandler Carruthdc298322015-08-13 01:03:26 +0000209
Chandler Carruthd9c60702015-08-13 00:10:03 +0000210 if (SE->hasLoopInvariantBackedgeTakenCount(L))
211 return runOnCountableLoop();
Chandler Carruthdc298322015-08-13 01:03:26 +0000212
Chandler Carruthd9c60702015-08-13 00:10:03 +0000213 return runOnNoncountableLoop();
214}
215
Shuxin Yang95de7c32012-12-09 03:12:46 +0000216bool LoopIdiomRecognize::runOnCountableLoop() {
217 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000218 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000219 "runOnCountableLoop() called on a loop without a predictable"
220 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000221
222 // If this loop executes exactly one time, then it should be peeled, not
223 // optimized by this pass.
224 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
225 if (BECst->getValue()->getValue() == 0)
226 return false;
227
Chandler Carruthbad690e2015-08-12 23:06:37 +0000228 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000229 CurLoop->getUniqueExitBlocks(ExitBlocks);
230
231 DEBUG(dbgs() << "loop-idiom Scanning: F["
Chandler Carruthbad690e2015-08-12 23:06:37 +0000232 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
233 << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000234
235 bool MadeChange = false;
236 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000237 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000238 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000239 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000240 continue;
241
Davide Italiano80625af2015-05-13 19:51:21 +0000242 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000243 }
244 return MadeChange;
245}
246
Chad Rosiera548fe52015-11-12 19:09:16 +0000247static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
248 uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
249 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
250 "Don't overflow unsigned.");
251 return (unsigned)SizeInBits >> 3;
252}
253
254static unsigned getStoreStride(const SCEVAddRecExpr *StoreEv) {
255 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
256 return ConstStride->getValue()->getValue().getZExtValue();
257}
258
259bool LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
Chad Rosier869962f2015-12-01 14:26:35 +0000260 // Don't touch volatile stores.
261 if (!SI->isSimple())
262 return false;
263
Chad Rosiera548fe52015-11-12 19:09:16 +0000264 Value *StoredVal = SI->getValueOperand();
265 Value *StorePtr = SI->getPointerOperand();
266
267 // Reject stores that are so large that they overflow an unsigned.
268 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
269 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
270 return false;
271
272 // See if the pointer expression is an AddRec like {base,+,1} on the current
273 // loop, which indicates a strided store. If we have something else, it's a
274 // random store we can't handle.
275 const SCEVAddRecExpr *StoreEv =
276 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
277 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
278 return false;
279
280 // Check to see if we have a constant stride.
281 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
282 return false;
283
284 return true;
285}
286
Chad Rosiercc9030b2015-11-11 23:00:59 +0000287void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
288 StoreRefs.clear();
289 for (Instruction &I : *BB) {
290 StoreInst *SI = dyn_cast<StoreInst>(&I);
291 if (!SI)
292 continue;
293
Chad Rosiera548fe52015-11-12 19:09:16 +0000294 // Make sure this is a strided store with a constant stride.
295 if (!isLegalStore(SI))
296 continue;
297
Chad Rosiercc9030b2015-11-11 23:00:59 +0000298 // Save the store locations.
299 StoreRefs.push_back(SI);
300 }
301}
302
Chris Lattner8455b6e2011-01-02 19:01:03 +0000303/// runOnLoopBlock - Process the specified block, which lives in a counted loop
304/// with the specified backedge count. This block is known to be in the current
305/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000306bool LoopIdiomRecognize::runOnLoopBlock(
307 BasicBlock *BB, const SCEV *BECount,
308 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000309 // We can only promote stores in this block if they are unconditionally
310 // executed in the loop. For a block to be unconditionally executed, it has
311 // to dominate all the exit blocks of the loop. Verify this now.
312 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
313 if (!DT->dominates(BB, ExitBlocks[i]))
314 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000315
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000316 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000317 // Look for store instructions, which may be optimized to memset/memcpy.
318 collectStores(BB);
319 for (auto &SI : StoreRefs)
320 MadeChange |= processLoopStore(SI, BECount);
321
Chandler Carruthbad690e2015-08-12 23:06:37 +0000322 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000323 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000324 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000325 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000326 WeakVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000327 if (!processLoopMemSet(MSI, BECount))
328 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000329 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000330
Chris Lattner86438102011-01-04 07:46:33 +0000331 // If processing the memset invalidated our iterator, start over from the
332 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000333 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000334 I = BB->begin();
335 continue;
336 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000337 }
Andrew Trick328b2232011-03-14 16:48:10 +0000338
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000339 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000340}
341
Chris Lattner86438102011-01-04 07:46:33 +0000342/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000343bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Chad Rosiercc9030b2015-11-11 23:00:59 +0000344 assert(SI->isSimple() && "Expected only non-volatile stores.");
Chris Lattner86438102011-01-04 07:46:33 +0000345
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000346 Value *StoredVal = SI->getValueOperand();
Chris Lattner29e14ed2010-12-26 23:42:51 +0000347 Value *StorePtr = SI->getPointerOperand();
Andrew Trick328b2232011-03-14 16:48:10 +0000348
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000349 // Check to see if the stride matches the size of the store. If so, then we
350 // know that every byte is touched in the loop.
Chad Rosiera548fe52015-11-12 19:09:16 +0000351 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
352 unsigned Stride = getStoreStride(StoreEv);
353 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
Chad Rosier79676142015-10-28 14:38:49 +0000354 if (StoreSize != Stride && StoreSize != -Stride)
355 return false;
356
357 bool NegStride = StoreSize == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000358
359 // See if we can optimize just this store in isolation.
360 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
Chad Rosier79676142015-10-28 14:38:49 +0000361 StoredVal, SI, StoreEv, BECount, NegStride))
Chris Lattner0f4a6402011-02-19 19:31:39 +0000362 return true;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000363
Chad Rosier1cd3da12015-11-19 21:33:07 +0000364 // Optimize the store into a memcpy, if it feeds an similarly strided load.
Chad Rosierfddc01f2015-11-19 18:22:21 +0000365 return processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, BECount, NegStride);
Chris Lattner81ae3f22010-12-26 19:39:38 +0000366}
367
Chris Lattner86438102011-01-04 07:46:33 +0000368/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000369bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
370 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000371 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000372 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
373 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000374
Chris Lattnere6b261f2011-02-18 22:22:15 +0000375 // If we're not allowed to hack on memset, we fail.
376 if (!TLI->has(LibFunc::memset))
377 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000378
Chris Lattner86438102011-01-04 07:46:33 +0000379 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000380
Chris Lattner86438102011-01-04 07:46:33 +0000381 // See if the pointer expression is an AddRec like {base,+,1} on the current
382 // loop, which indicates a strided store. If we have something else, it's a
383 // random store we can't handle.
384 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000385 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000386 return false;
387
388 // Reject memsets that are so large that they overflow an unsigned.
389 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
390 if ((SizeInBytes >> 32) != 0)
391 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000392
Chris Lattner86438102011-01-04 07:46:33 +0000393 // Check to see if the stride matches the size of the memset. If so, then we
394 // know that every byte is touched in the loop.
395 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000396
Chris Lattner86438102011-01-04 07:46:33 +0000397 // TODO: Could also handle negative stride here someday, that will require the
398 // validity check in mayLoopAccessLocation to be updated though.
Craig Topperf40110f2014-04-25 05:29:35 +0000399 if (!Stride || MSI->getLength() != Stride->getValue())
Chris Lattner86438102011-01-04 07:46:33 +0000400 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000401
Chris Lattner0f4a6402011-02-19 19:31:39 +0000402 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000403 MSI->getAlignment(), MSI->getValue(), MSI, Ev,
404 BECount, /*NegStride=*/false);
Chris Lattner86438102011-01-04 07:46:33 +0000405}
406
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000407/// mayLoopAccessLocation - Return true if the specified loop might access the
408/// specified pointer location, which is a loop-strided access. The 'Access'
409/// argument specifies what the verboten forms of access are (read or write).
Chandler Carruth194f59c2015-07-22 23:15:57 +0000410static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
411 const SCEV *BECount, unsigned StoreSize,
412 AliasAnalysis &AA,
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000413 Instruction *IgnoredStore) {
414 // Get the location that may be stored across the loop. Since the access is
415 // strided positively through memory, we say that the modified location starts
416 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000417 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000418
419 // If the loop iterates a fixed number of times, we can refine the access size
420 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
421 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000422 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000423
424 // TODO: For this to be really effective, we have to dive into the pointer
425 // operand in the store. Store to &A[i] of 100 will always return may alias
426 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
427 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000428 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000429
430 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
431 ++BI)
432 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000433 if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000434 return true;
435
436 return false;
437}
438
Chris Lattner0f4a6402011-02-19 19:31:39 +0000439/// getMemSetPatternValue - If a strided store of the specified value is safe to
440/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
441/// be passed in. Otherwise, return null.
442///
443/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
444/// just replicate their input array and then pass on to memset_pattern16.
Chad Rosier43f9b482015-11-06 16:33:57 +0000445static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000446 // If the value isn't a constant, we can't promote it to being in a constant
447 // array. We could theoretically do a store to an alloca or something, but
448 // that doesn't seem worthwhile.
449 Constant *C = dyn_cast<Constant>(V);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000450 if (!C)
451 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000452
Chris Lattner0f4a6402011-02-19 19:31:39 +0000453 // Only handle simple values that are a power of two bytes in size.
Chad Rosier43f9b482015-11-06 16:33:57 +0000454 uint64_t Size = DL->getTypeSizeInBits(V->getType());
Chandler Carruthbad690e2015-08-12 23:06:37 +0000455 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000456 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000457
Chris Lattner72a35fb2011-02-19 19:56:44 +0000458 // Don't care enough about darwin/ppc to implement this.
Chad Rosier43f9b482015-11-06 16:33:57 +0000459 if (DL->isBigEndian())
Craig Topperf40110f2014-04-25 05:29:35 +0000460 return nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000461
462 // Convert to size in bytes.
463 Size /= 8;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000464
Chris Lattner0f4a6402011-02-19 19:31:39 +0000465 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner72a35fb2011-02-19 19:56:44 +0000466 // if the top and bottom are the same (e.g. for vectors and large integers).
Chandler Carruthbad690e2015-08-12 23:06:37 +0000467 if (Size > 16)
468 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000469
Chris Lattner72a35fb2011-02-19 19:56:44 +0000470 // If the constant is exactly 16 bytes, just use it.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000471 if (Size == 16)
472 return C;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000473
Chris Lattner72a35fb2011-02-19 19:56:44 +0000474 // Otherwise, we'll use an array of the constants.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000475 unsigned ArraySize = 16 / Size;
Chris Lattner72a35fb2011-02-19 19:56:44 +0000476 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000477 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
Chris Lattner0f4a6402011-02-19 19:31:39 +0000478}
479
Chad Rosiered0c7d12015-11-13 19:11:07 +0000480// If we have a negative stride, Start refers to the end of the memory location
481// we're trying to memset. Therefore, we need to recompute the base pointer,
482// which is just Start - BECount*Size.
483static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
484 Type *IntPtr, unsigned StoreSize,
485 ScalarEvolution *SE) {
486 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
487 if (StoreSize != 1)
488 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
489 SCEV::FlagNUW);
490 return SE->getMinusSCEV(Start, Index);
491}
492
Chris Lattner0f4a6402011-02-19 19:31:39 +0000493/// processLoopStridedStore - We see a strided store of some value. If we can
494/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000495bool LoopIdiomRecognize::processLoopStridedStore(
496 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
497 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000498 const SCEV *BECount, bool NegStride) {
Andrew Trick328b2232011-03-14 16:48:10 +0000499
Chris Lattner0f4a6402011-02-19 19:31:39 +0000500 // If the stored value is a byte-wise value (like i32 -1), then it may be
501 // turned into a memset of i8 -1, assuming that all the consecutive bytes
502 // are stored. A store of i32 0x01020304 can never be turned into a memset,
503 // but it can be turned into memset_pattern if the target supports it.
504 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000505 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000506 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
507
Chris Lattner0f4a6402011-02-19 19:31:39 +0000508 // If we're allowed to form a memset, and the stored value would be acceptable
509 // for memset, use it.
510 if (SplatValue && TLI->has(LibFunc::memset) &&
511 // Verify that the stored value is loop invariant. If not, we can't
512 // promote the memset.
513 CurLoop->isLoopInvariant(SplatValue)) {
514 // Keep and use SplatValue.
Craig Topperf40110f2014-04-25 05:29:35 +0000515 PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000516 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
517 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
Matt Arsenault009faed2013-09-11 05:09:42 +0000518 // Don't create memset_pattern16s with address spaces.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000519 // It looks like we can use PatternValue!
Craig Topperf40110f2014-04-25 05:29:35 +0000520 SplatValue = nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000521 } else {
522 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedmana93ab132011-09-13 00:44:16 +0000523 // do anything with a 3-byte store.
Chris Lattnera3514442011-01-01 20:12:04 +0000524 return false;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000525 }
Andrew Trick328b2232011-03-14 16:48:10 +0000526
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000527 // The trip count of the loop and the base pointer of the addrec SCEV is
528 // guaranteed to be loop invariant, which means that it should dominate the
529 // header. This allows us to insert code for it in the preheader.
530 BasicBlock *Preheader = CurLoop->getLoopPreheader();
531 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000532 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000533
Matt Arsenault009faed2013-09-11 05:09:42 +0000534 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000535 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000536
537 const SCEV *Start = Ev->getStart();
Chad Rosier2fa50a72015-11-13 19:13:40 +0000538 // Handle negative strided loops.
Chad Rosiered0c7d12015-11-13 19:11:07 +0000539 if (NegStride)
540 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
Matt Arsenault009faed2013-09-11 05:09:42 +0000541
Chris Lattner29e14ed2010-12-26 23:42:51 +0000542 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000543 // this into a memset in the loop preheader now if we want. However, this
544 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000545 // or write to the aliased location. Check for any overlap by generating the
546 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000547 Value *BasePtr =
548 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Chandler Carruth194f59c2015-07-22 23:15:57 +0000549 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000550 *AA, TheStore)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000551 Expander.clear();
552 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000553 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000554 return false;
555 }
556
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000557 // Okay, everything looks good, insert the memset.
558
Chris Lattner29e14ed2010-12-26 23:42:51 +0000559 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
560 // pointer size if it isn't already.
Chris Lattner0ba473c2011-01-04 00:06:55 +0000561 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000562
Chandler Carruthbad690e2015-08-12 23:06:37 +0000563 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000564 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000565 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000566 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000567 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000568 }
Andrew Trick328b2232011-03-14 16:48:10 +0000569
570 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000571 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000572
Devang Pateld00c6282011-03-07 22:43:45 +0000573 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000574 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000575 NewCall =
576 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000577 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000578 // Everything is emitted in default address space
579 Type *Int8PtrTy = DestInt8PtrTy;
580
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000581 Module *M = TheStore->getModule();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000582 Value *MSP =
583 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
584 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
Andrew Trick328b2232011-03-14 16:48:10 +0000585
Chris Lattner0f4a6402011-02-19 19:31:39 +0000586 // Otherwise we should form a memset_pattern16. PatternValue is known to be
587 // an constant array of 16-bytes. Plop the value into a mergable global.
588 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000589 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000590 PatternValue, ".memset_pattern");
591 GV->setUnnamedAddr(true); // Ok to merge these.
592 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000593 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000594 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000595 }
Andrew Trick328b2232011-03-14 16:48:10 +0000596
Chris Lattner29e14ed2010-12-26 23:42:51 +0000597 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000598 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000599 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000600
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000601 // Okay, the memset has been formed. Zap the original store and anything that
602 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000603 deleteDeadInstruction(TheStore, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +0000604 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000605 return true;
606}
607
Chad Rosier1cd3da12015-11-19 21:33:07 +0000608/// If the stored value is a strided load in the same loop with the same stride
609/// this may be transformable into a memcpy. This kicks in for stuff like
610/// for (i) A[i] = B[i];
Chandler Carruthbad690e2015-08-12 23:06:37 +0000611bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
612 StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
Chad Rosierfddc01f2015-11-19 18:22:21 +0000613 const SCEV *BECount, bool NegStride) {
Chris Lattnere6b261f2011-02-18 22:22:15 +0000614 // If we're not allowed to form memcpy, we fail.
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000615 if (!TLI->has(LibFunc::memcpy))
Chris Lattnere6b261f2011-02-18 22:22:15 +0000616 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000617
Chad Rosierfddc01f2015-11-19 18:22:21 +0000618 // The store must be feeding a non-volatile load.
619 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
620 if (!LI || !LI->isSimple())
621 return false;
622
623 // See if the pointer expression is an AddRec like {base,+,1} on the current
624 // loop, which indicates a strided load. If we have something else, it's a
625 // random load we can't handle.
Chad Rosier3ecc8d82015-11-19 18:25:11 +0000626 const SCEVAddRecExpr *LoadEv =
627 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
Chad Rosierfddc01f2015-11-19 18:22:21 +0000628 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
629 return false;
630
631 // The store and load must share the same stride.
632 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
633 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000634
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000635 // The trip count of the loop and the base pointer of the addrec SCEV is
636 // guaranteed to be loop invariant, which means that it should dominate the
637 // header. This allows us to insert code for it in the preheader.
638 BasicBlock *Preheader = CurLoop->getLoopPreheader();
639 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000640 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000641
Chad Rosiercc299b62015-11-13 21:51:02 +0000642 const SCEV *StrStart = StoreEv->getStart();
643 unsigned StrAS = SI->getPointerAddressSpace();
644 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
645
646 // Handle negative strided loops.
647 if (NegStride)
648 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
649
Chris Lattner85b6d812011-01-02 03:37:56 +0000650 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000651 // this into a memcpy in the loop preheader now if we want. However, this
652 // would be unsafe to do if there is anything else in the loop that may read
653 // or write the memory region we're storing to. This includes the load that
654 // feeds the stores. Check for an alias by generating the base address and
655 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000656 Value *StoreBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000657 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000658
Chandler Carruth194f59c2015-07-22 23:15:57 +0000659 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000660 StoreSize, *AA, SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000661 Expander.clear();
662 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000663 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000664 return false;
665 }
666
Chad Rosiercc299b62015-11-13 21:51:02 +0000667 const SCEV *LdStart = LoadEv->getStart();
668 unsigned LdAS = LI->getPointerAddressSpace();
669
670 // Handle negative strided loops.
671 if (NegStride)
672 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
673
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000674 // For a memcpy, we have to make sure that the input array is not being
675 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000676 Value *LoadBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000677 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000678
Chandler Carruth194f59c2015-07-22 23:15:57 +0000679 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000680 *AA, SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000681 Expander.clear();
682 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000683 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
684 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000685 return false;
686 }
687
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000688 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000689
Chris Lattner85b6d812011-01-02 03:37:56 +0000690 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
691 // pointer size if it isn't already.
Matt Arsenault009faed2013-09-11 05:09:42 +0000692 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +0000693
Chandler Carruthbad690e2015-08-12 23:06:37 +0000694 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000695 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +0000696 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +0000697 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000698 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +0000699
Chris Lattner85b6d812011-01-02 03:37:56 +0000700 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000701 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000702
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000703 CallInst *NewCall =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000704 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000705 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +0000706 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000707
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000708 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +0000709 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
710 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000711
Chad Rosier7f08d802015-10-13 20:59:16 +0000712 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +0000713 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000714 deleteDeadInstruction(SI, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000715 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +0000716 return true;
717}
Chandler Carruthd9c60702015-08-13 00:10:03 +0000718
719bool LoopIdiomRecognize::runOnNoncountableLoop() {
Chad Rosier19dc92d2015-11-09 16:56:06 +0000720 return recognizePopcount();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000721}
Chandler Carruth8219a502015-08-13 00:44:29 +0000722
723/// Check if the given conditional branch is based on the comparison between
724/// a variable and zero, and if the variable is non-zero, the control yields to
725/// the loop entry. If the branch matches the behavior, the variable involved
726/// in the comparion is returned. This function will be called to see if the
727/// precondition and postcondition of the loop are in desirable form.
728static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
729 if (!BI || !BI->isConditional())
730 return nullptr;
731
732 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
733 if (!Cond)
734 return nullptr;
735
736 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
737 if (!CmpZero || !CmpZero->isZero())
738 return nullptr;
739
740 ICmpInst::Predicate Pred = Cond->getPredicate();
741 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
742 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
743 return Cond->getOperand(0);
744
745 return nullptr;
746}
747
748/// Return true iff the idiom is detected in the loop.
749///
750/// Additionally:
751/// 1) \p CntInst is set to the instruction counting the population bit.
752/// 2) \p CntPhi is set to the corresponding phi node.
753/// 3) \p Var is set to the value whose population bits are being counted.
754///
755/// The core idiom we are trying to detect is:
756/// \code
757/// if (x0 != 0)
758/// goto loop-exit // the precondition of the loop
759/// cnt0 = init-val;
760/// do {
761/// x1 = phi (x0, x2);
762/// cnt1 = phi(cnt0, cnt2);
763///
764/// cnt2 = cnt1 + 1;
765/// ...
766/// x2 = x1 & (x1 - 1);
767/// ...
768/// } while(x != 0);
769///
770/// loop-exit:
771/// \endcode
772static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
773 Instruction *&CntInst, PHINode *&CntPhi,
774 Value *&Var) {
775 // step 1: Check to see if the look-back branch match this pattern:
776 // "if (a!=0) goto loop-entry".
777 BasicBlock *LoopEntry;
778 Instruction *DefX2, *CountInst;
779 Value *VarX1, *VarX0;
780 PHINode *PhiX, *CountPhi;
781
782 DefX2 = CountInst = nullptr;
783 VarX1 = VarX0 = nullptr;
784 PhiX = CountPhi = nullptr;
785 LoopEntry = *(CurLoop->block_begin());
786
787 // step 1: Check if the loop-back branch is in desirable form.
788 {
789 if (Value *T = matchCondition(
790 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
791 DefX2 = dyn_cast<Instruction>(T);
792 else
793 return false;
794 }
795
796 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
797 {
798 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
799 return false;
800
801 BinaryOperator *SubOneOp;
802
803 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
804 VarX1 = DefX2->getOperand(1);
805 else {
806 VarX1 = DefX2->getOperand(0);
807 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
808 }
809 if (!SubOneOp)
810 return false;
811
812 Instruction *SubInst = cast<Instruction>(SubOneOp);
813 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
814 if (!Dec ||
815 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
816 (SubInst->getOpcode() == Instruction::Add &&
817 Dec->isAllOnesValue()))) {
818 return false;
819 }
820 }
821
822 // step 3: Check the recurrence of variable X
823 {
824 PhiX = dyn_cast<PHINode>(VarX1);
825 if (!PhiX ||
826 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
827 return false;
828 }
829 }
830
831 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
832 {
833 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000834 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +0000835 IterE = LoopEntry->end();
836 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000837 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +0000838 if (Inst->getOpcode() != Instruction::Add)
839 continue;
840
841 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
842 if (!Inc || !Inc->isOne())
843 continue;
844
845 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
846 if (!Phi || Phi->getParent() != LoopEntry)
847 continue;
848
849 // Check if the result of the instruction is live of the loop.
850 bool LiveOutLoop = false;
851 for (User *U : Inst->users()) {
852 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
853 LiveOutLoop = true;
854 break;
855 }
856 }
857
858 if (LiveOutLoop) {
859 CountInst = Inst;
860 CountPhi = Phi;
861 break;
862 }
863 }
864
865 if (!CountInst)
866 return false;
867 }
868
869 // step 5: check if the precondition is in this form:
870 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
871 {
872 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
873 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
874 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
875 return false;
876
877 CntInst = CountInst;
878 CntPhi = CountPhi;
879 Var = T;
880 }
881
882 return true;
883}
884
885/// Recognizes a population count idiom in a non-countable loop.
886///
887/// If detected, transforms the relevant code to issue the popcount intrinsic
888/// function call, and returns true; otherwise, returns false.
889bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +0000890 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
891 return false;
892
893 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +0000894 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +0000895 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
896 // in a compact loop.
897
Renato Golin655348f2015-08-13 11:25:38 +0000898 // Give up if the loop has multiple blocks or multiple backedges.
899 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +0000900 return false;
901
Renato Golin655348f2015-08-13 11:25:38 +0000902 BasicBlock *LoopBody = *(CurLoop->block_begin());
903 if (LoopBody->size() >= 20) {
904 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +0000905 return false;
Renato Golin655348f2015-08-13 11:25:38 +0000906 }
Chandler Carruth8219a502015-08-13 00:44:29 +0000907
908 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +0000909 BasicBlock *PH = CurLoop->getLoopPreheader();
910 if (!PH)
Chandler Carruth8219a502015-08-13 00:44:29 +0000911 return false;
Renato Golin655348f2015-08-13 11:25:38 +0000912 if (&PH->front() != PH->getTerminator())
913 return false;
914 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +0000915 if (!EntryBI || EntryBI->isConditional())
916 return false;
917
918 // It should have a precondition block where the generated popcount instrinsic
919 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +0000920 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +0000921 if (!PreCondBB)
922 return false;
923 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
924 if (!PreCondBI || PreCondBI->isUnconditional())
925 return false;
926
927 Instruction *CntInst;
928 PHINode *CntPhi;
929 Value *Val;
930 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
931 return false;
932
933 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
934 return true;
935}
936
937static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
938 DebugLoc DL) {
939 Value *Ops[] = {Val};
940 Type *Tys[] = {Val->getType()};
941
942 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
943 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
944 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
945 CI->setDebugLoc(DL);
946
947 return CI;
948}
949
950void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
951 Instruction *CntInst,
952 PHINode *CntPhi, Value *Var) {
953 BasicBlock *PreHead = CurLoop->getLoopPreheader();
954 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
955 const DebugLoc DL = CntInst->getDebugLoc();
956
957 // Assuming before transformation, the loop is following:
958 // if (x) // the precondition
959 // do { cnt++; x &= x - 1; } while(x);
960
961 // Step 1: Insert the ctpop instruction at the end of the precondition block
962 IRBuilder<> Builder(PreCondBr);
963 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
964 {
965 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
966 NewCount = PopCntZext =
967 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
968
969 if (NewCount != PopCnt)
970 (cast<Instruction>(NewCount))->setDebugLoc(DL);
971
972 // TripCnt is exactly the number of iterations the loop has
973 TripCnt = NewCount;
974
975 // If the population counter's initial value is not zero, insert Add Inst.
976 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
977 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
978 if (!InitConst || !InitConst->isZero()) {
979 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
980 (cast<Instruction>(NewCount))->setDebugLoc(DL);
981 }
982 }
983
Nick Lewycky2c852542015-08-19 06:22:33 +0000984 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +0000985 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +0000986 // function would be partial dead code, and downstream passes will drag
987 // it back from the precondition block to the preheader.
988 {
989 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
990
991 Value *Opnd0 = PopCntZext;
992 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
993 if (PreCond->getOperand(0) != Var)
994 std::swap(Opnd0, Opnd1);
995
996 ICmpInst *NewPreCond = cast<ICmpInst>(
997 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
998 PreCondBr->setCondition(NewPreCond);
999
1000 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1001 }
1002
1003 // Step 3: Note that the population count is exactly the trip count of the
Nick Lewycky1098e492015-08-19 06:25:30 +00001004 // loop in question, which enable us to to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +00001005 // loop into a countable one. The benefit is twofold:
1006 //
Nick Lewycky2c852542015-08-19 06:22:33 +00001007 // - If the loop only counts population, the entire loop becomes dead after
1008 // the transformation. It is a lot easier to prove a countable loop dead
1009 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +00001010 // isn't dead even if it computes nothing useful. In general, DCE needs
1011 // to prove a noncountable loop finite before safely delete it.)
1012 //
1013 // - If the loop also performs something else, it remains alive.
1014 // Since it is transformed to countable form, it can be aggressively
1015 // optimized by some optimizations which are in general not applicable
1016 // to a noncountable loop.
1017 //
1018 // After this step, this loop (conceptually) would look like following:
1019 // newcnt = __builtin_ctpop(x);
1020 // t = newcnt;
1021 // if (x)
1022 // do { cnt++; x &= x-1; t--) } while (t > 0);
1023 BasicBlock *Body = *(CurLoop->block_begin());
1024 {
1025 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1026 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1027 Type *Ty = TripCnt->getType();
1028
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001029 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +00001030
1031 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +00001032 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +00001033 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1034 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +00001035
1036 TcPhi->addIncoming(TripCnt, PreHead);
1037 TcPhi->addIncoming(TcDec, Body);
1038
1039 CmpInst::Predicate Pred =
1040 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1041 LbCond->setPredicate(Pred);
1042 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001043 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001044 }
1045
1046 // Step 4: All the references to the original population counter outside
1047 // the loop are replaced with the NewCount -- the value returned from
1048 // __builtin_ctpop().
1049 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1050
1051 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1052 // loop. The loop would otherwise not be deleted even if it becomes empty.
1053 SE->forgetLoop(CurLoop);
1054}