blob: a711319ce5a60bf52c8505c6862460ae4d1ab4c9 [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"
Chris Lattner29e14ed2010-12-26 23:42:51 +000045#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000046#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.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);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000121 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
122 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
123
124 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
125 unsigned StoreAlignment, Value *SplatValue,
126 Instruction *TheStore, const SCEVAddRecExpr *Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000127 const SCEV *BECount, bool NegStride);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000128 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
129 const SCEVAddRecExpr *StoreEv,
130 const SCEVAddRecExpr *LoadEv,
131 const SCEV *BECount);
132
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 Rosiercc9030b2015-11-11 23:00:59 +0000247void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
248 StoreRefs.clear();
249 for (Instruction &I : *BB) {
250 StoreInst *SI = dyn_cast<StoreInst>(&I);
251 if (!SI)
252 continue;
253
254 // Don't touch volatile stores.
255 if (!SI->isSimple())
256 continue;
257
258 // Save the store locations.
259 StoreRefs.push_back(SI);
260 }
261}
262
Chris Lattner8455b6e2011-01-02 19:01:03 +0000263/// runOnLoopBlock - Process the specified block, which lives in a counted loop
264/// with the specified backedge count. This block is known to be in the current
265/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000266bool LoopIdiomRecognize::runOnLoopBlock(
267 BasicBlock *BB, const SCEV *BECount,
268 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000269 // We can only promote stores in this block if they are unconditionally
270 // executed in the loop. For a block to be unconditionally executed, it has
271 // to dominate all the exit blocks of the loop. Verify this now.
272 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
273 if (!DT->dominates(BB, ExitBlocks[i]))
274 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000275
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000276 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000277 // Look for store instructions, which may be optimized to memset/memcpy.
278 collectStores(BB);
279 for (auto &SI : StoreRefs)
280 MadeChange |= processLoopStore(SI, BECount);
281
Chandler Carruthbad690e2015-08-12 23:06:37 +0000282 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000283 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000284 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000285 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000286 WeakVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000287 if (!processLoopMemSet(MSI, BECount))
288 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000289 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000290
Chris Lattner86438102011-01-04 07:46:33 +0000291 // If processing the memset invalidated our iterator, start over from the
292 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000293 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000294 I = BB->begin();
295 continue;
296 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000297 }
Andrew Trick328b2232011-03-14 16:48:10 +0000298
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000299 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000300}
301
Chris Lattner86438102011-01-04 07:46:33 +0000302/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000303bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Chad Rosiercc9030b2015-11-11 23:00:59 +0000304 assert(SI->isSimple() && "Expected only non-volatile stores.");
Chris Lattner86438102011-01-04 07:46:33 +0000305
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000306 Value *StoredVal = SI->getValueOperand();
Chris Lattner29e14ed2010-12-26 23:42:51 +0000307 Value *StorePtr = SI->getPointerOperand();
Andrew Trick328b2232011-03-14 16:48:10 +0000308
Chris Lattner65a699d2010-12-28 18:53:48 +0000309 // Reject stores that are so large that they overflow an unsigned.
Chad Rosier43f9b482015-11-06 16:33:57 +0000310 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
Chris Lattner65a699d2010-12-28 18:53:48 +0000311 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000312 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000313
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000314 // See if the pointer expression is an AddRec like {base,+,1} on the current
315 // loop, which indicates a strided store. If we have something else, it's a
316 // random store we can't handle.
Chris Lattner85b6d812011-01-02 03:37:56 +0000317 const SCEVAddRecExpr *StoreEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000318 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Craig Topperf40110f2014-04-25 05:29:35 +0000319 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000320 return false;
321
322 // Check to see if the stride matches the size of the store. If so, then we
323 // know that every byte is touched in the loop.
Andrew Trick328b2232011-03-14 16:48:10 +0000324 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Andrew Trick328b2232011-03-14 16:48:10 +0000325
Chad Rosier79676142015-10-28 14:38:49 +0000326 const SCEVConstant *ConstStride =
327 dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
328 if (!ConstStride)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000329 return false;
Chad Rosier79676142015-10-28 14:38:49 +0000330
331 APInt Stride = ConstStride->getValue()->getValue();
332 if (StoreSize != Stride && StoreSize != -Stride)
333 return false;
334
335 bool NegStride = StoreSize == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000336
337 // See if we can optimize just this store in isolation.
338 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
Chad Rosier79676142015-10-28 14:38:49 +0000339 StoredVal, SI, StoreEv, BECount, NegStride))
Chris Lattner0f4a6402011-02-19 19:31:39 +0000340 return true;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000341
Chad Rosier79676142015-10-28 14:38:49 +0000342 // TODO: We don't handle negative stride memcpys.
343 if (NegStride)
344 return false;
345
Chris Lattner85b6d812011-01-02 03:37:56 +0000346 // If the stored value is a strided load in the same loop with the same stride
Chad Rosier7142da02015-10-28 15:08:33 +0000347 // this may be transformable into a memcpy. This kicks in for stuff like
Chris Lattner85b6d812011-01-02 03:37:56 +0000348 // for (i) A[i] = B[i];
349 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
350 const SCEVAddRecExpr *LoadEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000351 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
Chris Lattner85b6d812011-01-02 03:37:56 +0000352 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman7c5dc122011-09-12 20:23:13 +0000353 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattner85b6d812011-01-02 03:37:56 +0000354 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
355 return true;
356 }
Chandler Carruthbad690e2015-08-12 23:06:37 +0000357 // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000358
Chris Lattner81ae3f22010-12-26 19:39:38 +0000359 return false;
360}
361
Chris Lattner86438102011-01-04 07:46:33 +0000362/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000363bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
364 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000365 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000366 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
367 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000368
Chris Lattnere6b261f2011-02-18 22:22:15 +0000369 // If we're not allowed to hack on memset, we fail.
370 if (!TLI->has(LibFunc::memset))
371 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000372
Chris Lattner86438102011-01-04 07:46:33 +0000373 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000374
Chris Lattner86438102011-01-04 07:46:33 +0000375 // See if the pointer expression is an AddRec like {base,+,1} on the current
376 // loop, which indicates a strided store. If we have something else, it's a
377 // random store we can't handle.
378 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000379 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000380 return false;
381
382 // Reject memsets that are so large that they overflow an unsigned.
383 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
384 if ((SizeInBytes >> 32) != 0)
385 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000386
Chris Lattner86438102011-01-04 07:46:33 +0000387 // Check to see if the stride matches the size of the memset. If so, then we
388 // know that every byte is touched in the loop.
389 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000390
Chris Lattner86438102011-01-04 07:46:33 +0000391 // TODO: Could also handle negative stride here someday, that will require the
392 // validity check in mayLoopAccessLocation to be updated though.
Craig Topperf40110f2014-04-25 05:29:35 +0000393 if (!Stride || MSI->getLength() != Stride->getValue())
Chris Lattner86438102011-01-04 07:46:33 +0000394 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000395
Chris Lattner0f4a6402011-02-19 19:31:39 +0000396 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Chandler Carruthbad690e2015-08-12 23:06:37 +0000397 MSI->getAlignment(), MSI->getValue(), MSI, Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000398 BECount, /*NegStride=*/false);
Chris Lattner86438102011-01-04 07:46:33 +0000399}
400
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000401/// mayLoopAccessLocation - Return true if the specified loop might access the
402/// specified pointer location, which is a loop-strided access. The 'Access'
403/// argument specifies what the verboten forms of access are (read or write).
Chandler Carruth194f59c2015-07-22 23:15:57 +0000404static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
405 const SCEV *BECount, unsigned StoreSize,
406 AliasAnalysis &AA,
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000407 Instruction *IgnoredStore) {
408 // Get the location that may be stored across the loop. Since the access is
409 // strided positively through memory, we say that the modified location starts
410 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000411 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000412
413 // If the loop iterates a fixed number of times, we can refine the access size
414 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
415 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000416 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000417
418 // TODO: For this to be really effective, we have to dive into the pointer
419 // operand in the store. Store to &A[i] of 100 will always return may alias
420 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
421 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000422 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000423
424 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
425 ++BI)
426 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000427 if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000428 return true;
429
430 return false;
431}
432
Chris Lattner0f4a6402011-02-19 19:31:39 +0000433/// getMemSetPatternValue - If a strided store of the specified value is safe to
434/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
435/// be passed in. Otherwise, return null.
436///
437/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
438/// just replicate their input array and then pass on to memset_pattern16.
Chad Rosier43f9b482015-11-06 16:33:57 +0000439static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000440 // If the value isn't a constant, we can't promote it to being in a constant
441 // array. We could theoretically do a store to an alloca or something, but
442 // that doesn't seem worthwhile.
443 Constant *C = dyn_cast<Constant>(V);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000444 if (!C)
445 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000446
Chris Lattner0f4a6402011-02-19 19:31:39 +0000447 // Only handle simple values that are a power of two bytes in size.
Chad Rosier43f9b482015-11-06 16:33:57 +0000448 uint64_t Size = DL->getTypeSizeInBits(V->getType());
Chandler Carruthbad690e2015-08-12 23:06:37 +0000449 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000450 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000451
Chris Lattner72a35fb2011-02-19 19:56:44 +0000452 // Don't care enough about darwin/ppc to implement this.
Chad Rosier43f9b482015-11-06 16:33:57 +0000453 if (DL->isBigEndian())
Craig Topperf40110f2014-04-25 05:29:35 +0000454 return nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000455
456 // Convert to size in bytes.
457 Size /= 8;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000458
Chris Lattner0f4a6402011-02-19 19:31:39 +0000459 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner72a35fb2011-02-19 19:56:44 +0000460 // if the top and bottom are the same (e.g. for vectors and large integers).
Chandler Carruthbad690e2015-08-12 23:06:37 +0000461 if (Size > 16)
462 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000463
Chris Lattner72a35fb2011-02-19 19:56:44 +0000464 // If the constant is exactly 16 bytes, just use it.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000465 if (Size == 16)
466 return C;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000467
Chris Lattner72a35fb2011-02-19 19:56:44 +0000468 // Otherwise, we'll use an array of the constants.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000469 unsigned ArraySize = 16 / Size;
Chris Lattner72a35fb2011-02-19 19:56:44 +0000470 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000471 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
Chris Lattner0f4a6402011-02-19 19:31:39 +0000472}
473
Chris Lattner0f4a6402011-02-19 19:31:39 +0000474/// processLoopStridedStore - We see a strided store of some value. If we can
475/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000476bool LoopIdiomRecognize::processLoopStridedStore(
477 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
478 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000479 const SCEV *BECount, bool NegStride) {
Andrew Trick328b2232011-03-14 16:48:10 +0000480
Chris Lattner0f4a6402011-02-19 19:31:39 +0000481 // If the stored value is a byte-wise value (like i32 -1), then it may be
482 // turned into a memset of i8 -1, assuming that all the consecutive bytes
483 // are stored. A store of i32 0x01020304 can never be turned into a memset,
484 // but it can be turned into memset_pattern if the target supports it.
485 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000486 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000487 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
488
Chris Lattner0f4a6402011-02-19 19:31:39 +0000489 // If we're allowed to form a memset, and the stored value would be acceptable
490 // for memset, use it.
491 if (SplatValue && TLI->has(LibFunc::memset) &&
492 // Verify that the stored value is loop invariant. If not, we can't
493 // promote the memset.
494 CurLoop->isLoopInvariant(SplatValue)) {
495 // Keep and use SplatValue.
Craig Topperf40110f2014-04-25 05:29:35 +0000496 PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000497 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
498 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
Matt Arsenault009faed2013-09-11 05:09:42 +0000499 // Don't create memset_pattern16s with address spaces.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000500 // It looks like we can use PatternValue!
Craig Topperf40110f2014-04-25 05:29:35 +0000501 SplatValue = nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000502 } else {
503 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedmana93ab132011-09-13 00:44:16 +0000504 // do anything with a 3-byte store.
Chris Lattnera3514442011-01-01 20:12:04 +0000505 return false;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000506 }
Andrew Trick328b2232011-03-14 16:48:10 +0000507
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000508 // The trip count of the loop and the base pointer of the addrec SCEV is
509 // guaranteed to be loop invariant, which means that it should dominate the
510 // header. This allows us to insert code for it in the preheader.
511 BasicBlock *Preheader = CurLoop->getLoopPreheader();
512 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000513 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000514
Matt Arsenault009faed2013-09-11 05:09:42 +0000515 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000516 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000517
518 const SCEV *Start = Ev->getStart();
519 // If we have a negative stride, Start refers to the end of the memory
520 // location we're trying to memset. Therefore, we need to recompute the start
521 // point, which is just Start - BECount*Size.
522 if (NegStride) {
523 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
524 if (StoreSize != 1)
525 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
526 SCEV::FlagNUW);
527 Start = SE->getMinusSCEV(Ev->getStart(), Index);
528 }
Matt Arsenault009faed2013-09-11 05:09:42 +0000529
Chris Lattner29e14ed2010-12-26 23:42:51 +0000530 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000531 // this into a memset in the loop preheader now if we want. However, this
532 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000533 // or write to the aliased location. Check for any overlap by generating the
534 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000535 Value *BasePtr =
536 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Chandler Carruth194f59c2015-07-22 23:15:57 +0000537 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000538 *AA, TheStore)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000539 Expander.clear();
540 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000541 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000542 return false;
543 }
544
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000545 // Okay, everything looks good, insert the memset.
546
Chris Lattner29e14ed2010-12-26 23:42:51 +0000547 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
548 // pointer size if it isn't already.
Chris Lattner0ba473c2011-01-04 00:06:55 +0000549 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000550
Chandler Carruthbad690e2015-08-12 23:06:37 +0000551 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000552 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000553 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000554 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000555 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000556 }
Andrew Trick328b2232011-03-14 16:48:10 +0000557
558 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000559 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000560
Devang Pateld00c6282011-03-07 22:43:45 +0000561 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000562 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000563 NewCall =
564 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000565 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000566 // Everything is emitted in default address space
567 Type *Int8PtrTy = DestInt8PtrTy;
568
Chris Lattner0f4a6402011-02-19 19:31:39 +0000569 Module *M = TheStore->getParent()->getParent()->getParent();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000570 Value *MSP =
571 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
572 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
Andrew Trick328b2232011-03-14 16:48:10 +0000573
Chris Lattner0f4a6402011-02-19 19:31:39 +0000574 // Otherwise we should form a memset_pattern16. PatternValue is known to be
575 // an constant array of 16-bytes. Plop the value into a mergable global.
576 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000577 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000578 PatternValue, ".memset_pattern");
579 GV->setUnnamedAddr(true); // Ok to merge these.
580 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000581 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000582 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000583 }
Andrew Trick328b2232011-03-14 16:48:10 +0000584
Chris Lattner29e14ed2010-12-26 23:42:51 +0000585 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000586 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000587 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000588
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000589 // Okay, the memset has been formed. Zap the original store and anything that
590 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000591 deleteDeadInstruction(TheStore, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +0000592 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000593 return true;
594}
595
Chris Lattner85b6d812011-01-02 03:37:56 +0000596/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
597/// same-strided load.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000598bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
599 StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
600 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
Chris Lattnere6b261f2011-02-18 22:22:15 +0000601 // If we're not allowed to form memcpy, we fail.
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000602 if (!TLI->has(LibFunc::memcpy))
Chris Lattnere6b261f2011-02-18 22:22:15 +0000603 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000604
Chris Lattner85b6d812011-01-02 03:37:56 +0000605 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trick328b2232011-03-14 16:48:10 +0000606
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000607 // The trip count of the loop and the base pointer of the addrec SCEV is
608 // guaranteed to be loop invariant, which means that it should dominate the
609 // header. This allows us to insert code for it in the preheader.
610 BasicBlock *Preheader = CurLoop->getLoopPreheader();
611 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000612 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000613
Chris Lattner85b6d812011-01-02 03:37:56 +0000614 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000615 // this into a memcpy in the loop preheader now if we want. However, this
616 // would be unsafe to do if there is anything else in the loop that may read
617 // or write the memory region we're storing to. This includes the load that
618 // feeds the stores. Check for an alias by generating the base address and
619 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000620 Value *StoreBasePtr = Expander.expandCodeFor(
621 StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
622 Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000623
Chandler Carruth194f59c2015-07-22 23:15:57 +0000624 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000625 StoreSize, *AA, SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000626 Expander.clear();
627 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000628 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000629 return false;
630 }
631
632 // For a memcpy, we have to make sure that the input array is not being
633 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000634 Value *LoadBasePtr = Expander.expandCodeFor(
635 LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
636 Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000637
Chandler Carruth194f59c2015-07-22 23:15:57 +0000638 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
Chandler Carruthbf143e22015-08-14 00:21:10 +0000639 *AA, SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000640 Expander.clear();
641 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000642 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
643 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000644 return false;
645 }
646
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000647 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000648
Chris Lattner85b6d812011-01-02 03:37:56 +0000649 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
650 // pointer size if it isn't already.
Chad Rosier43f9b482015-11-06 16:33:57 +0000651 Type *IntPtrTy = Builder.getIntPtrTy(*DL, SI->getPointerAddressSpace());
Matt Arsenault009faed2013-09-11 05:09:42 +0000652 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +0000653
Chandler Carruthbad690e2015-08-12 23:06:37 +0000654 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000655 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +0000656 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +0000657 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000658 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +0000659
Chris Lattner85b6d812011-01-02 03:37:56 +0000660 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000661 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000662
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000663 CallInst *NewCall =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000664 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
665 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +0000666 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000667
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000668 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +0000669 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
670 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000671
Chad Rosier7f08d802015-10-13 20:59:16 +0000672 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +0000673 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000674 deleteDeadInstruction(SI, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000675 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +0000676 return true;
677}
Chandler Carruthd9c60702015-08-13 00:10:03 +0000678
679bool LoopIdiomRecognize::runOnNoncountableLoop() {
Chad Rosier19dc92d2015-11-09 16:56:06 +0000680 return recognizePopcount();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000681}
Chandler Carruth8219a502015-08-13 00:44:29 +0000682
683/// Check if the given conditional branch is based on the comparison between
684/// a variable and zero, and if the variable is non-zero, the control yields to
685/// the loop entry. If the branch matches the behavior, the variable involved
686/// in the comparion is returned. This function will be called to see if the
687/// precondition and postcondition of the loop are in desirable form.
688static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
689 if (!BI || !BI->isConditional())
690 return nullptr;
691
692 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
693 if (!Cond)
694 return nullptr;
695
696 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
697 if (!CmpZero || !CmpZero->isZero())
698 return nullptr;
699
700 ICmpInst::Predicate Pred = Cond->getPredicate();
701 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
702 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
703 return Cond->getOperand(0);
704
705 return nullptr;
706}
707
708/// Return true iff the idiom is detected in the loop.
709///
710/// Additionally:
711/// 1) \p CntInst is set to the instruction counting the population bit.
712/// 2) \p CntPhi is set to the corresponding phi node.
713/// 3) \p Var is set to the value whose population bits are being counted.
714///
715/// The core idiom we are trying to detect is:
716/// \code
717/// if (x0 != 0)
718/// goto loop-exit // the precondition of the loop
719/// cnt0 = init-val;
720/// do {
721/// x1 = phi (x0, x2);
722/// cnt1 = phi(cnt0, cnt2);
723///
724/// cnt2 = cnt1 + 1;
725/// ...
726/// x2 = x1 & (x1 - 1);
727/// ...
728/// } while(x != 0);
729///
730/// loop-exit:
731/// \endcode
732static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
733 Instruction *&CntInst, PHINode *&CntPhi,
734 Value *&Var) {
735 // step 1: Check to see if the look-back branch match this pattern:
736 // "if (a!=0) goto loop-entry".
737 BasicBlock *LoopEntry;
738 Instruction *DefX2, *CountInst;
739 Value *VarX1, *VarX0;
740 PHINode *PhiX, *CountPhi;
741
742 DefX2 = CountInst = nullptr;
743 VarX1 = VarX0 = nullptr;
744 PhiX = CountPhi = nullptr;
745 LoopEntry = *(CurLoop->block_begin());
746
747 // step 1: Check if the loop-back branch is in desirable form.
748 {
749 if (Value *T = matchCondition(
750 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
751 DefX2 = dyn_cast<Instruction>(T);
752 else
753 return false;
754 }
755
756 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
757 {
758 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
759 return false;
760
761 BinaryOperator *SubOneOp;
762
763 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
764 VarX1 = DefX2->getOperand(1);
765 else {
766 VarX1 = DefX2->getOperand(0);
767 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
768 }
769 if (!SubOneOp)
770 return false;
771
772 Instruction *SubInst = cast<Instruction>(SubOneOp);
773 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
774 if (!Dec ||
775 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
776 (SubInst->getOpcode() == Instruction::Add &&
777 Dec->isAllOnesValue()))) {
778 return false;
779 }
780 }
781
782 // step 3: Check the recurrence of variable X
783 {
784 PhiX = dyn_cast<PHINode>(VarX1);
785 if (!PhiX ||
786 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
787 return false;
788 }
789 }
790
791 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
792 {
793 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000794 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +0000795 IterE = LoopEntry->end();
796 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000797 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +0000798 if (Inst->getOpcode() != Instruction::Add)
799 continue;
800
801 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
802 if (!Inc || !Inc->isOne())
803 continue;
804
805 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
806 if (!Phi || Phi->getParent() != LoopEntry)
807 continue;
808
809 // Check if the result of the instruction is live of the loop.
810 bool LiveOutLoop = false;
811 for (User *U : Inst->users()) {
812 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
813 LiveOutLoop = true;
814 break;
815 }
816 }
817
818 if (LiveOutLoop) {
819 CountInst = Inst;
820 CountPhi = Phi;
821 break;
822 }
823 }
824
825 if (!CountInst)
826 return false;
827 }
828
829 // step 5: check if the precondition is in this form:
830 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
831 {
832 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
833 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
834 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
835 return false;
836
837 CntInst = CountInst;
838 CntPhi = CountPhi;
839 Var = T;
840 }
841
842 return true;
843}
844
845/// Recognizes a population count idiom in a non-countable loop.
846///
847/// If detected, transforms the relevant code to issue the popcount intrinsic
848/// function call, and returns true; otherwise, returns false.
849bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +0000850 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
851 return false;
852
853 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +0000854 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +0000855 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
856 // in a compact loop.
857
Renato Golin655348f2015-08-13 11:25:38 +0000858 // Give up if the loop has multiple blocks or multiple backedges.
859 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +0000860 return false;
861
Renato Golin655348f2015-08-13 11:25:38 +0000862 BasicBlock *LoopBody = *(CurLoop->block_begin());
863 if (LoopBody->size() >= 20) {
864 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +0000865 return false;
Renato Golin655348f2015-08-13 11:25:38 +0000866 }
Chandler Carruth8219a502015-08-13 00:44:29 +0000867
868 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +0000869 BasicBlock *PH = CurLoop->getLoopPreheader();
870 if (!PH)
Chandler Carruth8219a502015-08-13 00:44:29 +0000871 return false;
Renato Golin655348f2015-08-13 11:25:38 +0000872 if (&PH->front() != PH->getTerminator())
873 return false;
874 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +0000875 if (!EntryBI || EntryBI->isConditional())
876 return false;
877
878 // It should have a precondition block where the generated popcount instrinsic
879 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +0000880 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +0000881 if (!PreCondBB)
882 return false;
883 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
884 if (!PreCondBI || PreCondBI->isUnconditional())
885 return false;
886
887 Instruction *CntInst;
888 PHINode *CntPhi;
889 Value *Val;
890 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
891 return false;
892
893 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
894 return true;
895}
896
897static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
898 DebugLoc DL) {
899 Value *Ops[] = {Val};
900 Type *Tys[] = {Val->getType()};
901
902 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
903 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
904 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
905 CI->setDebugLoc(DL);
906
907 return CI;
908}
909
910void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
911 Instruction *CntInst,
912 PHINode *CntPhi, Value *Var) {
913 BasicBlock *PreHead = CurLoop->getLoopPreheader();
914 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
915 const DebugLoc DL = CntInst->getDebugLoc();
916
917 // Assuming before transformation, the loop is following:
918 // if (x) // the precondition
919 // do { cnt++; x &= x - 1; } while(x);
920
921 // Step 1: Insert the ctpop instruction at the end of the precondition block
922 IRBuilder<> Builder(PreCondBr);
923 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
924 {
925 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
926 NewCount = PopCntZext =
927 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
928
929 if (NewCount != PopCnt)
930 (cast<Instruction>(NewCount))->setDebugLoc(DL);
931
932 // TripCnt is exactly the number of iterations the loop has
933 TripCnt = NewCount;
934
935 // If the population counter's initial value is not zero, insert Add Inst.
936 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
937 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
938 if (!InitConst || !InitConst->isZero()) {
939 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
940 (cast<Instruction>(NewCount))->setDebugLoc(DL);
941 }
942 }
943
Nick Lewycky2c852542015-08-19 06:22:33 +0000944 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +0000945 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +0000946 // function would be partial dead code, and downstream passes will drag
947 // it back from the precondition block to the preheader.
948 {
949 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
950
951 Value *Opnd0 = PopCntZext;
952 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
953 if (PreCond->getOperand(0) != Var)
954 std::swap(Opnd0, Opnd1);
955
956 ICmpInst *NewPreCond = cast<ICmpInst>(
957 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
958 PreCondBr->setCondition(NewPreCond);
959
960 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
961 }
962
963 // Step 3: Note that the population count is exactly the trip count of the
Nick Lewycky1098e492015-08-19 06:25:30 +0000964 // loop in question, which enable us to to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +0000965 // loop into a countable one. The benefit is twofold:
966 //
Nick Lewycky2c852542015-08-19 06:22:33 +0000967 // - If the loop only counts population, the entire loop becomes dead after
968 // the transformation. It is a lot easier to prove a countable loop dead
969 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +0000970 // isn't dead even if it computes nothing useful. In general, DCE needs
971 // to prove a noncountable loop finite before safely delete it.)
972 //
973 // - If the loop also performs something else, it remains alive.
974 // Since it is transformed to countable form, it can be aggressively
975 // optimized by some optimizations which are in general not applicable
976 // to a noncountable loop.
977 //
978 // After this step, this loop (conceptually) would look like following:
979 // newcnt = __builtin_ctpop(x);
980 // t = newcnt;
981 // if (x)
982 // do { cnt++; x &= x-1; t--) } while (t > 0);
983 BasicBlock *Body = *(CurLoop->block_begin());
984 {
985 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
986 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
987 Type *Ty = TripCnt->getType();
988
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000989 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +0000990
991 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +0000992 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +0000993 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
994 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +0000995
996 TcPhi->addIncoming(TripCnt, PreHead);
997 TcPhi->addIncoming(TcDec, Body);
998
999 CmpInst::Predicate Pred =
1000 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1001 LbCond->setPredicate(Pred);
1002 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001003 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001004 }
1005
1006 // Step 4: All the references to the original population counter outside
1007 // the loop are replaced with the NewCount -- the value returned from
1008 // __builtin_ctpop().
1009 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1010
1011 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1012 // loop. The loop would otherwise not be deleted even if it becomes empty.
1013 SE->forgetLoop(CurLoop);
1014}