blob: 48d5ae88cda91faa3ade4a63122767d6c43c5bd1 [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//
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +000014// If compiling for code size we avoid idiom recognition if the resulting
15// code could be larger than the code for the original loop. One way this could
16// happen is if the loop is not removable after idiom recognition due to the
17// presence of non-idiom instructions. The initial implementation of the
18// heuristics applies to idioms in multi-block loops.
19//
Chris Lattner81ae3f22010-12-26 19:39:38 +000020//===----------------------------------------------------------------------===//
Chris Lattner0469e012011-01-02 18:32:09 +000021//
22// TODO List:
23//
24// Future loop memory idioms to recognize:
Chandler Carruth099f5cb02012-11-02 08:33:25 +000025// memcmp, memmove, strlen, etc.
Chris Lattner0469e012011-01-02 18:32:09 +000026// Future floating point idioms to recognize in -ffast-math mode:
27// fpowi
28// Future integer operation idioms to recognize:
29// ctpop, ctlz, cttz
30//
31// Beware that isel's default lowering for ctpop is highly inefficient for
32// i64 and larger types when i64 is legal and the value has few bits set. It
33// would be good to enhance isel to emit a loop for ctpop in this case.
34//
Chris Lattner02a97762011-01-03 01:10:08 +000035// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000036// replace them with calls to BLAS (if linked in??).
37//
Chris Lattner0469e012011-01-02 18:32:09 +000038//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000039
Dehao Chenb9f8e292016-07-12 18:45:51 +000040#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000041#include "llvm/ADT/MapVector.h"
42#include "llvm/ADT/SetVector.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000044#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000045#include "llvm/Analysis/BasicAliasAnalysis.h"
46#include "llvm/Analysis/GlobalsModRef.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000047#include "llvm/Analysis/LoopAccessAnalysis.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000048#include "llvm/Analysis/LoopPass.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chad Rosiera15b4b62015-11-23 21:09:13 +000050#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000051#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000053#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000054#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/IRBuilder.h"
58#include "llvm/IR/IntrinsicInst.h"
59#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000060#include "llvm/Support/Debug.h"
61#include "llvm/Support/raw_ostream.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000062#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000063#include "llvm/Transforms/Scalar/LoopPassManager.h"
Ahmed Bougachaace97c12016-04-27 19:04:50 +000064#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000065#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000066#include "llvm/Transforms/Utils/LoopUtils.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000067using namespace llvm;
68
Chandler Carruth964daaa2014-04-22 02:55:47 +000069#define DEBUG_TYPE "loop-idiom"
70
Chandler Carruth099f5cb02012-11-02 08:33:25 +000071STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
72STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +000073
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +000074static cl::opt<bool> UseLIRCodeSizeHeurs(
75 "use-lir-code-size-heurs",
76 cl::desc("Use loop idiom recognition code size heuristics when compiling"
77 "with -Os/-Oz"),
78 cl::init(true), cl::Hidden);
79
Chris Lattner81ae3f22010-12-26 19:39:38 +000080namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000081
Dehao Chenb9f8e292016-07-12 18:45:51 +000082class LoopIdiomRecognize {
Chandler Carruthbad690e2015-08-12 23:06:37 +000083 Loop *CurLoop;
Chandler Carruthbf143e22015-08-14 00:21:10 +000084 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +000085 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +000086 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +000087 ScalarEvolution *SE;
88 TargetLibraryInfo *TLI;
89 const TargetTransformInfo *TTI;
Chad Rosier43f9b482015-11-06 16:33:57 +000090 const DataLayout *DL;
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +000091 bool ApplyCodeSizeHeuristics;
Chris Lattner81ae3f22010-12-26 19:39:38 +000092
Chandler Carruthbad690e2015-08-12 23:06:37 +000093public:
Dehao Chenb9f8e292016-07-12 18:45:51 +000094 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
95 LoopInfo *LI, ScalarEvolution *SE,
96 TargetLibraryInfo *TLI,
97 const TargetTransformInfo *TTI,
98 const DataLayout *DL)
99 : CurLoop(nullptr), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI),
100 DL(DL) {}
Chris Lattner81ae3f22010-12-26 19:39:38 +0000101
Dehao Chenb9f8e292016-07-12 18:45:51 +0000102 bool runOnLoop(Loop *L);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000103
Chandler Carruthbad690e2015-08-12 23:06:37 +0000104private:
Chad Rosiercc9030b2015-11-11 23:00:59 +0000105 typedef SmallVector<StoreInst *, 8> StoreList;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000106 typedef MapVector<Value *, StoreList> StoreListMap;
107 StoreListMap StoreRefsForMemset;
108 StoreListMap StoreRefsForMemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000109 StoreList StoreRefsForMemcpy;
110 bool HasMemset;
111 bool HasMemsetPattern;
112 bool HasMemcpy;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000113
Chandler Carruthd9c60702015-08-13 00:10:03 +0000114 /// \name Countable Loop Idiom Handling
115 /// @{
116
Chandler Carruthbad690e2015-08-12 23:06:37 +0000117 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000118 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
119 SmallVectorImpl<BasicBlock *> &ExitBlocks);
120
Chad Rosiercc9030b2015-11-11 23:00:59 +0000121 void collectStores(BasicBlock *BB);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000122 bool isLegalStore(StoreInst *SI, bool &ForMemset, bool &ForMemsetPattern,
123 bool &ForMemcpy);
124 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
125 bool ForMemset);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000126 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
127
128 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000129 unsigned StoreAlignment, Value *StoredVal,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000130 Instruction *TheStore,
131 SmallPtrSetImpl<Instruction *> &Stores,
132 const SCEVAddRecExpr *Ev, const SCEV *BECount,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000133 bool NegStride, bool IsLoopMemset = false);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000134 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000135 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
136 bool IsLoopMemset = false);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000137
138 /// @}
139 /// \name Noncountable Loop Idiom Handling
140 /// @{
141
142 bool runOnNoncountableLoop();
143
Chandler Carruth8219a502015-08-13 00:44:29 +0000144 bool recognizePopcount();
145 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
146 PHINode *CntPhi, Value *Var);
147
Chandler Carruthd9c60702015-08-13 00:10:03 +0000148 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000149};
150
Dehao Chenb9f8e292016-07-12 18:45:51 +0000151class LoopIdiomRecognizeLegacyPass : public LoopPass {
152public:
153 static char ID;
154 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
155 initializeLoopIdiomRecognizeLegacyPassPass(
156 *PassRegistry::getPassRegistry());
157 }
158
159 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
160 if (skipLoop(L))
161 return false;
162
163 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
164 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
165 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
166 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
167 TargetLibraryInfo *TLI =
168 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
169 const TargetTransformInfo *TTI =
170 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
171 *L->getHeader()->getParent());
172 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
173
174 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
175 return LIR.runOnLoop(L);
176 }
177
178 /// This transformation requires natural loop information & requires that
179 /// loop preheaders be inserted into the CFG.
180 ///
181 void getAnalysisUsage(AnalysisUsage &AU) const override {
182 AU.addRequired<TargetLibraryInfoWrapperPass>();
183 AU.addRequired<TargetTransformInfoWrapperPass>();
184 getLoopAnalysisUsage(AU);
185 }
186};
Chandler Carruthbad690e2015-08-12 23:06:37 +0000187} // End anonymous namespace.
Chris Lattner81ae3f22010-12-26 19:39:38 +0000188
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000189PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
190 LoopStandardAnalysisResults &AR,
191 LPMUpdater &) {
Dehao Chenb9f8e292016-07-12 18:45:51 +0000192 const auto *DL = &L.getHeader()->getModule()->getDataLayout();
Dehao Chenb9f8e292016-07-12 18:45:51 +0000193
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000194 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, DL);
Dehao Chenb9f8e292016-07-12 18:45:51 +0000195 if (!LIR.runOnLoop(&L))
196 return PreservedAnalyses::all();
197
198 return getLoopPassPreservedAnalyses();
199}
200
201char LoopIdiomRecognizeLegacyPass::ID = 0;
202INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
203 "Recognize loop idioms", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000204INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000205INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000206INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Dehao Chenb9f8e292016-07-12 18:45:51 +0000207INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
208 "Recognize loop idioms", false, false)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000209
Dehao Chenb9f8e292016-07-12 18:45:51 +0000210Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
Chris Lattner81ae3f22010-12-26 19:39:38 +0000211
David Majnemerc5601df2016-06-20 16:03:25 +0000212static void deleteDeadInstruction(Instruction *I) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000213 I->replaceAllUsesWith(UndefValue::get(I->getType()));
214 I->eraseFromParent();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000215}
216
Shuxin Yang95de7c32012-12-09 03:12:46 +0000217//===----------------------------------------------------------------------===//
218//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000219// Implementation of LoopIdiomRecognize
220//
221//===----------------------------------------------------------------------===//
222
Dehao Chenb9f8e292016-07-12 18:45:51 +0000223bool LoopIdiomRecognize::runOnLoop(Loop *L) {
Chandler Carruthd9c60702015-08-13 00:10:03 +0000224 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000225 // If the loop could not be converted to canonical form, it must have an
226 // indirectbr in it, just give up.
227 if (!L->getLoopPreheader())
228 return false;
229
230 // Disable loop idiom recognition if the function's name is a common idiom.
231 StringRef Name = L->getHeader()->getParent()->getName();
232 if (Name == "memset" || Name == "memcpy")
233 return false;
234
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000235 // Determine if code size heuristics need to be applied.
236 ApplyCodeSizeHeuristics =
237 L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs;
238
David L. Jonesd21529f2017-01-23 23:16:46 +0000239 HasMemset = TLI->has(LibFunc_memset);
240 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
241 HasMemcpy = TLI->has(LibFunc_memcpy);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000242
243 if (HasMemset || HasMemsetPattern || HasMemcpy)
244 if (SE->hasLoopInvariantBackedgeTakenCount(L))
245 return runOnCountableLoop();
Chandler Carruthdc298322015-08-13 01:03:26 +0000246
Chandler Carruthd9c60702015-08-13 00:10:03 +0000247 return runOnNoncountableLoop();
248}
249
Shuxin Yang95de7c32012-12-09 03:12:46 +0000250bool LoopIdiomRecognize::runOnCountableLoop() {
251 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000252 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000253 "runOnCountableLoop() called on a loop without a predictable"
254 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000255
256 // If this loop executes exactly one time, then it should be peeled, not
257 // optimized by this pass.
258 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000259 if (BECst->getAPInt() == 0)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000260 return false;
261
Chandler Carruthbad690e2015-08-12 23:06:37 +0000262 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000263 CurLoop->getUniqueExitBlocks(ExitBlocks);
264
265 DEBUG(dbgs() << "loop-idiom Scanning: F["
Chandler Carruthbad690e2015-08-12 23:06:37 +0000266 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
267 << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000268
269 bool MadeChange = false;
Haicheng Wua95cd1262016-07-06 21:05:40 +0000270
271 // The following transforms hoist stores/memsets into the loop pre-header.
272 // Give up if the loop has instructions may throw.
273 LoopSafetyInfo SafetyInfo;
274 computeLoopSafetyInfo(&SafetyInfo, CurLoop);
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +0000275 if (SafetyInfo.MayThrow)
Haicheng Wua95cd1262016-07-06 21:05:40 +0000276 return MadeChange;
277
Shuxin Yang95de7c32012-12-09 03:12:46 +0000278 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000279 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000280 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000281 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000282 continue;
283
Davide Italiano80625af2015-05-13 19:51:21 +0000284 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000285 }
286 return MadeChange;
287}
288
Chad Rosiera548fe52015-11-12 19:09:16 +0000289static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
290 uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
291 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
292 "Don't overflow unsigned.");
293 return (unsigned)SizeInBits >> 3;
294}
295
Chad Rosier4acff962016-02-12 19:05:27 +0000296static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
Chad Rosiera548fe52015-11-12 19:09:16 +0000297 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
Chad Rosier4acff962016-02-12 19:05:27 +0000298 return ConstStride->getAPInt();
Chad Rosiera548fe52015-11-12 19:09:16 +0000299}
300
Chad Rosier94274fb2015-12-21 14:49:32 +0000301/// getMemSetPatternValue - If a strided store of the specified value is safe to
302/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
303/// be passed in. Otherwise, return null.
304///
305/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
306/// just replicate their input array and then pass on to memset_pattern16.
307static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
308 // If the value isn't a constant, we can't promote it to being in a constant
309 // array. We could theoretically do a store to an alloca or something, but
310 // that doesn't seem worthwhile.
311 Constant *C = dyn_cast<Constant>(V);
312 if (!C)
313 return nullptr;
314
315 // Only handle simple values that are a power of two bytes in size.
316 uint64_t Size = DL->getTypeSizeInBits(V->getType());
317 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
318 return nullptr;
319
320 // Don't care enough about darwin/ppc to implement this.
321 if (DL->isBigEndian())
322 return nullptr;
323
324 // Convert to size in bytes.
325 Size /= 8;
326
327 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
328 // if the top and bottom are the same (e.g. for vectors and large integers).
329 if (Size > 16)
330 return nullptr;
331
332 // If the constant is exactly 16 bytes, just use it.
333 if (Size == 16)
334 return C;
335
336 // Otherwise, we'll use an array of the constants.
337 unsigned ArraySize = 16 / Size;
338 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
339 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
340}
341
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000342bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000343 bool &ForMemsetPattern, bool &ForMemcpy) {
Chad Rosier869962f2015-12-01 14:26:35 +0000344 // Don't touch volatile stores.
345 if (!SI->isSimple())
346 return false;
347
Sanjoy Das206f65c2017-04-24 20:12:10 +0000348 // Don't convert stores of non-integral pointer types to memsets (which stores
349 // integers).
350 if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType()))
351 return false;
352
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000353 // Avoid merging nontemporal stores.
354 if (SI->getMetadata(LLVMContext::MD_nontemporal))
355 return false;
356
Chad Rosiera548fe52015-11-12 19:09:16 +0000357 Value *StoredVal = SI->getValueOperand();
358 Value *StorePtr = SI->getPointerOperand();
359
360 // Reject stores that are so large that they overflow an unsigned.
361 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
362 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
363 return false;
364
365 // See if the pointer expression is an AddRec like {base,+,1} on the current
366 // loop, which indicates a strided store. If we have something else, it's a
367 // random store we can't handle.
368 const SCEVAddRecExpr *StoreEv =
369 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
370 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
371 return false;
372
373 // Check to see if we have a constant stride.
374 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
375 return false;
376
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000377 // See if the store can be turned into a memset.
378
379 // If the stored value is a byte-wise value (like i32 -1), then it may be
380 // turned into a memset of i8 -1, assuming that all the consecutive bytes
381 // are stored. A store of i32 0x01020304 can never be turned into a memset,
382 // but it can be turned into memset_pattern if the target supports it.
383 Value *SplatValue = isBytewiseValue(StoredVal);
384 Constant *PatternValue = nullptr;
385
386 // If we're allowed to form a memset, and the stored value would be
387 // acceptable for memset, use it.
388 if (HasMemset && SplatValue &&
389 // Verify that the stored value is loop invariant. If not, we can't
390 // promote the memset.
391 CurLoop->isLoopInvariant(SplatValue)) {
392 // It looks like we can use SplatValue.
393 ForMemset = true;
394 return true;
395 } else if (HasMemsetPattern &&
396 // Don't create memset_pattern16s with address spaces.
397 StorePtr->getType()->getPointerAddressSpace() == 0 &&
398 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
399 // It looks like we can use PatternValue!
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000400 ForMemsetPattern = true;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000401 return true;
402 }
403
404 // Otherwise, see if the store can be turned into a memcpy.
405 if (HasMemcpy) {
406 // Check to see if the stride matches the size of the store. If so, then we
407 // know that every byte is touched in the loop.
Chad Rosier4acff962016-02-12 19:05:27 +0000408 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000409 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
410 if (StoreSize != Stride && StoreSize != -Stride)
411 return false;
412
413 // The store must be feeding a non-volatile load.
414 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
415 if (!LI || !LI->isSimple())
416 return false;
417
418 // See if the pointer expression is an AddRec like {base,+,1} on the current
419 // loop, which indicates a strided load. If we have something else, it's a
420 // random load we can't handle.
421 const SCEVAddRecExpr *LoadEv =
422 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
423 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
424 return false;
425
426 // The store and load must share the same stride.
427 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
428 return false;
429
430 // Success. This store can be converted into a memcpy.
431 ForMemcpy = true;
432 return true;
433 }
434 // This store can't be transformed into a memset/memcpy.
435 return false;
Chad Rosiera548fe52015-11-12 19:09:16 +0000436}
437
Chad Rosiercc9030b2015-11-11 23:00:59 +0000438void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000439 StoreRefsForMemset.clear();
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000440 StoreRefsForMemsetPattern.clear();
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000441 StoreRefsForMemcpy.clear();
Chad Rosiercc9030b2015-11-11 23:00:59 +0000442 for (Instruction &I : *BB) {
443 StoreInst *SI = dyn_cast<StoreInst>(&I);
444 if (!SI)
445 continue;
446
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000447 bool ForMemset = false;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000448 bool ForMemsetPattern = false;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000449 bool ForMemcpy = false;
Chad Rosiera548fe52015-11-12 19:09:16 +0000450 // Make sure this is a strided store with a constant stride.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000451 if (!isLegalStore(SI, ForMemset, ForMemsetPattern, ForMemcpy))
Chad Rosiera548fe52015-11-12 19:09:16 +0000452 continue;
453
Chad Rosiercc9030b2015-11-11 23:00:59 +0000454 // Save the store locations.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000455 if (ForMemset) {
456 // Find the base pointer.
457 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
458 StoreRefsForMemset[Ptr].push_back(SI);
459 } else if (ForMemsetPattern) {
460 // Find the base pointer.
461 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
462 StoreRefsForMemsetPattern[Ptr].push_back(SI);
463 } else if (ForMemcpy)
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000464 StoreRefsForMemcpy.push_back(SI);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000465 }
466}
467
Chris Lattner8455b6e2011-01-02 19:01:03 +0000468/// runOnLoopBlock - Process the specified block, which lives in a counted loop
469/// with the specified backedge count. This block is known to be in the current
470/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000471bool LoopIdiomRecognize::runOnLoopBlock(
472 BasicBlock *BB, const SCEV *BECount,
473 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000474 // We can only promote stores in this block if they are unconditionally
475 // executed in the loop. For a block to be unconditionally executed, it has
476 // to dominate all the exit blocks of the loop. Verify this now.
477 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
478 if (!DT->dominates(BB, ExitBlocks[i]))
479 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000480
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000481 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000482 // Look for store instructions, which may be optimized to memset/memcpy.
483 collectStores(BB);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000484
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000485 // Look for a single store or sets of stores with a common base, which can be
486 // optimized into a memset (memset_pattern). The latter most commonly happens
487 // with structs and handunrolled loops.
488 for (auto &SL : StoreRefsForMemset)
489 MadeChange |= processLoopStores(SL.second, BECount, true);
490
491 for (auto &SL : StoreRefsForMemsetPattern)
492 MadeChange |= processLoopStores(SL.second, BECount, false);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000493
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000494 // Optimize the store into a memcpy, if it feeds an similarly strided load.
495 for (auto &SI : StoreRefsForMemcpy)
496 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
497
Chandler Carruthbad690e2015-08-12 23:06:37 +0000498 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000499 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000500 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000501 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000502 WeakTrackingVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000503 if (!processLoopMemSet(MSI, BECount))
504 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000505 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000506
Chris Lattner86438102011-01-04 07:46:33 +0000507 // If processing the memset invalidated our iterator, start over from the
508 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000509 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000510 I = BB->begin();
511 continue;
512 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000513 }
Andrew Trick328b2232011-03-14 16:48:10 +0000514
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000515 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000516}
517
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000518/// processLoopStores - See if this store(s) can be promoted to a memset.
519bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
520 const SCEV *BECount,
521 bool ForMemset) {
522 // Try to find consecutive stores that can be transformed into memsets.
523 SetVector<StoreInst *> Heads, Tails;
524 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
Chris Lattner86438102011-01-04 07:46:33 +0000525
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000526 // Do a quadratic search on all of the given stores and find
527 // all of the pairs of stores that follow each other.
528 SmallVector<unsigned, 16> IndexQueue;
529 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
530 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
Andrew Trick328b2232011-03-14 16:48:10 +0000531
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000532 Value *FirstStoredVal = SL[i]->getValueOperand();
533 Value *FirstStorePtr = SL[i]->getPointerOperand();
534 const SCEVAddRecExpr *FirstStoreEv =
535 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000536 APInt FirstStride = getStoreStride(FirstStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000537 unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL);
Chad Rosier79676142015-10-28 14:38:49 +0000538
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000539 // See if we can optimize just this store in isolation.
Chad Rosier4acff962016-02-12 19:05:27 +0000540 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000541 Heads.insert(SL[i]);
542 continue;
543 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000544
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000545 Value *FirstSplatValue = nullptr;
546 Constant *FirstPatternValue = nullptr;
547
548 if (ForMemset)
549 FirstSplatValue = isBytewiseValue(FirstStoredVal);
550 else
551 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
552
553 assert((FirstSplatValue || FirstPatternValue) &&
554 "Expected either splat value or pattern value.");
555
556 IndexQueue.clear();
557 // If a store has multiple consecutive store candidates, search Stores
558 // array according to the sequence: from i+1 to e, then from i-1 to 0.
559 // This is because usually pairing with immediate succeeding or preceding
560 // candidate create the best chance to find memset opportunity.
561 unsigned j = 0;
562 for (j = i + 1; j < e; ++j)
563 IndexQueue.push_back(j);
564 for (j = i; j > 0; --j)
565 IndexQueue.push_back(j - 1);
566
567 for (auto &k : IndexQueue) {
568 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
569 Value *SecondStorePtr = SL[k]->getPointerOperand();
570 const SCEVAddRecExpr *SecondStoreEv =
571 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000572 APInt SecondStride = getStoreStride(SecondStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000573
574 if (FirstStride != SecondStride)
575 continue;
576
577 Value *SecondStoredVal = SL[k]->getValueOperand();
578 Value *SecondSplatValue = nullptr;
579 Constant *SecondPatternValue = nullptr;
580
581 if (ForMemset)
582 SecondSplatValue = isBytewiseValue(SecondStoredVal);
583 else
584 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
585
586 assert((SecondSplatValue || SecondPatternValue) &&
587 "Expected either splat value or pattern value.");
588
589 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
590 if (ForMemset) {
591 if (FirstSplatValue != SecondSplatValue)
592 continue;
593 } else {
594 if (FirstPatternValue != SecondPatternValue)
595 continue;
596 }
597 Tails.insert(SL[k]);
598 Heads.insert(SL[i]);
599 ConsecutiveChain[SL[i]] = SL[k];
600 break;
601 }
602 }
603 }
604
605 // We may run into multiple chains that merge into a single chain. We mark the
606 // stores that we transformed so that we don't visit the same store twice.
607 SmallPtrSet<Value *, 16> TransformedStores;
608 bool Changed = false;
609
610 // For stores that start but don't end a link in the chain:
611 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
612 it != e; ++it) {
613 if (Tails.count(*it))
614 continue;
615
616 // We found a store instr that starts a chain. Now follow the chain and try
617 // to transform it.
618 SmallPtrSet<Instruction *, 8> AdjacentStores;
619 StoreInst *I = *it;
620
621 StoreInst *HeadStore = I;
622 unsigned StoreSize = 0;
623
624 // Collect the chain into a list.
625 while (Tails.count(I) || Heads.count(I)) {
626 if (TransformedStores.count(I))
627 break;
628 AdjacentStores.insert(I);
629
630 StoreSize += getStoreSizeInBytes(I, DL);
631 // Move to the next value in the chain.
632 I = ConsecutiveChain[I];
633 }
634
635 Value *StoredVal = HeadStore->getValueOperand();
636 Value *StorePtr = HeadStore->getPointerOperand();
637 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000638 APInt Stride = getStoreStride(StoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000639
640 // Check to see if the stride matches the size of the stores. If so, then
641 // we know that every byte is touched in the loop.
642 if (StoreSize != Stride && StoreSize != -Stride)
643 continue;
644
645 bool NegStride = StoreSize == -Stride;
646
647 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
648 StoredVal, HeadStore, AdjacentStores, StoreEv,
649 BECount, NegStride)) {
650 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
651 Changed = true;
652 }
653 }
654
655 return Changed;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000656}
657
Chris Lattner86438102011-01-04 07:46:33 +0000658/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000659bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
660 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000661 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000662 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
663 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000664
Chris Lattnere6b261f2011-02-18 22:22:15 +0000665 // If we're not allowed to hack on memset, we fail.
Ahmed Bougacha7f971932016-04-27 19:04:46 +0000666 if (!HasMemset)
Chris Lattnere6b261f2011-02-18 22:22:15 +0000667 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000668
Chris Lattner86438102011-01-04 07:46:33 +0000669 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000670
Chris Lattner86438102011-01-04 07:46:33 +0000671 // See if the pointer expression is an AddRec like {base,+,1} on the current
672 // loop, which indicates a strided store. If we have something else, it's a
673 // random store we can't handle.
674 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000675 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000676 return false;
677
678 // Reject memsets that are so large that they overflow an unsigned.
679 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
680 if ((SizeInBytes >> 32) != 0)
681 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000682
Chris Lattner86438102011-01-04 07:46:33 +0000683 // Check to see if the stride matches the size of the memset. If so, then we
684 // know that every byte is touched in the loop.
Chad Rosier81362a82016-02-12 21:03:23 +0000685 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
686 if (!ConstStride)
687 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000688
Chad Rosier81362a82016-02-12 21:03:23 +0000689 APInt Stride = ConstStride->getAPInt();
690 if (SizeInBytes != Stride && SizeInBytes != -Stride)
Chris Lattner86438102011-01-04 07:46:33 +0000691 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000692
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000693 // Verify that the memset value is loop invariant. If not, we can't promote
694 // the memset.
695 Value *SplatValue = MSI->getValue();
696 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
697 return false;
698
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000699 SmallPtrSet<Instruction *, 1> MSIs;
700 MSIs.insert(MSI);
Chad Rosier81362a82016-02-12 21:03:23 +0000701 bool NegStride = SizeInBytes == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000702 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000703 MSI->getAlignment(), SplatValue, MSI, MSIs, Ev,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000704 BECount, NegStride, /*IsLoopMemset=*/true);
Chris Lattner86438102011-01-04 07:46:33 +0000705}
706
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000707/// mayLoopAccessLocation - Return true if the specified loop might access the
708/// specified pointer location, which is a loop-strided access. The 'Access'
709/// argument specifies what the verboten forms of access are (read or write).
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000710static bool
711mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
712 const SCEV *BECount, unsigned StoreSize,
713 AliasAnalysis &AA,
714 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000715 // Get the location that may be stored across the loop. Since the access is
716 // strided positively through memory, we say that the modified location starts
717 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000718 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000719
720 // If the loop iterates a fixed number of times, we can refine the access size
721 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
722 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000723 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000724
725 // TODO: For this to be really effective, we have to dive into the pointer
726 // operand in the store. Store to &A[i] of 100 will always return may alias
727 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
728 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000729 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000730
731 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
732 ++BI)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000733 for (Instruction &I : **BI)
734 if (IgnoredStores.count(&I) == 0 &&
735 (AA.getModRefInfo(&I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000736 return true;
737
738 return false;
739}
740
Chad Rosiered0c7d12015-11-13 19:11:07 +0000741// If we have a negative stride, Start refers to the end of the memory location
742// we're trying to memset. Therefore, we need to recompute the base pointer,
743// which is just Start - BECount*Size.
744static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
745 Type *IntPtr, unsigned StoreSize,
746 ScalarEvolution *SE) {
747 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
748 if (StoreSize != 1)
749 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
750 SCEV::FlagNUW);
751 return SE->getMinusSCEV(Start, Index);
752}
753
Chris Lattner0f4a6402011-02-19 19:31:39 +0000754/// processLoopStridedStore - We see a strided store of some value. If we can
755/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000756bool LoopIdiomRecognize::processLoopStridedStore(
757 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000758 Value *StoredVal, Instruction *TheStore,
759 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000760 const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000761 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000762 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000763
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000764 if (!SplatValue)
765 PatternValue = getMemSetPatternValue(StoredVal, DL);
766
767 assert((SplatValue || PatternValue) &&
768 "Expected either splat value or pattern value.");
Andrew Trick328b2232011-03-14 16:48:10 +0000769
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000770 // The trip count of the loop and the base pointer of the addrec SCEV is
771 // guaranteed to be loop invariant, which means that it should dominate the
772 // header. This allows us to insert code for it in the preheader.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000773 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000774 BasicBlock *Preheader = CurLoop->getLoopPreheader();
775 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000776 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000777
Matt Arsenault009faed2013-09-11 05:09:42 +0000778 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000779 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000780
781 const SCEV *Start = Ev->getStart();
Chad Rosier2fa50a72015-11-13 19:13:40 +0000782 // Handle negative strided loops.
Chad Rosiered0c7d12015-11-13 19:11:07 +0000783 if (NegStride)
784 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
Matt Arsenault009faed2013-09-11 05:09:42 +0000785
Aditya Kumar1c42d132017-05-05 14:49:45 +0000786 // TODO: ideally we should still be able to generate memset if SCEV expander
787 // is taught to generate the dependencies at the latest point.
788 if (!isSafeToExpand(Start, *SE))
789 return false;
790
Chris Lattner29e14ed2010-12-26 23:42:51 +0000791 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000792 // this into a memset in the loop preheader now if we want. However, this
793 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000794 // or write to the aliased location. Check for any overlap by generating the
795 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000796 Value *BasePtr =
797 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Chandler Carruth194f59c2015-07-22 23:15:57 +0000798 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000799 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000800 Expander.clear();
801 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000802 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000803 return false;
804 }
805
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000806 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
807 return false;
808
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000809 // Okay, everything looks good, insert the memset.
810
Chris Lattner29e14ed2010-12-26 23:42:51 +0000811 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
812 // pointer size if it isn't already.
Chris Lattner0ba473c2011-01-04 00:06:55 +0000813 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000814
Chandler Carruthbad690e2015-08-12 23:06:37 +0000815 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000816 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000817 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000818 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000819 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000820 }
Andrew Trick328b2232011-03-14 16:48:10 +0000821
Aditya Kumar1c42d132017-05-05 14:49:45 +0000822 // TODO: ideally we should still be able to generate memset if SCEV expander
823 // is taught to generate the dependencies at the latest point.
824 if (!isSafeToExpand(NumBytesS, *SE))
825 return false;
826
Andrew Trick328b2232011-03-14 16:48:10 +0000827 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000828 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000829
Devang Pateld00c6282011-03-07 22:43:45 +0000830 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000831 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000832 NewCall =
833 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000834 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000835 // Everything is emitted in default address space
836 Type *Int8PtrTy = DestInt8PtrTy;
837
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000838 Module *M = TheStore->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000839 Value *MSP =
840 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000841 Int8PtrTy, Int8PtrTy, IntPtr);
Ahmed Bougachaace97c12016-04-27 19:04:50 +0000842 inferLibFuncAttributes(*M->getFunction("memset_pattern16"), *TLI);
Andrew Trick328b2232011-03-14 16:48:10 +0000843
Chris Lattner0f4a6402011-02-19 19:31:39 +0000844 // Otherwise we should form a memset_pattern16. PatternValue is known to be
845 // an constant array of 16-bytes. Plop the value into a mergable global.
846 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000847 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000848 PatternValue, ".memset_pattern");
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000849 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000850 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000851 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000852 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000853 }
Andrew Trick328b2232011-03-14 16:48:10 +0000854
Chris Lattner29e14ed2010-12-26 23:42:51 +0000855 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000856 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000857 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000858
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000859 // Okay, the memset has been formed. Zap the original store and anything that
860 // feeds into it.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000861 for (auto *I : Stores)
David Majnemer41ff4fd2016-06-20 16:07:38 +0000862 deleteDeadInstruction(I);
Chris Lattner12f91be2011-01-02 07:36:44 +0000863 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000864 return true;
865}
866
Chad Rosier1cd3da12015-11-19 21:33:07 +0000867/// If the stored value is a strided load in the same loop with the same stride
868/// this may be transformable into a memcpy. This kicks in for stuff like
Xin Tonga41bf702017-05-01 23:08:19 +0000869/// for (i) A[i] = B[i];
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000870bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
871 const SCEV *BECount) {
872 assert(SI->isSimple() && "Expected only non-volatile stores.");
873
874 Value *StorePtr = SI->getPointerOperand();
875 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000876 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000877 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
878 bool NegStride = StoreSize == -Stride;
Andrew Trick328b2232011-03-14 16:48:10 +0000879
Chad Rosierfddc01f2015-11-19 18:22:21 +0000880 // The store must be feeding a non-volatile load.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000881 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
882 assert(LI->isSimple() && "Expected only non-volatile stores.");
Chad Rosierfddc01f2015-11-19 18:22:21 +0000883
884 // See if the pointer expression is an AddRec like {base,+,1} on the current
885 // loop, which indicates a strided load. If we have something else, it's a
886 // random load we can't handle.
Chad Rosier3ecc8d82015-11-19 18:25:11 +0000887 const SCEVAddRecExpr *LoadEv =
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000888 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
Andrew Trick328b2232011-03-14 16:48:10 +0000889
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000890 // The trip count of the loop and the base pointer of the addrec SCEV is
891 // guaranteed to be loop invariant, which means that it should dominate the
892 // header. This allows us to insert code for it in the preheader.
893 BasicBlock *Preheader = CurLoop->getLoopPreheader();
894 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000895 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000896
Chad Rosiercc299b62015-11-13 21:51:02 +0000897 const SCEV *StrStart = StoreEv->getStart();
898 unsigned StrAS = SI->getPointerAddressSpace();
899 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
900
901 // Handle negative strided loops.
902 if (NegStride)
903 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
904
Chris Lattner85b6d812011-01-02 03:37:56 +0000905 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000906 // this into a memcpy in the loop preheader now if we want. However, this
907 // would be unsafe to do if there is anything else in the loop that may read
908 // or write the memory region we're storing to. This includes the load that
909 // feeds the stores. Check for an alias by generating the base address and
910 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000911 Value *StoreBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000912 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000913
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000914 SmallPtrSet<Instruction *, 1> Stores;
915 Stores.insert(SI);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000916 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000917 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000918 Expander.clear();
919 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000920 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000921 return false;
922 }
923
Chad Rosiercc299b62015-11-13 21:51:02 +0000924 const SCEV *LdStart = LoadEv->getStart();
925 unsigned LdAS = LI->getPointerAddressSpace();
926
927 // Handle negative strided loops.
928 if (NegStride)
929 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
930
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000931 // For a memcpy, we have to make sure that the input array is not being
932 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000933 Value *LoadBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000934 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000935
Chandler Carruth194f59c2015-07-22 23:15:57 +0000936 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000937 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000938 Expander.clear();
939 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000940 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
941 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000942 return false;
943 }
944
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000945 if (avoidLIRForMultiBlockLoop())
946 return false;
947
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000948 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000949
Chris Lattner85b6d812011-01-02 03:37:56 +0000950 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
951 // pointer size if it isn't already.
Matt Arsenault009faed2013-09-11 05:09:42 +0000952 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +0000953
Chandler Carruthbad690e2015-08-12 23:06:37 +0000954 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000955 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +0000956 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +0000957 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000958 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +0000959
Chris Lattner85b6d812011-01-02 03:37:56 +0000960 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000961 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000962
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000963 CallInst *NewCall =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000964 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000965 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +0000966 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000967
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000968 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +0000969 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
970 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000971
Chad Rosier7f08d802015-10-13 20:59:16 +0000972 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +0000973 // feeds into it.
David Majnemer41ff4fd2016-06-20 16:07:38 +0000974 deleteDeadInstruction(SI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000975 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +0000976 return true;
977}
Chandler Carruthd9c60702015-08-13 00:10:03 +0000978
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000979// When compiling for codesize we avoid idiom recognition for a multi-block loop
980// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
981//
982bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
983 bool IsLoopMemset) {
984 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
985 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
986 DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
987 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
988 << " avoided: multi-block top-level loop\n");
989 return true;
990 }
991 }
992
993 return false;
994}
995
Chandler Carruthd9c60702015-08-13 00:10:03 +0000996bool LoopIdiomRecognize::runOnNoncountableLoop() {
Chad Rosier19dc92d2015-11-09 16:56:06 +0000997 return recognizePopcount();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000998}
Chandler Carruth8219a502015-08-13 00:44:29 +0000999
1000/// Check if the given conditional branch is based on the comparison between
1001/// a variable and zero, and if the variable is non-zero, the control yields to
1002/// the loop entry. If the branch matches the behavior, the variable involved
Xin Tong8b8a6002017-01-05 21:40:08 +00001003/// in the comparison is returned. This function will be called to see if the
Chandler Carruth8219a502015-08-13 00:44:29 +00001004/// precondition and postcondition of the loop are in desirable form.
1005static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
1006 if (!BI || !BI->isConditional())
1007 return nullptr;
1008
1009 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1010 if (!Cond)
1011 return nullptr;
1012
1013 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1014 if (!CmpZero || !CmpZero->isZero())
1015 return nullptr;
1016
1017 ICmpInst::Predicate Pred = Cond->getPredicate();
1018 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
1019 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
1020 return Cond->getOperand(0);
1021
1022 return nullptr;
1023}
1024
1025/// Return true iff the idiom is detected in the loop.
1026///
1027/// Additionally:
1028/// 1) \p CntInst is set to the instruction counting the population bit.
1029/// 2) \p CntPhi is set to the corresponding phi node.
1030/// 3) \p Var is set to the value whose population bits are being counted.
1031///
1032/// The core idiom we are trying to detect is:
1033/// \code
1034/// if (x0 != 0)
1035/// goto loop-exit // the precondition of the loop
1036/// cnt0 = init-val;
1037/// do {
1038/// x1 = phi (x0, x2);
1039/// cnt1 = phi(cnt0, cnt2);
1040///
1041/// cnt2 = cnt1 + 1;
1042/// ...
1043/// x2 = x1 & (x1 - 1);
1044/// ...
1045/// } while(x != 0);
1046///
1047/// loop-exit:
1048/// \endcode
1049static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1050 Instruction *&CntInst, PHINode *&CntPhi,
1051 Value *&Var) {
1052 // step 1: Check to see if the look-back branch match this pattern:
1053 // "if (a!=0) goto loop-entry".
1054 BasicBlock *LoopEntry;
1055 Instruction *DefX2, *CountInst;
1056 Value *VarX1, *VarX0;
1057 PHINode *PhiX, *CountPhi;
1058
1059 DefX2 = CountInst = nullptr;
1060 VarX1 = VarX0 = nullptr;
1061 PhiX = CountPhi = nullptr;
1062 LoopEntry = *(CurLoop->block_begin());
1063
1064 // step 1: Check if the loop-back branch is in desirable form.
1065 {
1066 if (Value *T = matchCondition(
1067 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1068 DefX2 = dyn_cast<Instruction>(T);
1069 else
1070 return false;
1071 }
1072
1073 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1074 {
1075 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1076 return false;
1077
1078 BinaryOperator *SubOneOp;
1079
1080 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1081 VarX1 = DefX2->getOperand(1);
1082 else {
1083 VarX1 = DefX2->getOperand(0);
1084 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1085 }
1086 if (!SubOneOp)
1087 return false;
1088
1089 Instruction *SubInst = cast<Instruction>(SubOneOp);
1090 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
1091 if (!Dec ||
1092 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1093 (SubInst->getOpcode() == Instruction::Add &&
1094 Dec->isAllOnesValue()))) {
1095 return false;
1096 }
1097 }
1098
1099 // step 3: Check the recurrence of variable X
1100 {
1101 PhiX = dyn_cast<PHINode>(VarX1);
1102 if (!PhiX ||
1103 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
1104 return false;
1105 }
1106 }
1107
1108 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1109 {
1110 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001111 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +00001112 IterE = LoopEntry->end();
1113 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001114 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +00001115 if (Inst->getOpcode() != Instruction::Add)
1116 continue;
1117
1118 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1119 if (!Inc || !Inc->isOne())
1120 continue;
1121
1122 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
1123 if (!Phi || Phi->getParent() != LoopEntry)
1124 continue;
1125
1126 // Check if the result of the instruction is live of the loop.
1127 bool LiveOutLoop = false;
1128 for (User *U : Inst->users()) {
1129 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1130 LiveOutLoop = true;
1131 break;
1132 }
1133 }
1134
1135 if (LiveOutLoop) {
1136 CountInst = Inst;
1137 CountPhi = Phi;
1138 break;
1139 }
1140 }
1141
1142 if (!CountInst)
1143 return false;
1144 }
1145
1146 // step 5: check if the precondition is in this form:
1147 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1148 {
1149 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1150 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1151 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1152 return false;
1153
1154 CntInst = CountInst;
1155 CntPhi = CountPhi;
1156 Var = T;
1157 }
1158
1159 return true;
1160}
1161
1162/// Recognizes a population count idiom in a non-countable loop.
1163///
1164/// If detected, transforms the relevant code to issue the popcount intrinsic
1165/// function call, and returns true; otherwise, returns false.
1166bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +00001167 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1168 return false;
1169
1170 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001171 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +00001172 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1173 // in a compact loop.
1174
Renato Golin655348f2015-08-13 11:25:38 +00001175 // Give up if the loop has multiple blocks or multiple backedges.
1176 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001177 return false;
1178
Renato Golin655348f2015-08-13 11:25:38 +00001179 BasicBlock *LoopBody = *(CurLoop->block_begin());
1180 if (LoopBody->size() >= 20) {
1181 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +00001182 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001183 }
Chandler Carruth8219a502015-08-13 00:44:29 +00001184
1185 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +00001186 BasicBlock *PH = CurLoop->getLoopPreheader();
Davide Italianoc0169fa2016-10-07 18:39:43 +00001187 if (!PH || &PH->front() != PH->getTerminator())
Renato Golin655348f2015-08-13 11:25:38 +00001188 return false;
1189 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001190 if (!EntryBI || EntryBI->isConditional())
1191 return false;
1192
1193 // It should have a precondition block where the generated popcount instrinsic
1194 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +00001195 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +00001196 if (!PreCondBB)
1197 return false;
1198 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1199 if (!PreCondBI || PreCondBI->isUnconditional())
1200 return false;
1201
1202 Instruction *CntInst;
1203 PHINode *CntPhi;
1204 Value *Val;
1205 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1206 return false;
1207
1208 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1209 return true;
1210}
1211
1212static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001213 const DebugLoc &DL) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001214 Value *Ops[] = {Val};
1215 Type *Tys[] = {Val->getType()};
1216
1217 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1218 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1219 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1220 CI->setDebugLoc(DL);
1221
1222 return CI;
1223}
1224
1225void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1226 Instruction *CntInst,
1227 PHINode *CntPhi, Value *Var) {
1228 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1229 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1230 const DebugLoc DL = CntInst->getDebugLoc();
1231
1232 // Assuming before transformation, the loop is following:
1233 // if (x) // the precondition
1234 // do { cnt++; x &= x - 1; } while(x);
1235
1236 // Step 1: Insert the ctpop instruction at the end of the precondition block
1237 IRBuilder<> Builder(PreCondBr);
1238 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1239 {
1240 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1241 NewCount = PopCntZext =
1242 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1243
1244 if (NewCount != PopCnt)
1245 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1246
1247 // TripCnt is exactly the number of iterations the loop has
1248 TripCnt = NewCount;
1249
1250 // If the population counter's initial value is not zero, insert Add Inst.
1251 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1252 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1253 if (!InitConst || !InitConst->isZero()) {
1254 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1255 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1256 }
1257 }
1258
Nick Lewycky2c852542015-08-19 06:22:33 +00001259 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +00001260 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001261 // function would be partial dead code, and downstream passes will drag
1262 // it back from the precondition block to the preheader.
1263 {
1264 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1265
1266 Value *Opnd0 = PopCntZext;
1267 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1268 if (PreCond->getOperand(0) != Var)
1269 std::swap(Opnd0, Opnd1);
1270
1271 ICmpInst *NewPreCond = cast<ICmpInst>(
1272 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1273 PreCondBr->setCondition(NewPreCond);
1274
1275 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1276 }
1277
1278 // Step 3: Note that the population count is exactly the trip count of the
Nick Lewycky1098e492015-08-19 06:25:30 +00001279 // loop in question, which enable us to to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +00001280 // loop into a countable one. The benefit is twofold:
1281 //
Nick Lewycky2c852542015-08-19 06:22:33 +00001282 // - If the loop only counts population, the entire loop becomes dead after
1283 // the transformation. It is a lot easier to prove a countable loop dead
1284 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +00001285 // isn't dead even if it computes nothing useful. In general, DCE needs
1286 // to prove a noncountable loop finite before safely delete it.)
1287 //
1288 // - If the loop also performs something else, it remains alive.
1289 // Since it is transformed to countable form, it can be aggressively
1290 // optimized by some optimizations which are in general not applicable
1291 // to a noncountable loop.
1292 //
1293 // After this step, this loop (conceptually) would look like following:
1294 // newcnt = __builtin_ctpop(x);
1295 // t = newcnt;
1296 // if (x)
1297 // do { cnt++; x &= x-1; t--) } while (t > 0);
1298 BasicBlock *Body = *(CurLoop->block_begin());
1299 {
1300 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1301 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1302 Type *Ty = TripCnt->getType();
1303
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001304 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +00001305
1306 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +00001307 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +00001308 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1309 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +00001310
1311 TcPhi->addIncoming(TripCnt, PreHead);
1312 TcPhi->addIncoming(TcDec, Body);
1313
1314 CmpInst::Predicate Pred =
1315 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1316 LbCond->setPredicate(Pred);
1317 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001318 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001319 }
1320
1321 // Step 4: All the references to the original population counter outside
1322 // the loop are replaced with the NewCount -- the value returned from
1323 // __builtin_ctpop().
1324 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1325
1326 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1327 // loop. The loop would otherwise not be deleted even if it becomes empty.
1328 SE->forgetLoop(CurLoop);
1329}