blob: 8ccbf9dcb1a7ef2670a8142a97c5220f8b1c456d [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 Lattnerbc661d62011-02-21 02:08:54 +000034// We should enhance this to handle negative strides through memory.
35// Alternatively (and perhaps better) we could rely on an earlier pass to force
36// forward iteration through memory, which is generally better for cache
37// behavior. Negative strides *do* happen for memset/memcpy loops.
38//
Chris Lattner02a97762011-01-03 01:10:08 +000039// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000040// replace them with calls to BLAS (if linked in??).
41//
Chris Lattner0469e012011-01-02 18:32:09 +000042//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000043
Chris Lattner81ae3f22010-12-26 19:39:38 +000044#include "llvm/Transforms/Scalar.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000046#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000047#include "llvm/Analysis/LoopPass.h"
Chris Lattner29e14ed2010-12-26 23:42:51 +000048#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000050#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000051#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000052#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000054#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/IntrinsicInst.h"
57#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000058#include "llvm/Support/Debug.h"
59#include "llvm/Support/raw_ostream.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000060#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000061using namespace llvm;
62
Chandler Carruth964daaa2014-04-22 02:55:47 +000063#define DEBUG_TYPE "loop-idiom"
64
Chandler Carruth099f5cb02012-11-02 08:33:25 +000065STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
66STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +000067
68namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000069
Chandler Carruthbad690e2015-08-12 23:06:37 +000070class LoopIdiomRecognize : public LoopPass {
71 Loop *CurLoop;
72 DominatorTree *DT;
73 ScalarEvolution *SE;
74 TargetLibraryInfo *TLI;
75 const TargetTransformInfo *TTI;
Chris Lattner81ae3f22010-12-26 19:39:38 +000076
Chandler Carruthbad690e2015-08-12 23:06:37 +000077public:
78 static char ID;
79 explicit LoopIdiomRecognize() : LoopPass(ID) {
80 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
81 DT = nullptr;
82 SE = nullptr;
83 TLI = nullptr;
84 TTI = nullptr;
85 }
Chris Lattner81ae3f22010-12-26 19:39:38 +000086
Chandler Carruthbad690e2015-08-12 23:06:37 +000087 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Shuxin Yang95de7c32012-12-09 03:12:46 +000088
Chandler Carruthbad690e2015-08-12 23:06:37 +000089 /// This transformation requires natural loop information & requires that
90 /// loop preheaders be inserted into the CFG.
91 ///
92 void getAnalysisUsage(AnalysisUsage &AU) const override {
93 AU.addRequired<LoopInfoWrapperPass>();
94 AU.addPreserved<LoopInfoWrapperPass>();
95 AU.addRequiredID(LoopSimplifyID);
96 AU.addPreservedID(LoopSimplifyID);
97 AU.addRequiredID(LCSSAID);
98 AU.addPreservedID(LCSSAID);
99 AU.addRequired<AliasAnalysis>();
100 AU.addPreserved<AliasAnalysis>();
101 AU.addRequired<ScalarEvolution>();
102 AU.addPreserved<ScalarEvolution>();
103 AU.addPreserved<DominatorTreeWrapperPass>();
104 AU.addRequired<DominatorTreeWrapperPass>();
105 AU.addRequired<TargetLibraryInfoWrapperPass>();
106 AU.addRequired<TargetTransformInfoWrapperPass>();
107 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000108
Chandler Carruthbad690e2015-08-12 23:06:37 +0000109 DominatorTree *getDominatorTree() {
110 return DT ? DT
111 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
112 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000113
Chandler Carruthbad690e2015-08-12 23:06:37 +0000114 ScalarEvolution *getScalarEvolution() {
115 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
116 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000117
Chandler Carruthbad690e2015-08-12 23:06:37 +0000118 TargetLibraryInfo *getTargetLibraryInfo() {
119 if (!TLI)
120 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000121
Chandler Carruthbad690e2015-08-12 23:06:37 +0000122 return TLI;
123 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000124
Chandler Carruthbad690e2015-08-12 23:06:37 +0000125 const TargetTransformInfo *getTargetTransformInfo() {
126 return TTI ? TTI
127 : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
128 *CurLoop->getHeader()->getParent()));
129 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000130
Chandler Carruthbad690e2015-08-12 23:06:37 +0000131 Loop *getLoop() const { return CurLoop; }
132
133private:
Chandler Carruthd9c60702015-08-13 00:10:03 +0000134 /// \name Countable Loop Idiom Handling
135 /// @{
136
Chandler Carruthbad690e2015-08-12 23:06:37 +0000137 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000138 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
139 SmallVectorImpl<BasicBlock *> &ExitBlocks);
140
141 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
142 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
143
144 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
145 unsigned StoreAlignment, Value *SplatValue,
146 Instruction *TheStore, const SCEVAddRecExpr *Ev,
147 const SCEV *BECount);
148 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
149 const SCEVAddRecExpr *StoreEv,
150 const SCEVAddRecExpr *LoadEv,
151 const SCEV *BECount);
152
153 /// @}
154 /// \name Noncountable Loop Idiom Handling
155 /// @{
156
157 bool runOnNoncountableLoop();
158
Chandler Carruth8219a502015-08-13 00:44:29 +0000159 bool recognizePopcount();
160 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
161 PHINode *CntPhi, Value *Var);
162
Chandler Carruthd9c60702015-08-13 00:10:03 +0000163 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000164};
165
166} // End anonymous namespace.
Chris Lattner81ae3f22010-12-26 19:39:38 +0000167
168char LoopIdiomRecognize::ID = 0;
169INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
170 false, false)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000171INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000172INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000173INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
174INITIALIZE_PASS_DEPENDENCY(LCSSA)
175INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000176INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chris Lattnercb18bfa2010-12-27 18:39:08 +0000177INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chandler Carruth705b1852015-01-31 03:43:40 +0000178INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000179INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
180 false, false)
181
182Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
183
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000184/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000185/// and zero out all the operands of this instruction. If any of them become
186/// dead, delete them and the computation tree that feeds them.
187///
Benjamin Kramerf094d772015-02-07 21:37:08 +0000188static void deleteDeadInstruction(Instruction *I,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000189 const TargetLibraryInfo *TLI) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000190 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
191 I->replaceAllUsesWith(UndefValue::get(I->getType()));
192 I->eraseFromParent();
193 for (Value *Op : Operands)
194 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000195}
196
Shuxin Yang95de7c32012-12-09 03:12:46 +0000197//===----------------------------------------------------------------------===//
198//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000199// Implementation of LoopIdiomRecognize
200//
201//===----------------------------------------------------------------------===//
202
Chandler Carruthd9c60702015-08-13 00:10:03 +0000203bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
204 if (skipOptnoneFunction(L))
205 return false;
206
207 CurLoop = L;
208
209 // If the loop could not be converted to canonical form, it must have an
210 // indirectbr in it, just give up.
211 if (!L->getLoopPreheader())
212 return false;
213
214 // Disable loop idiom recognition if the function's name is a common idiom.
215 StringRef Name = L->getHeader()->getParent()->getName();
216 if (Name == "memset" || Name == "memcpy")
217 return false;
218
219 SE = &getAnalysis<ScalarEvolution>();
220 if (SE->hasLoopInvariantBackedgeTakenCount(L))
221 return runOnCountableLoop();
222 return runOnNoncountableLoop();
223}
224
Shuxin Yang95de7c32012-12-09 03:12:46 +0000225bool LoopIdiomRecognize::runOnCountableLoop() {
226 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000227 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000228 "runOnCountableLoop() called on a loop without a predictable"
229 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000230
231 // If this loop executes exactly one time, then it should be peeled, not
232 // optimized by this pass.
233 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
234 if (BECst->getValue()->getValue() == 0)
235 return false;
236
Matt Arsenaultfb183232013-07-22 18:59:58 +0000237 // set DT
Shuxin Yang98c844f2013-01-02 18:26:31 +0000238 (void)getDominatorTree();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000239
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000240 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000241 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000242
Matt Arsenaultfb183232013-07-22 18:59:58 +0000243 // set TLI
Shuxin Yang98c844f2013-01-02 18:26:31 +0000244 (void)getTargetLibraryInfo();
Shuxin Yang95de7c32012-12-09 03:12:46 +0000245
Chandler Carruthbad690e2015-08-12 23:06:37 +0000246 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000247 CurLoop->getUniqueExitBlocks(ExitBlocks);
248
249 DEBUG(dbgs() << "loop-idiom Scanning: F["
Chandler Carruthbad690e2015-08-12 23:06:37 +0000250 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
251 << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000252
253 bool MadeChange = false;
254 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000255 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000256 // Ignore blocks in subloops.
Davide Italiano80625af2015-05-13 19:51:21 +0000257 if (LI.getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000258 continue;
259
Davide Italiano80625af2015-05-13 19:51:21 +0000260 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000261 }
262 return MadeChange;
263}
264
Chris Lattner8455b6e2011-01-02 19:01:03 +0000265/// runOnLoopBlock - Process the specified block, which lives in a counted loop
266/// with the specified backedge count. This block is known to be in the current
267/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000268bool LoopIdiomRecognize::runOnLoopBlock(
269 BasicBlock *BB, const SCEV *BECount,
270 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000271 // We can only promote stores in this block if they are unconditionally
272 // executed in the loop. For a block to be unconditionally executed, it has
273 // to dominate all the exit blocks of the loop. Verify this now.
274 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
275 if (!DT->dominates(BB, ExitBlocks[i]))
276 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000277
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000278 bool MadeChange = false;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000279 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000280 Instruction *Inst = I++;
281 // Look for store instructions, which may be optimized to memset/memcpy.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000282 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnera62b01d2011-01-04 07:27:30 +0000283 WeakVH InstPtr(I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000284 if (!processLoopStore(SI, BECount))
285 continue;
Chris Lattnera62b01d2011-01-04 07:27:30 +0000286 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000287
Chris Lattnera62b01d2011-01-04 07:27:30 +0000288 // If processing the store invalidated our iterator, start over from the
Chris Lattner86438102011-01-04 07:46:33 +0000289 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000290 if (!InstPtr)
Chris Lattnera62b01d2011-01-04 07:27:30 +0000291 I = BB->begin();
292 continue;
293 }
Andrew Trick328b2232011-03-14 16:48:10 +0000294
Chris Lattner86438102011-01-04 07:46:33 +0000295 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000296 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Chris Lattner86438102011-01-04 07:46:33 +0000297 WeakVH InstPtr(I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000298 if (!processLoopMemSet(MSI, BECount))
299 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000300 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000301
Chris Lattner86438102011-01-04 07:46:33 +0000302 // If processing the memset invalidated our iterator, start over from the
303 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000304 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000305 I = BB->begin();
306 continue;
307 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000308 }
Andrew Trick328b2232011-03-14 16:48:10 +0000309
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000310 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000311}
312
Chris Lattner86438102011-01-04 07:46:33 +0000313/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000314bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000315 if (!SI->isSimple())
316 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000317
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000318 Value *StoredVal = SI->getValueOperand();
Chris Lattner29e14ed2010-12-26 23:42:51 +0000319 Value *StorePtr = SI->getPointerOperand();
Andrew Trick328b2232011-03-14 16:48:10 +0000320
Chris Lattner65a699d2010-12-28 18:53:48 +0000321 // Reject stores that are so large that they overflow an unsigned.
Mehdi Amini46a43552015-03-04 18:43:29 +0000322 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
323 uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
Chris Lattner65a699d2010-12-28 18:53:48 +0000324 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000325 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000326
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000327 // See if the pointer expression is an AddRec like {base,+,1} on the current
328 // loop, which indicates a strided store. If we have something else, it's a
329 // random store we can't handle.
Chris Lattner85b6d812011-01-02 03:37:56 +0000330 const SCEVAddRecExpr *StoreEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000331 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Craig Topperf40110f2014-04-25 05:29:35 +0000332 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000333 return false;
334
335 // Check to see if the stride matches the size of the store. If so, then we
336 // know that every byte is touched in the loop.
Andrew Trick328b2232011-03-14 16:48:10 +0000337 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattner85b6d812011-01-02 03:37:56 +0000338 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000339
Craig Topperf40110f2014-04-25 05:29:35 +0000340 if (!Stride || StoreSize != Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000341 // TODO: Could also handle negative stride here someday, that will require
342 // the validity check in mayLoopAccessLocation to be updated though.
343 // Enable this to print exact negative strides.
Chris Lattner2333ac22011-02-21 17:02:55 +0000344 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
Chris Lattnerbc661d62011-02-21 02:08:54 +0000345 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
346 dbgs() << "BB: " << *SI->getParent();
347 }
Andrew Trick328b2232011-03-14 16:48:10 +0000348
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000349 return false;
Chris Lattnerbc661d62011-02-21 02:08:54 +0000350 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000351
352 // See if we can optimize just this store in isolation.
353 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
354 StoredVal, SI, StoreEv, BECount))
355 return true;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000356
Chris Lattner85b6d812011-01-02 03:37:56 +0000357 // If the stored value is a strided load in the same loop with the same stride
358 // this this may be transformable into a memcpy. This kicks in for stuff like
359 // for (i) A[i] = B[i];
360 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
361 const SCEVAddRecExpr *LoadEv =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000362 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
Chris Lattner85b6d812011-01-02 03:37:56 +0000363 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
Eli Friedman7c5dc122011-09-12 20:23:13 +0000364 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
Chris Lattner85b6d812011-01-02 03:37:56 +0000365 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
366 return true;
367 }
Chandler Carruthbad690e2015-08-12 23:06:37 +0000368 // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000369
Chris Lattner81ae3f22010-12-26 19:39:38 +0000370 return false;
371}
372
Chris Lattner86438102011-01-04 07:46:33 +0000373/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000374bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
375 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000376 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000377 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
378 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000379
Chris Lattnere6b261f2011-02-18 22:22:15 +0000380 // If we're not allowed to hack on memset, we fail.
381 if (!TLI->has(LibFunc::memset))
382 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000383
Chris Lattner86438102011-01-04 07:46:33 +0000384 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000385
Chris Lattner86438102011-01-04 07:46:33 +0000386 // See if the pointer expression is an AddRec like {base,+,1} on the current
387 // loop, which indicates a strided store. If we have something else, it's a
388 // random store we can't handle.
389 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000390 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000391 return false;
392
393 // Reject memsets that are so large that they overflow an unsigned.
394 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
395 if ((SizeInBytes >> 32) != 0)
396 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000397
Chris Lattner86438102011-01-04 07:46:33 +0000398 // Check to see if the stride matches the size of the memset. If so, then we
399 // know that every byte is touched in the loop.
400 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
Andrew Trick328b2232011-03-14 16:48:10 +0000401
Chris Lattner86438102011-01-04 07:46:33 +0000402 // TODO: Could also handle negative stride here someday, that will require the
403 // validity check in mayLoopAccessLocation to be updated though.
Craig Topperf40110f2014-04-25 05:29:35 +0000404 if (!Stride || MSI->getLength() != Stride->getValue())
Chris Lattner86438102011-01-04 07:46:33 +0000405 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000406
Chris Lattner0f4a6402011-02-19 19:31:39 +0000407 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Chandler Carruthbad690e2015-08-12 23:06:37 +0000408 MSI->getAlignment(), MSI->getValue(), MSI, Ev,
409 BECount);
Chris Lattner86438102011-01-04 07:46:33 +0000410}
411
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000412/// mayLoopAccessLocation - Return true if the specified loop might access the
413/// specified pointer location, which is a loop-strided access. The 'Access'
414/// argument specifies what the verboten forms of access are (read or write).
Chandler Carruth194f59c2015-07-22 23:15:57 +0000415static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
416 const SCEV *BECount, unsigned StoreSize,
417 AliasAnalysis &AA,
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000418 Instruction *IgnoredStore) {
419 // Get the location that may be stored across the loop. Since the access is
420 // strided positively through memory, we say that the modified location starts
421 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000422 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000423
424 // If the loop iterates a fixed number of times, we can refine the access size
425 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
426 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000427 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000428
429 // TODO: For this to be really effective, we have to dive into the pointer
430 // operand in the store. Store to &A[i] of 100 will always return may alias
431 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
432 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000433 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000434
435 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
436 ++BI)
437 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Chandler Carruthbad690e2015-08-12 23:06:37 +0000438 if (&*I != IgnoredStore && (AA.getModRefInfo(I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000439 return true;
440
441 return false;
442}
443
Chris Lattner0f4a6402011-02-19 19:31:39 +0000444/// getMemSetPatternValue - If a strided store of the specified value is safe to
445/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
446/// be passed in. Otherwise, return null.
447///
448/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
449/// just replicate their input array and then pass on to memset_pattern16.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000450static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000451 // If the value isn't a constant, we can't promote it to being in a constant
452 // array. We could theoretically do a store to an alloca or something, but
453 // that doesn't seem worthwhile.
454 Constant *C = dyn_cast<Constant>(V);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000455 if (!C)
456 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000457
Chris Lattner0f4a6402011-02-19 19:31:39 +0000458 // Only handle simple values that are a power of two bytes in size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000459 uint64_t Size = DL.getTypeSizeInBits(V->getType());
Chandler Carruthbad690e2015-08-12 23:06:37 +0000460 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000461 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000462
Chris Lattner72a35fb2011-02-19 19:56:44 +0000463 // Don't care enough about darwin/ppc to implement this.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000464 if (DL.isBigEndian())
Craig Topperf40110f2014-04-25 05:29:35 +0000465 return nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000466
467 // Convert to size in bytes.
468 Size /= 8;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000469
Chris Lattner0f4a6402011-02-19 19:31:39 +0000470 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
Chris Lattner72a35fb2011-02-19 19:56:44 +0000471 // if the top and bottom are the same (e.g. for vectors and large integers).
Chandler Carruthbad690e2015-08-12 23:06:37 +0000472 if (Size > 16)
473 return nullptr;
Andrew Trick328b2232011-03-14 16:48:10 +0000474
Chris Lattner72a35fb2011-02-19 19:56:44 +0000475 // If the constant is exactly 16 bytes, just use it.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000476 if (Size == 16)
477 return C;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000478
Chris Lattner72a35fb2011-02-19 19:56:44 +0000479 // Otherwise, we'll use an array of the constants.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000480 unsigned ArraySize = 16 / Size;
Chris Lattner72a35fb2011-02-19 19:56:44 +0000481 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000482 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
Chris Lattner0f4a6402011-02-19 19:31:39 +0000483}
484
Chris Lattner0f4a6402011-02-19 19:31:39 +0000485/// processLoopStridedStore - We see a strided store of some value. If we can
486/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000487bool LoopIdiomRecognize::processLoopStridedStore(
488 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
489 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
490 const SCEV *BECount) {
Andrew Trick328b2232011-03-14 16:48:10 +0000491
Chris Lattner0f4a6402011-02-19 19:31:39 +0000492 // If the stored value is a byte-wise value (like i32 -1), then it may be
493 // turned into a memset of i8 -1, assuming that all the consecutive bytes
494 // are stored. A store of i32 0x01020304 can never be turned into a memset,
495 // but it can be turned into memset_pattern if the target supports it.
496 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000497 Constant *PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000498 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
Matt Arsenault009faed2013-09-11 05:09:42 +0000499 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
500
Chris Lattner0f4a6402011-02-19 19:31:39 +0000501 // If we're allowed to form a memset, and the stored value would be acceptable
502 // for memset, use it.
503 if (SplatValue && TLI->has(LibFunc::memset) &&
504 // Verify that the stored value is loop invariant. If not, we can't
505 // promote the memset.
506 CurLoop->isLoopInvariant(SplatValue)) {
507 // Keep and use SplatValue.
Craig Topperf40110f2014-04-25 05:29:35 +0000508 PatternValue = nullptr;
Mehdi Amini46a43552015-03-04 18:43:29 +0000509 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
510 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
Matt Arsenault009faed2013-09-11 05:09:42 +0000511 // Don't create memset_pattern16s with address spaces.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000512 // It looks like we can use PatternValue!
Craig Topperf40110f2014-04-25 05:29:35 +0000513 SplatValue = nullptr;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000514 } else {
515 // Otherwise, this isn't an idiom we can transform. For example, we can't
Eli Friedmana93ab132011-09-13 00:44:16 +0000516 // do anything with a 3-byte store.
Chris Lattnera3514442011-01-01 20:12:04 +0000517 return false;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000518 }
Andrew Trick328b2232011-03-14 16:48:10 +0000519
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000520 // The trip count of the loop and the base pointer of the addrec SCEV is
521 // guaranteed to be loop invariant, which means that it should dominate the
522 // header. This allows us to insert code for it in the preheader.
523 BasicBlock *Preheader = CurLoop->getLoopPreheader();
524 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000525 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000526
Matt Arsenault009faed2013-09-11 05:09:42 +0000527 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
528
Chris Lattner29e14ed2010-12-26 23:42:51 +0000529 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000530 // this into a memset in the loop preheader now if we want. However, this
531 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000532 // or write to the aliased location. Check for any overlap by generating the
533 // base pointer and checking the region.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000534 Value *BasePtr = Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
535 Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000536
Chandler Carruth194f59c2015-07-22 23:15:57 +0000537 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
538 getAnalysis<AliasAnalysis>(), 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.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000549 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
Chris Lattner0ba473c2011-01-04 00:06:55 +0000550 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000551
Chandler Carruthbad690e2015-08-12 23:06:37 +0000552 const SCEV *NumBytesS =
553 SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000554 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000555 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000556 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000557 }
Andrew Trick328b2232011-03-14 16:48:10 +0000558
559 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000560 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000561
Devang Pateld00c6282011-03-07 22:43:45 +0000562 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000563 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000564 NewCall =
565 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000566 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000567 // Everything is emitted in default address space
568 Type *Int8PtrTy = DestInt8PtrTy;
569
Chris Lattner0f4a6402011-02-19 19:31:39 +0000570 Module *M = TheStore->getParent()->getParent()->getParent();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000571 Value *MSP =
572 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
573 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
Andrew Trick328b2232011-03-14 16:48:10 +0000574
Chris Lattner0f4a6402011-02-19 19:31:39 +0000575 // Otherwise we should form a memset_pattern16. PatternValue is known to be
576 // an constant array of 16-bytes. Plop the value into a mergable global.
577 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000578 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000579 PatternValue, ".memset_pattern");
580 GV->setUnnamedAddr(true); // Ok to merge these.
581 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000582 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000583 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000584 }
Andrew Trick328b2232011-03-14 16:48:10 +0000585
Chris Lattner29e14ed2010-12-26 23:42:51 +0000586 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000587 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000588 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000589
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000590 // Okay, the memset has been formed. Zap the original store and anything that
591 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000592 deleteDeadInstruction(TheStore, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +0000593 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000594 return true;
595}
596
Chris Lattner85b6d812011-01-02 03:37:56 +0000597/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
598/// same-strided load.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000599bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
600 StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
601 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
Chris Lattnere6b261f2011-02-18 22:22:15 +0000602 // If we're not allowed to form memcpy, we fail.
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000603 if (!TLI->has(LibFunc::memcpy))
Chris Lattnere6b261f2011-02-18 22:22:15 +0000604 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000605
Chris Lattner85b6d812011-01-02 03:37:56 +0000606 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Andrew Trick328b2232011-03-14 16:48:10 +0000607
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000608 // The trip count of the loop and the base pointer of the addrec SCEV is
609 // guaranteed to be loop invariant, which means that it should dominate the
610 // header. This allows us to insert code for it in the preheader.
611 BasicBlock *Preheader = CurLoop->getLoopPreheader();
612 IRBuilder<> Builder(Preheader->getTerminator());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000613 const DataLayout &DL = Preheader->getModule()->getDataLayout();
614 SCEVExpander Expander(*SE, DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000615
Chris Lattner85b6d812011-01-02 03:37:56 +0000616 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000617 // this into a memcpy in the loop preheader now if we want. However, this
618 // would be unsafe to do if there is anything else in the loop that may read
619 // or write the memory region we're storing to. This includes the load that
620 // feeds the stores. Check for an alias by generating the base address and
621 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000622 Value *StoreBasePtr = Expander.expandCodeFor(
623 StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
624 Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000625
Chandler Carruth194f59c2015-07-22 23:15:57 +0000626 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
627 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000628 Expander.clear();
629 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000630 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000631 return false;
632 }
633
634 // For a memcpy, we have to make sure that the input array is not being
635 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000636 Value *LoadBasePtr = Expander.expandCodeFor(
637 LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
638 Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000639
Chandler Carruth194f59c2015-07-22 23:15:57 +0000640 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
641 getAnalysis<AliasAnalysis>(), SI)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000642 Expander.clear();
643 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000644 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
645 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000646 return false;
647 }
648
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000649 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000650
Chris Lattner85b6d812011-01-02 03:37:56 +0000651 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
652 // pointer size if it isn't already.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000653 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
Matt Arsenault009faed2013-09-11 05:09:42 +0000654 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +0000655
Chandler Carruthbad690e2015-08-12 23:06:37 +0000656 const SCEV *NumBytesS =
657 SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1), SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +0000658 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +0000659 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000660 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +0000661
Chris Lattner85b6d812011-01-02 03:37:56 +0000662 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000663 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000664
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000665 CallInst *NewCall =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000666 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
667 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +0000668 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000669
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000670 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +0000671 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
672 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000673
Chris Lattner85b6d812011-01-02 03:37:56 +0000674 // Okay, the memset has been formed. Zap the original store and anything that
675 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000676 deleteDeadInstruction(SI, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000677 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +0000678 return true;
679}
Chandler Carruthd9c60702015-08-13 00:10:03 +0000680
681bool LoopIdiomRecognize::runOnNoncountableLoop() {
Chandler Carruth8219a502015-08-13 00:44:29 +0000682 if (recognizePopcount())
Chandler Carruthd9c60702015-08-13 00:10:03 +0000683 return true;
684
685 return false;
686}
Chandler Carruth8219a502015-08-13 00:44:29 +0000687
688/// Check if the given conditional branch is based on the comparison between
689/// a variable and zero, and if the variable is non-zero, the control yields to
690/// the loop entry. If the branch matches the behavior, the variable involved
691/// in the comparion is returned. This function will be called to see if the
692/// precondition and postcondition of the loop are in desirable form.
693static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
694 if (!BI || !BI->isConditional())
695 return nullptr;
696
697 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
698 if (!Cond)
699 return nullptr;
700
701 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
702 if (!CmpZero || !CmpZero->isZero())
703 return nullptr;
704
705 ICmpInst::Predicate Pred = Cond->getPredicate();
706 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
707 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
708 return Cond->getOperand(0);
709
710 return nullptr;
711}
712
713/// Return true iff the idiom is detected in the loop.
714///
715/// Additionally:
716/// 1) \p CntInst is set to the instruction counting the population bit.
717/// 2) \p CntPhi is set to the corresponding phi node.
718/// 3) \p Var is set to the value whose population bits are being counted.
719///
720/// The core idiom we are trying to detect is:
721/// \code
722/// if (x0 != 0)
723/// goto loop-exit // the precondition of the loop
724/// cnt0 = init-val;
725/// do {
726/// x1 = phi (x0, x2);
727/// cnt1 = phi(cnt0, cnt2);
728///
729/// cnt2 = cnt1 + 1;
730/// ...
731/// x2 = x1 & (x1 - 1);
732/// ...
733/// } while(x != 0);
734///
735/// loop-exit:
736/// \endcode
737static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
738 Instruction *&CntInst, PHINode *&CntPhi,
739 Value *&Var) {
740 // step 1: Check to see if the look-back branch match this pattern:
741 // "if (a!=0) goto loop-entry".
742 BasicBlock *LoopEntry;
743 Instruction *DefX2, *CountInst;
744 Value *VarX1, *VarX0;
745 PHINode *PhiX, *CountPhi;
746
747 DefX2 = CountInst = nullptr;
748 VarX1 = VarX0 = nullptr;
749 PhiX = CountPhi = nullptr;
750 LoopEntry = *(CurLoop->block_begin());
751
752 // step 1: Check if the loop-back branch is in desirable form.
753 {
754 if (Value *T = matchCondition(
755 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
756 DefX2 = dyn_cast<Instruction>(T);
757 else
758 return false;
759 }
760
761 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
762 {
763 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
764 return false;
765
766 BinaryOperator *SubOneOp;
767
768 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
769 VarX1 = DefX2->getOperand(1);
770 else {
771 VarX1 = DefX2->getOperand(0);
772 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
773 }
774 if (!SubOneOp)
775 return false;
776
777 Instruction *SubInst = cast<Instruction>(SubOneOp);
778 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
779 if (!Dec ||
780 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
781 (SubInst->getOpcode() == Instruction::Add &&
782 Dec->isAllOnesValue()))) {
783 return false;
784 }
785 }
786
787 // step 3: Check the recurrence of variable X
788 {
789 PhiX = dyn_cast<PHINode>(VarX1);
790 if (!PhiX ||
791 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
792 return false;
793 }
794 }
795
796 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
797 {
798 CountInst = nullptr;
799 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
800 IterE = LoopEntry->end();
801 Iter != IterE; Iter++) {
802 Instruction *Inst = Iter;
803 if (Inst->getOpcode() != Instruction::Add)
804 continue;
805
806 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
807 if (!Inc || !Inc->isOne())
808 continue;
809
810 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
811 if (!Phi || Phi->getParent() != LoopEntry)
812 continue;
813
814 // Check if the result of the instruction is live of the loop.
815 bool LiveOutLoop = false;
816 for (User *U : Inst->users()) {
817 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
818 LiveOutLoop = true;
819 break;
820 }
821 }
822
823 if (LiveOutLoop) {
824 CountInst = Inst;
825 CountPhi = Phi;
826 break;
827 }
828 }
829
830 if (!CountInst)
831 return false;
832 }
833
834 // step 5: check if the precondition is in this form:
835 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
836 {
837 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
838 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
839 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
840 return false;
841
842 CntInst = CountInst;
843 CntPhi = CountPhi;
844 Var = T;
845 }
846
847 return true;
848}
849
850/// Recognizes a population count idiom in a non-countable loop.
851///
852/// If detected, transforms the relevant code to issue the popcount intrinsic
853/// function call, and returns true; otherwise, returns false.
854bool LoopIdiomRecognize::recognizePopcount() {
855 (void)getScalarEvolution();
856 (void)getTargetLibraryInfo();
857 (void)getTargetTransformInfo();
858
859 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
860 return false;
861
862 // Counting population are usually conducted by few arithmetic instructions.
863 // Such instructions can be easilly "absorbed" by vacant slots in a
864 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
865 // in a compact loop.
866
867 // Give up if the loop has multiple blocks or multiple backedges.
868 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
869 return false;
870
871 BasicBlock *LoopBody = *(CurLoop->block_begin());
872 if (LoopBody->size() >= 20) {
873 // The loop is too big, bail out.
874 return false;
875 }
876
877 // It should have a preheader containing nothing but an unconditional branch.
878 BasicBlock *PH = CurLoop->getLoopPreheader();
879 if (!PH)
880 return false;
881 if (&PH->front() != PH->getTerminator())
882 return false;
883 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
884 if (!EntryBI || EntryBI->isConditional())
885 return false;
886
887 // It should have a precondition block where the generated popcount instrinsic
888 // function can be inserted.
889 auto *PreCondBB = PH->getSinglePredecessor();
890 if (!PreCondBB)
891 return false;
892 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
893 if (!PreCondBI || PreCondBI->isUnconditional())
894 return false;
895
896 Instruction *CntInst;
897 PHINode *CntPhi;
898 Value *Val;
899 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
900 return false;
901
902 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
903 return true;
904}
905
906static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
907 DebugLoc DL) {
908 Value *Ops[] = {Val};
909 Type *Tys[] = {Val->getType()};
910
911 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
912 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
913 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
914 CI->setDebugLoc(DL);
915
916 return CI;
917}
918
919void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
920 Instruction *CntInst,
921 PHINode *CntPhi, Value *Var) {
922 BasicBlock *PreHead = CurLoop->getLoopPreheader();
923 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
924 const DebugLoc DL = CntInst->getDebugLoc();
925
926 // Assuming before transformation, the loop is following:
927 // if (x) // the precondition
928 // do { cnt++; x &= x - 1; } while(x);
929
930 // Step 1: Insert the ctpop instruction at the end of the precondition block
931 IRBuilder<> Builder(PreCondBr);
932 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
933 {
934 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
935 NewCount = PopCntZext =
936 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
937
938 if (NewCount != PopCnt)
939 (cast<Instruction>(NewCount))->setDebugLoc(DL);
940
941 // TripCnt is exactly the number of iterations the loop has
942 TripCnt = NewCount;
943
944 // If the population counter's initial value is not zero, insert Add Inst.
945 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
946 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
947 if (!InitConst || !InitConst->isZero()) {
948 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
949 (cast<Instruction>(NewCount))->setDebugLoc(DL);
950 }
951 }
952
953 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
954 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
955 // function would be partial dead code, and downstream passes will drag
956 // it back from the precondition block to the preheader.
957 {
958 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
959
960 Value *Opnd0 = PopCntZext;
961 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
962 if (PreCond->getOperand(0) != Var)
963 std::swap(Opnd0, Opnd1);
964
965 ICmpInst *NewPreCond = cast<ICmpInst>(
966 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
967 PreCondBr->setCondition(NewPreCond);
968
969 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
970 }
971
972 // Step 3: Note that the population count is exactly the trip count of the
973 // loop in question, which enble us to to convert the loop from noncountable
974 // loop into a countable one. The benefit is twofold:
975 //
976 // - If the loop only counts population, the entire loop become dead after
977 // the transformation. It is lots easier to prove a countable loop dead
978 // than to prove a noncountable one. (In some C dialects, a infite loop
979 // isn't dead even if it computes nothing useful. In general, DCE needs
980 // to prove a noncountable loop finite before safely delete it.)
981 //
982 // - If the loop also performs something else, it remains alive.
983 // Since it is transformed to countable form, it can be aggressively
984 // optimized by some optimizations which are in general not applicable
985 // to a noncountable loop.
986 //
987 // After this step, this loop (conceptually) would look like following:
988 // newcnt = __builtin_ctpop(x);
989 // t = newcnt;
990 // if (x)
991 // do { cnt++; x &= x-1; t--) } while (t > 0);
992 BasicBlock *Body = *(CurLoop->block_begin());
993 {
994 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
995 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
996 Type *Ty = TripCnt->getType();
997
998 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
999
1000 Builder.SetInsertPoint(LbCond);
1001 Value *Opnd1 = cast<Value>(TcPhi);
1002 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
1003 Instruction *TcDec = cast<Instruction>(
1004 Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
1005
1006 TcPhi->addIncoming(TripCnt, PreHead);
1007 TcPhi->addIncoming(TcDec, Body);
1008
1009 CmpInst::Predicate Pred =
1010 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1011 LbCond->setPredicate(Pred);
1012 LbCond->setOperand(0, TcDec);
1013 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
1014 }
1015
1016 // Step 4: All the references to the original population counter outside
1017 // the loop are replaced with the NewCount -- the value returned from
1018 // __builtin_ctpop().
1019 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1020
1021 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1022 // loop. The loop would otherwise not be deleted even if it becomes empty.
1023 SE->forgetLoop(CurLoop);
1024}