blob: 900cdae41d4d131aab7283b56b77b2cc0fdfd492 [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//
Chris Lattner02a97762011-01-03 01:10:08 +000029// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000030// replace them with calls to BLAS (if linked in??).
31//
Chris Lattner0469e012011-01-02 18:32:09 +000032//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000033
Chris Lattner81ae3f22010-12-26 19:39:38 +000034#include "llvm/Transforms/Scalar.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000035#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/SetVector.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000037#include "llvm/ADT/Statistic.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000038#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000039#include "llvm/Analysis/BasicAliasAnalysis.h"
40#include "llvm/Analysis/GlobalsModRef.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000041#include "llvm/Analysis/LoopPass.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000042#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000043#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chad Rosiera15b4b62015-11-23 21:09:13 +000044#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000047#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000048#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/IRBuilder.h"
52#include "llvm/IR/IntrinsicInst.h"
53#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000054#include "llvm/Support/Debug.h"
55#include "llvm/Support/raw_ostream.h"
Chris Lattnerb9fe6852010-12-27 00:03:23 +000056#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ae3f22010-12-26 19:39:38 +000057using namespace llvm;
58
Chandler Carruth964daaa2014-04-22 02:55:47 +000059#define DEBUG_TYPE "loop-idiom"
60
Chandler Carruth099f5cb02012-11-02 08:33:25 +000061STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
62STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +000063
64namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +000065
Chandler Carruthbad690e2015-08-12 23:06:37 +000066class LoopIdiomRecognize : public LoopPass {
67 Loop *CurLoop;
Chandler Carruthbf143e22015-08-14 00:21:10 +000068 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +000069 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +000070 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +000071 ScalarEvolution *SE;
72 TargetLibraryInfo *TLI;
73 const TargetTransformInfo *TTI;
Chad Rosier43f9b482015-11-06 16:33:57 +000074 const DataLayout *DL;
Chris Lattner81ae3f22010-12-26 19:39:38 +000075
Chandler Carruthbad690e2015-08-12 23:06:37 +000076public:
77 static char ID;
78 explicit LoopIdiomRecognize() : LoopPass(ID) {
79 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
Chandler Carruthbad690e2015-08-12 23:06:37 +000080 }
Chris Lattner81ae3f22010-12-26 19:39:38 +000081
Chandler Carruthbad690e2015-08-12 23:06:37 +000082 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Shuxin Yang95de7c32012-12-09 03:12:46 +000083
Chandler Carruthbad690e2015-08-12 23:06:37 +000084 /// This transformation requires natural loop information & requires that
85 /// loop preheaders be inserted into the CFG.
86 ///
87 void getAnalysisUsage(AnalysisUsage &AU) const override {
88 AU.addRequired<LoopInfoWrapperPass>();
89 AU.addPreserved<LoopInfoWrapperPass>();
90 AU.addRequiredID(LoopSimplifyID);
91 AU.addPreservedID(LoopSimplifyID);
92 AU.addRequiredID(LCSSAID);
93 AU.addPreservedID(LCSSAID);
Chandler Carruth7b560d42015-09-09 17:55:00 +000094 AU.addRequired<AAResultsWrapperPass>();
95 AU.addPreserved<AAResultsWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000096 AU.addRequired<ScalarEvolutionWrapperPass>();
97 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +000098 AU.addPreserved<SCEVAAWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +000099 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000100 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000101 AU.addRequired<TargetLibraryInfoWrapperPass>();
102 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000103 AU.addPreserved<BasicAAWrapperPass>();
104 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000105 }
Shuxin Yang95de7c32012-12-09 03:12:46 +0000106
Chandler Carruthbad690e2015-08-12 23:06:37 +0000107private:
Chad Rosiercc9030b2015-11-11 23:00:59 +0000108 typedef SmallVector<StoreInst *, 8> StoreList;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000109 typedef MapVector<Value *, StoreList> StoreListMap;
110 StoreListMap StoreRefsForMemset;
111 StoreListMap StoreRefsForMemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000112 StoreList StoreRefsForMemcpy;
113 bool HasMemset;
114 bool HasMemsetPattern;
115 bool HasMemcpy;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000116
Chandler Carruthd9c60702015-08-13 00:10:03 +0000117 /// \name Countable Loop Idiom Handling
118 /// @{
119
Chandler Carruthbad690e2015-08-12 23:06:37 +0000120 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000121 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
122 SmallVectorImpl<BasicBlock *> &ExitBlocks);
123
Chad Rosiercc9030b2015-11-11 23:00:59 +0000124 void collectStores(BasicBlock *BB);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000125 bool isLegalStore(StoreInst *SI, bool &ForMemset, bool &ForMemsetPattern,
126 bool &ForMemcpy);
127 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
128 bool ForMemset);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000129 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
130
131 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000132 unsigned StoreAlignment, Value *StoredVal,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000133 Instruction *TheStore,
134 SmallPtrSetImpl<Instruction *> &Stores,
135 const SCEVAddRecExpr *Ev, const SCEV *BECount,
136 bool NegStride);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000137 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000138
139 /// @}
140 /// \name Noncountable Loop Idiom Handling
141 /// @{
142
143 bool runOnNoncountableLoop();
144
Chandler Carruth8219a502015-08-13 00:44:29 +0000145 bool recognizePopcount();
146 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
147 PHINode *CntPhi, Value *Var);
148
Chandler Carruthd9c60702015-08-13 00:10:03 +0000149 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000150};
151
152} // End anonymous namespace.
Chris Lattner81ae3f22010-12-26 19:39:38 +0000153
154char LoopIdiomRecognize::ID = 0;
155INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
156 false, false)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000157INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000158INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000159INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
160INITIALIZE_PASS_DEPENDENCY(LCSSA)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000161INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000162INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000163INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
164INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
165INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
166INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000167INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000168INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
169 false, false)
170
171Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
172
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000173/// deleteDeadInstruction - Delete this instruction. Before we do, go through
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000174/// and zero out all the operands of this instruction. If any of them become
175/// dead, delete them and the computation tree that feeds them.
176///
Benjamin Kramerf094d772015-02-07 21:37:08 +0000177static void deleteDeadInstruction(Instruction *I,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000178 const TargetLibraryInfo *TLI) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000179 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
180 I->replaceAllUsesWith(UndefValue::get(I->getType()));
181 I->eraseFromParent();
182 for (Value *Op : Operands)
183 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000184}
185
Shuxin Yang95de7c32012-12-09 03:12:46 +0000186//===----------------------------------------------------------------------===//
187//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000188// Implementation of LoopIdiomRecognize
189//
190//===----------------------------------------------------------------------===//
191
Chandler Carruthd9c60702015-08-13 00:10:03 +0000192bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
193 if (skipOptnoneFunction(L))
194 return false;
195
196 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000197 // If the loop could not be converted to canonical form, it must have an
198 // indirectbr in it, just give up.
199 if (!L->getLoopPreheader())
200 return false;
201
202 // Disable loop idiom recognition if the function's name is a common idiom.
203 StringRef Name = L->getHeader()->getParent()->getName();
204 if (Name == "memset" || Name == "memcpy")
205 return false;
206
Chandler Carruth7b560d42015-09-09 17:55:00 +0000207 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruthdc298322015-08-13 01:03:26 +0000208 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth18c26692015-08-13 09:27:01 +0000209 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000210 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthdc298322015-08-13 01:03:26 +0000211 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
212 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
213 *CurLoop->getHeader()->getParent());
Chad Rosier43f9b482015-11-06 16:33:57 +0000214 DL = &CurLoop->getHeader()->getModule()->getDataLayout();
Chandler Carruthdc298322015-08-13 01:03:26 +0000215
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000216 HasMemset = TLI->has(LibFunc::memset);
217 HasMemsetPattern = TLI->has(LibFunc::memset_pattern16);
218 HasMemcpy = TLI->has(LibFunc::memcpy);
219
220 if (HasMemset || HasMemsetPattern || HasMemcpy)
221 if (SE->hasLoopInvariantBackedgeTakenCount(L))
222 return runOnCountableLoop();
Chandler Carruthdc298322015-08-13 01:03:26 +0000223
Chandler Carruthd9c60702015-08-13 00:10:03 +0000224 return runOnNoncountableLoop();
225}
226
Shuxin Yang95de7c32012-12-09 03:12:46 +0000227bool LoopIdiomRecognize::runOnCountableLoop() {
228 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000229 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000230 "runOnCountableLoop() called on a loop without a predictable"
231 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000232
233 // If this loop executes exactly one time, then it should be peeled, not
234 // optimized by this pass.
235 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000236 if (BECst->getAPInt() == 0)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000237 return false;
238
Chandler Carruthbad690e2015-08-12 23:06:37 +0000239 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000240 CurLoop->getUniqueExitBlocks(ExitBlocks);
241
242 DEBUG(dbgs() << "loop-idiom Scanning: F["
Chandler Carruthbad690e2015-08-12 23:06:37 +0000243 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
244 << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000245
246 bool MadeChange = false;
247 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000248 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000249 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000250 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000251 continue;
252
Davide Italiano80625af2015-05-13 19:51:21 +0000253 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000254 }
255 return MadeChange;
256}
257
Chad Rosiera548fe52015-11-12 19:09:16 +0000258static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
259 uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
260 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
261 "Don't overflow unsigned.");
262 return (unsigned)SizeInBits >> 3;
263}
264
Chad Rosier4acff962016-02-12 19:05:27 +0000265static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
Chad Rosiera548fe52015-11-12 19:09:16 +0000266 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
Chad Rosier4acff962016-02-12 19:05:27 +0000267 return ConstStride->getAPInt();
Chad Rosiera548fe52015-11-12 19:09:16 +0000268}
269
Chad Rosier94274fb2015-12-21 14:49:32 +0000270/// getMemSetPatternValue - If a strided store of the specified value is safe to
271/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
272/// be passed in. Otherwise, return null.
273///
274/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
275/// just replicate their input array and then pass on to memset_pattern16.
276static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
277 // If the value isn't a constant, we can't promote it to being in a constant
278 // array. We could theoretically do a store to an alloca or something, but
279 // that doesn't seem worthwhile.
280 Constant *C = dyn_cast<Constant>(V);
281 if (!C)
282 return nullptr;
283
284 // Only handle simple values that are a power of two bytes in size.
285 uint64_t Size = DL->getTypeSizeInBits(V->getType());
286 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
287 return nullptr;
288
289 // Don't care enough about darwin/ppc to implement this.
290 if (DL->isBigEndian())
291 return nullptr;
292
293 // Convert to size in bytes.
294 Size /= 8;
295
296 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
297 // if the top and bottom are the same (e.g. for vectors and large integers).
298 if (Size > 16)
299 return nullptr;
300
301 // If the constant is exactly 16 bytes, just use it.
302 if (Size == 16)
303 return C;
304
305 // Otherwise, we'll use an array of the constants.
306 unsigned ArraySize = 16 / Size;
307 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
308 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
309}
310
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000311bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000312 bool &ForMemsetPattern, bool &ForMemcpy) {
Chad Rosier869962f2015-12-01 14:26:35 +0000313 // Don't touch volatile stores.
314 if (!SI->isSimple())
315 return false;
316
Chad Rosiera548fe52015-11-12 19:09:16 +0000317 Value *StoredVal = SI->getValueOperand();
318 Value *StorePtr = SI->getPointerOperand();
319
320 // Reject stores that are so large that they overflow an unsigned.
321 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
322 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
323 return false;
324
325 // See if the pointer expression is an AddRec like {base,+,1} on the current
326 // loop, which indicates a strided store. If we have something else, it's a
327 // random store we can't handle.
328 const SCEVAddRecExpr *StoreEv =
329 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
330 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
331 return false;
332
333 // Check to see if we have a constant stride.
334 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
335 return false;
336
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000337 // See if the store can be turned into a memset.
338
339 // If the stored value is a byte-wise value (like i32 -1), then it may be
340 // turned into a memset of i8 -1, assuming that all the consecutive bytes
341 // are stored. A store of i32 0x01020304 can never be turned into a memset,
342 // but it can be turned into memset_pattern if the target supports it.
343 Value *SplatValue = isBytewiseValue(StoredVal);
344 Constant *PatternValue = nullptr;
345
346 // If we're allowed to form a memset, and the stored value would be
347 // acceptable for memset, use it.
348 if (HasMemset && SplatValue &&
349 // Verify that the stored value is loop invariant. If not, we can't
350 // promote the memset.
351 CurLoop->isLoopInvariant(SplatValue)) {
352 // It looks like we can use SplatValue.
353 ForMemset = true;
354 return true;
355 } else if (HasMemsetPattern &&
356 // Don't create memset_pattern16s with address spaces.
357 StorePtr->getType()->getPointerAddressSpace() == 0 &&
358 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
359 // It looks like we can use PatternValue!
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000360 ForMemsetPattern = true;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000361 return true;
362 }
363
364 // Otherwise, see if the store can be turned into a memcpy.
365 if (HasMemcpy) {
366 // Check to see if the stride matches the size of the store. If so, then we
367 // know that every byte is touched in the loop.
Chad Rosier4acff962016-02-12 19:05:27 +0000368 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000369 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
370 if (StoreSize != Stride && StoreSize != -Stride)
371 return false;
372
373 // The store must be feeding a non-volatile load.
374 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
375 if (!LI || !LI->isSimple())
376 return false;
377
378 // See if the pointer expression is an AddRec like {base,+,1} on the current
379 // loop, which indicates a strided load. If we have something else, it's a
380 // random load we can't handle.
381 const SCEVAddRecExpr *LoadEv =
382 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
383 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
384 return false;
385
386 // The store and load must share the same stride.
387 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
388 return false;
389
390 // Success. This store can be converted into a memcpy.
391 ForMemcpy = true;
392 return true;
393 }
394 // This store can't be transformed into a memset/memcpy.
395 return false;
Chad Rosiera548fe52015-11-12 19:09:16 +0000396}
397
Chad Rosiercc9030b2015-11-11 23:00:59 +0000398void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000399 StoreRefsForMemset.clear();
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000400 StoreRefsForMemsetPattern.clear();
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000401 StoreRefsForMemcpy.clear();
Chad Rosiercc9030b2015-11-11 23:00:59 +0000402 for (Instruction &I : *BB) {
403 StoreInst *SI = dyn_cast<StoreInst>(&I);
404 if (!SI)
405 continue;
406
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000407 bool ForMemset = false;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000408 bool ForMemsetPattern = false;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000409 bool ForMemcpy = false;
Chad Rosiera548fe52015-11-12 19:09:16 +0000410 // Make sure this is a strided store with a constant stride.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000411 if (!isLegalStore(SI, ForMemset, ForMemsetPattern, ForMemcpy))
Chad Rosiera548fe52015-11-12 19:09:16 +0000412 continue;
413
Chad Rosiercc9030b2015-11-11 23:00:59 +0000414 // Save the store locations.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000415 if (ForMemset) {
416 // Find the base pointer.
417 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
418 StoreRefsForMemset[Ptr].push_back(SI);
419 } else if (ForMemsetPattern) {
420 // Find the base pointer.
421 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
422 StoreRefsForMemsetPattern[Ptr].push_back(SI);
423 } else if (ForMemcpy)
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000424 StoreRefsForMemcpy.push_back(SI);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000425 }
426}
427
Chris Lattner8455b6e2011-01-02 19:01:03 +0000428/// runOnLoopBlock - Process the specified block, which lives in a counted loop
429/// with the specified backedge count. This block is known to be in the current
430/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000431bool LoopIdiomRecognize::runOnLoopBlock(
432 BasicBlock *BB, const SCEV *BECount,
433 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000434 // We can only promote stores in this block if they are unconditionally
435 // executed in the loop. For a block to be unconditionally executed, it has
436 // to dominate all the exit blocks of the loop. Verify this now.
437 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
438 if (!DT->dominates(BB, ExitBlocks[i]))
439 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000440
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000441 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000442 // Look for store instructions, which may be optimized to memset/memcpy.
443 collectStores(BB);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000444
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000445 // Look for a single store or sets of stores with a common base, which can be
446 // optimized into a memset (memset_pattern). The latter most commonly happens
447 // with structs and handunrolled loops.
448 for (auto &SL : StoreRefsForMemset)
449 MadeChange |= processLoopStores(SL.second, BECount, true);
450
451 for (auto &SL : StoreRefsForMemsetPattern)
452 MadeChange |= processLoopStores(SL.second, BECount, false);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000453
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000454 // Optimize the store into a memcpy, if it feeds an similarly strided load.
455 for (auto &SI : StoreRefsForMemcpy)
456 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
457
Chandler Carruthbad690e2015-08-12 23:06:37 +0000458 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000459 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000460 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000461 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000462 WeakVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000463 if (!processLoopMemSet(MSI, BECount))
464 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000465 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000466
Chris Lattner86438102011-01-04 07:46:33 +0000467 // If processing the memset invalidated our iterator, start over from the
468 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000469 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000470 I = BB->begin();
471 continue;
472 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000473 }
Andrew Trick328b2232011-03-14 16:48:10 +0000474
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000475 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000476}
477
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000478/// processLoopStores - See if this store(s) can be promoted to a memset.
479bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
480 const SCEV *BECount,
481 bool ForMemset) {
482 // Try to find consecutive stores that can be transformed into memsets.
483 SetVector<StoreInst *> Heads, Tails;
484 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
Chris Lattner86438102011-01-04 07:46:33 +0000485
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000486 // Do a quadratic search on all of the given stores and find
487 // all of the pairs of stores that follow each other.
488 SmallVector<unsigned, 16> IndexQueue;
489 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
490 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
Andrew Trick328b2232011-03-14 16:48:10 +0000491
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000492 Value *FirstStoredVal = SL[i]->getValueOperand();
493 Value *FirstStorePtr = SL[i]->getPointerOperand();
494 const SCEVAddRecExpr *FirstStoreEv =
495 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000496 APInt FirstStride = getStoreStride(FirstStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000497 unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL);
Chad Rosier79676142015-10-28 14:38:49 +0000498
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000499 // See if we can optimize just this store in isolation.
Chad Rosier4acff962016-02-12 19:05:27 +0000500 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000501 Heads.insert(SL[i]);
502 continue;
503 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000504
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000505 Value *FirstSplatValue = nullptr;
506 Constant *FirstPatternValue = nullptr;
507
508 if (ForMemset)
509 FirstSplatValue = isBytewiseValue(FirstStoredVal);
510 else
511 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
512
513 assert((FirstSplatValue || FirstPatternValue) &&
514 "Expected either splat value or pattern value.");
515
516 IndexQueue.clear();
517 // If a store has multiple consecutive store candidates, search Stores
518 // array according to the sequence: from i+1 to e, then from i-1 to 0.
519 // This is because usually pairing with immediate succeeding or preceding
520 // candidate create the best chance to find memset opportunity.
521 unsigned j = 0;
522 for (j = i + 1; j < e; ++j)
523 IndexQueue.push_back(j);
524 for (j = i; j > 0; --j)
525 IndexQueue.push_back(j - 1);
526
527 for (auto &k : IndexQueue) {
528 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
529 Value *SecondStorePtr = SL[k]->getPointerOperand();
530 const SCEVAddRecExpr *SecondStoreEv =
531 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000532 APInt SecondStride = getStoreStride(SecondStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000533
534 if (FirstStride != SecondStride)
535 continue;
536
537 Value *SecondStoredVal = SL[k]->getValueOperand();
538 Value *SecondSplatValue = nullptr;
539 Constant *SecondPatternValue = nullptr;
540
541 if (ForMemset)
542 SecondSplatValue = isBytewiseValue(SecondStoredVal);
543 else
544 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
545
546 assert((SecondSplatValue || SecondPatternValue) &&
547 "Expected either splat value or pattern value.");
548
549 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
550 if (ForMemset) {
551 if (FirstSplatValue != SecondSplatValue)
552 continue;
553 } else {
554 if (FirstPatternValue != SecondPatternValue)
555 continue;
556 }
557 Tails.insert(SL[k]);
558 Heads.insert(SL[i]);
559 ConsecutiveChain[SL[i]] = SL[k];
560 break;
561 }
562 }
563 }
564
565 // We may run into multiple chains that merge into a single chain. We mark the
566 // stores that we transformed so that we don't visit the same store twice.
567 SmallPtrSet<Value *, 16> TransformedStores;
568 bool Changed = false;
569
570 // For stores that start but don't end a link in the chain:
571 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
572 it != e; ++it) {
573 if (Tails.count(*it))
574 continue;
575
576 // We found a store instr that starts a chain. Now follow the chain and try
577 // to transform it.
578 SmallPtrSet<Instruction *, 8> AdjacentStores;
579 StoreInst *I = *it;
580
581 StoreInst *HeadStore = I;
582 unsigned StoreSize = 0;
583
584 // Collect the chain into a list.
585 while (Tails.count(I) || Heads.count(I)) {
586 if (TransformedStores.count(I))
587 break;
588 AdjacentStores.insert(I);
589
590 StoreSize += getStoreSizeInBytes(I, DL);
591 // Move to the next value in the chain.
592 I = ConsecutiveChain[I];
593 }
594
595 Value *StoredVal = HeadStore->getValueOperand();
596 Value *StorePtr = HeadStore->getPointerOperand();
597 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000598 APInt Stride = getStoreStride(StoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000599
600 // Check to see if the stride matches the size of the stores. If so, then
601 // we know that every byte is touched in the loop.
602 if (StoreSize != Stride && StoreSize != -Stride)
603 continue;
604
605 bool NegStride = StoreSize == -Stride;
606
607 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
608 StoredVal, HeadStore, AdjacentStores, StoreEv,
609 BECount, NegStride)) {
610 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
611 Changed = true;
612 }
613 }
614
615 return Changed;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000616}
617
Chris Lattner86438102011-01-04 07:46:33 +0000618/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000619bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
620 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000621 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000622 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
623 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000624
Chris Lattnere6b261f2011-02-18 22:22:15 +0000625 // If we're not allowed to hack on memset, we fail.
626 if (!TLI->has(LibFunc::memset))
627 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000628
Chris Lattner86438102011-01-04 07:46:33 +0000629 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000630
Chris Lattner86438102011-01-04 07:46:33 +0000631 // See if the pointer expression is an AddRec like {base,+,1} on the current
632 // loop, which indicates a strided store. If we have something else, it's a
633 // random store we can't handle.
634 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000635 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000636 return false;
637
638 // Reject memsets that are so large that they overflow an unsigned.
639 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
640 if ((SizeInBytes >> 32) != 0)
641 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000642
Chris Lattner86438102011-01-04 07:46:33 +0000643 // Check to see if the stride matches the size of the memset. If so, then we
644 // know that every byte is touched in the loop.
Chad Rosier81362a82016-02-12 21:03:23 +0000645 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
646 if (!ConstStride)
647 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000648
Chad Rosier81362a82016-02-12 21:03:23 +0000649 APInt Stride = ConstStride->getAPInt();
650 if (SizeInBytes != Stride && SizeInBytes != -Stride)
Chris Lattner86438102011-01-04 07:46:33 +0000651 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000652
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000653 // Verify that the memset value is loop invariant. If not, we can't promote
654 // the memset.
655 Value *SplatValue = MSI->getValue();
656 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
657 return false;
658
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000659 SmallPtrSet<Instruction *, 1> MSIs;
660 MSIs.insert(MSI);
Chad Rosier81362a82016-02-12 21:03:23 +0000661 bool NegStride = SizeInBytes == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000662 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000663 MSI->getAlignment(), SplatValue, MSI, MSIs, Ev,
Chad Rosier81362a82016-02-12 21:03:23 +0000664 BECount, NegStride);
Chris Lattner86438102011-01-04 07:46:33 +0000665}
666
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000667/// mayLoopAccessLocation - Return true if the specified loop might access the
668/// specified pointer location, which is a loop-strided access. The 'Access'
669/// argument specifies what the verboten forms of access are (read or write).
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000670static bool
671mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
672 const SCEV *BECount, unsigned StoreSize,
673 AliasAnalysis &AA,
674 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000675 // Get the location that may be stored across the loop. Since the access is
676 // strided positively through memory, we say that the modified location starts
677 // at the pointer and has infinite size.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000678 uint64_t AccessSize = MemoryLocation::UnknownSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000679
680 // If the loop iterates a fixed number of times, we can refine the access size
681 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
682 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Chandler Carruthbad690e2015-08-12 23:06:37 +0000683 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000684
685 // TODO: For this to be really effective, we have to dive into the pointer
686 // operand in the store. Store to &A[i] of 100 will always return may alias
687 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
688 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000689 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000690
691 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
692 ++BI)
693 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000694 if (IgnoredStores.count(&*I) == 0 &&
695 (AA.getModRefInfo(&*I, StoreLoc) & Access))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000696 return true;
697
698 return false;
699}
700
Chad Rosiered0c7d12015-11-13 19:11:07 +0000701// If we have a negative stride, Start refers to the end of the memory location
702// we're trying to memset. Therefore, we need to recompute the base pointer,
703// which is just Start - BECount*Size.
704static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
705 Type *IntPtr, unsigned StoreSize,
706 ScalarEvolution *SE) {
707 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
708 if (StoreSize != 1)
709 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
710 SCEV::FlagNUW);
711 return SE->getMinusSCEV(Start, Index);
712}
713
Chris Lattner0f4a6402011-02-19 19:31:39 +0000714/// processLoopStridedStore - We see a strided store of some value. If we can
715/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000716bool LoopIdiomRecognize::processLoopStridedStore(
717 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000718 Value *StoredVal, Instruction *TheStore,
719 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
Chad Rosier79676142015-10-28 14:38:49 +0000720 const SCEV *BECount, bool NegStride) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000721 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000722 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000723
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000724 if (!SplatValue)
725 PatternValue = getMemSetPatternValue(StoredVal, DL);
726
727 assert((SplatValue || PatternValue) &&
728 "Expected either splat value or pattern value.");
Andrew Trick328b2232011-03-14 16:48:10 +0000729
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000730 // The trip count of the loop and the base pointer of the addrec SCEV is
731 // guaranteed to be loop invariant, which means that it should dominate the
732 // header. This allows us to insert code for it in the preheader.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000733 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000734 BasicBlock *Preheader = CurLoop->getLoopPreheader();
735 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000736 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000737
Matt Arsenault009faed2013-09-11 05:09:42 +0000738 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000739 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000740
741 const SCEV *Start = Ev->getStart();
Chad Rosier2fa50a72015-11-13 19:13:40 +0000742 // Handle negative strided loops.
Chad Rosiered0c7d12015-11-13 19:11:07 +0000743 if (NegStride)
744 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
Matt Arsenault009faed2013-09-11 05:09:42 +0000745
Chris Lattner29e14ed2010-12-26 23:42:51 +0000746 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000747 // this into a memset in the loop preheader now if we want. However, this
748 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000749 // or write to the aliased location. Check for any overlap by generating the
750 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000751 Value *BasePtr =
752 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Chandler Carruth194f59c2015-07-22 23:15:57 +0000753 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000754 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000755 Expander.clear();
756 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000757 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000758 return false;
759 }
760
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000761 // Okay, everything looks good, insert the memset.
762
Chris Lattner29e14ed2010-12-26 23:42:51 +0000763 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
764 // pointer size if it isn't already.
Chris Lattner0ba473c2011-01-04 00:06:55 +0000765 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Andrew Trick328b2232011-03-14 16:48:10 +0000766
Chandler Carruthbad690e2015-08-12 23:06:37 +0000767 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000768 SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000769 if (StoreSize != 1) {
Chris Lattner29e14ed2010-12-26 23:42:51 +0000770 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000771 SCEV::FlagNUW);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000772 }
Andrew Trick328b2232011-03-14 16:48:10 +0000773
774 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000775 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000776
Devang Pateld00c6282011-03-07 22:43:45 +0000777 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000778 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000779 NewCall =
780 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000781 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000782 // Everything is emitted in default address space
783 Type *Int8PtrTy = DestInt8PtrTy;
784
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000785 Module *M = TheStore->getModule();
Chandler Carruthbad690e2015-08-12 23:06:37 +0000786 Value *MSP =
787 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
788 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
Andrew Trick328b2232011-03-14 16:48:10 +0000789
Chris Lattner0f4a6402011-02-19 19:31:39 +0000790 // Otherwise we should form a memset_pattern16. PatternValue is known to be
791 // an constant array of 16-bytes. Plop the value into a mergable global.
792 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000793 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000794 PatternValue, ".memset_pattern");
795 GV->setUnnamedAddr(true); // Ok to merge these.
796 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000797 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000798 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000799 }
Andrew Trick328b2232011-03-14 16:48:10 +0000800
Chris Lattner29e14ed2010-12-26 23:42:51 +0000801 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattner86438102011-01-04 07:46:33 +0000802 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000803 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000804
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000805 // Okay, the memset has been formed. Zap the original store and anything that
806 // feeds into it.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000807 for (auto *I : Stores)
808 deleteDeadInstruction(I, TLI);
Chris Lattner12f91be2011-01-02 07:36:44 +0000809 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000810 return true;
811}
812
Chad Rosier1cd3da12015-11-19 21:33:07 +0000813/// If the stored value is a strided load in the same loop with the same stride
814/// this may be transformable into a memcpy. This kicks in for stuff like
815/// for (i) A[i] = B[i];
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000816bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
817 const SCEV *BECount) {
818 assert(SI->isSimple() && "Expected only non-volatile stores.");
819
820 Value *StorePtr = SI->getPointerOperand();
821 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000822 APInt Stride = getStoreStride(StoreEv);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000823 unsigned StoreSize = getStoreSizeInBytes(SI, DL);
824 bool NegStride = StoreSize == -Stride;
Andrew Trick328b2232011-03-14 16:48:10 +0000825
Chad Rosierfddc01f2015-11-19 18:22:21 +0000826 // The store must be feeding a non-volatile load.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000827 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
828 assert(LI->isSimple() && "Expected only non-volatile stores.");
Chad Rosierfddc01f2015-11-19 18:22:21 +0000829
830 // See if the pointer expression is an AddRec like {base,+,1} on the current
831 // loop, which indicates a strided load. If we have something else, it's a
832 // random load we can't handle.
Chad Rosier3ecc8d82015-11-19 18:25:11 +0000833 const SCEVAddRecExpr *LoadEv =
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000834 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
Andrew Trick328b2232011-03-14 16:48:10 +0000835
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000836 // The trip count of the loop and the base pointer of the addrec SCEV is
837 // guaranteed to be loop invariant, which means that it should dominate the
838 // header. This allows us to insert code for it in the preheader.
839 BasicBlock *Preheader = CurLoop->getLoopPreheader();
840 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000841 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000842
Chad Rosiercc299b62015-11-13 21:51:02 +0000843 const SCEV *StrStart = StoreEv->getStart();
844 unsigned StrAS = SI->getPointerAddressSpace();
845 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
846
847 // Handle negative strided loops.
848 if (NegStride)
849 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
850
Chris Lattner85b6d812011-01-02 03:37:56 +0000851 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000852 // this into a memcpy in the loop preheader now if we want. However, this
853 // would be unsafe to do if there is anything else in the loop that may read
854 // or write the memory region we're storing to. This includes the load that
855 // feeds the stores. Check for an alias by generating the base address and
856 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000857 Value *StoreBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000858 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000859
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000860 SmallPtrSet<Instruction *, 1> Stores;
861 Stores.insert(SI);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000862 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000863 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000864 Expander.clear();
865 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000866 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000867 return false;
868 }
869
Chad Rosiercc299b62015-11-13 21:51:02 +0000870 const SCEV *LdStart = LoadEv->getStart();
871 unsigned LdAS = LI->getPointerAddressSpace();
872
873 // Handle negative strided loops.
874 if (NegStride)
875 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
876
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000877 // For a memcpy, we have to make sure that the input array is not being
878 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000879 Value *LoadBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +0000880 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000881
Chandler Carruth194f59c2015-07-22 23:15:57 +0000882 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000883 *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000884 Expander.clear();
885 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000886 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
887 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000888 return false;
889 }
890
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000891 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000892
Chris Lattner85b6d812011-01-02 03:37:56 +0000893 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
894 // pointer size if it isn't already.
Matt Arsenault009faed2013-09-11 05:09:42 +0000895 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
Andrew Trick328b2232011-03-14 16:48:10 +0000896
Chandler Carruthbad690e2015-08-12 23:06:37 +0000897 const SCEV *NumBytesS =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000898 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
Chris Lattner85b6d812011-01-02 03:37:56 +0000899 if (StoreSize != 1)
Matt Arsenault009faed2013-09-11 05:09:42 +0000900 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
Andrew Trick8b55b732011-03-14 16:50:06 +0000901 SCEV::FlagNUW);
Andrew Trick328b2232011-03-14 16:48:10 +0000902
Chris Lattner85b6d812011-01-02 03:37:56 +0000903 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000904 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000905
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000906 CallInst *NewCall =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000907 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000908 std::min(SI->getAlignment(), LI->getAlignment()));
Devang Patel0daa07e2011-05-04 21:37:05 +0000909 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000910
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000911 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
Chris Lattner85b6d812011-01-02 03:37:56 +0000912 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
913 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000914
Chad Rosier7f08d802015-10-13 20:59:16 +0000915 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +0000916 // feeds into it.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000917 deleteDeadInstruction(SI, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000918 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +0000919 return true;
920}
Chandler Carruthd9c60702015-08-13 00:10:03 +0000921
922bool LoopIdiomRecognize::runOnNoncountableLoop() {
Chad Rosier19dc92d2015-11-09 16:56:06 +0000923 return recognizePopcount();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000924}
Chandler Carruth8219a502015-08-13 00:44:29 +0000925
926/// Check if the given conditional branch is based on the comparison between
927/// a variable and zero, and if the variable is non-zero, the control yields to
928/// the loop entry. If the branch matches the behavior, the variable involved
929/// in the comparion is returned. This function will be called to see if the
930/// precondition and postcondition of the loop are in desirable form.
931static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
932 if (!BI || !BI->isConditional())
933 return nullptr;
934
935 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
936 if (!Cond)
937 return nullptr;
938
939 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
940 if (!CmpZero || !CmpZero->isZero())
941 return nullptr;
942
943 ICmpInst::Predicate Pred = Cond->getPredicate();
944 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
945 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
946 return Cond->getOperand(0);
947
948 return nullptr;
949}
950
951/// Return true iff the idiom is detected in the loop.
952///
953/// Additionally:
954/// 1) \p CntInst is set to the instruction counting the population bit.
955/// 2) \p CntPhi is set to the corresponding phi node.
956/// 3) \p Var is set to the value whose population bits are being counted.
957///
958/// The core idiom we are trying to detect is:
959/// \code
960/// if (x0 != 0)
961/// goto loop-exit // the precondition of the loop
962/// cnt0 = init-val;
963/// do {
964/// x1 = phi (x0, x2);
965/// cnt1 = phi(cnt0, cnt2);
966///
967/// cnt2 = cnt1 + 1;
968/// ...
969/// x2 = x1 & (x1 - 1);
970/// ...
971/// } while(x != 0);
972///
973/// loop-exit:
974/// \endcode
975static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
976 Instruction *&CntInst, PHINode *&CntPhi,
977 Value *&Var) {
978 // step 1: Check to see if the look-back branch match this pattern:
979 // "if (a!=0) goto loop-entry".
980 BasicBlock *LoopEntry;
981 Instruction *DefX2, *CountInst;
982 Value *VarX1, *VarX0;
983 PHINode *PhiX, *CountPhi;
984
985 DefX2 = CountInst = nullptr;
986 VarX1 = VarX0 = nullptr;
987 PhiX = CountPhi = nullptr;
988 LoopEntry = *(CurLoop->block_begin());
989
990 // step 1: Check if the loop-back branch is in desirable form.
991 {
992 if (Value *T = matchCondition(
993 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
994 DefX2 = dyn_cast<Instruction>(T);
995 else
996 return false;
997 }
998
999 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1000 {
1001 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1002 return false;
1003
1004 BinaryOperator *SubOneOp;
1005
1006 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1007 VarX1 = DefX2->getOperand(1);
1008 else {
1009 VarX1 = DefX2->getOperand(0);
1010 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1011 }
1012 if (!SubOneOp)
1013 return false;
1014
1015 Instruction *SubInst = cast<Instruction>(SubOneOp);
1016 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
1017 if (!Dec ||
1018 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1019 (SubInst->getOpcode() == Instruction::Add &&
1020 Dec->isAllOnesValue()))) {
1021 return false;
1022 }
1023 }
1024
1025 // step 3: Check the recurrence of variable X
1026 {
1027 PhiX = dyn_cast<PHINode>(VarX1);
1028 if (!PhiX ||
1029 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
1030 return false;
1031 }
1032 }
1033
1034 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1035 {
1036 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001037 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +00001038 IterE = LoopEntry->end();
1039 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001040 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +00001041 if (Inst->getOpcode() != Instruction::Add)
1042 continue;
1043
1044 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1045 if (!Inc || !Inc->isOne())
1046 continue;
1047
1048 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
1049 if (!Phi || Phi->getParent() != LoopEntry)
1050 continue;
1051
1052 // Check if the result of the instruction is live of the loop.
1053 bool LiveOutLoop = false;
1054 for (User *U : Inst->users()) {
1055 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1056 LiveOutLoop = true;
1057 break;
1058 }
1059 }
1060
1061 if (LiveOutLoop) {
1062 CountInst = Inst;
1063 CountPhi = Phi;
1064 break;
1065 }
1066 }
1067
1068 if (!CountInst)
1069 return false;
1070 }
1071
1072 // step 5: check if the precondition is in this form:
1073 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1074 {
1075 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1076 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1077 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1078 return false;
1079
1080 CntInst = CountInst;
1081 CntPhi = CountPhi;
1082 Var = T;
1083 }
1084
1085 return true;
1086}
1087
1088/// Recognizes a population count idiom in a non-countable loop.
1089///
1090/// If detected, transforms the relevant code to issue the popcount intrinsic
1091/// function call, and returns true; otherwise, returns false.
1092bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +00001093 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1094 return false;
1095
1096 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001097 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +00001098 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1099 // in a compact loop.
1100
Renato Golin655348f2015-08-13 11:25:38 +00001101 // Give up if the loop has multiple blocks or multiple backedges.
1102 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001103 return false;
1104
Renato Golin655348f2015-08-13 11:25:38 +00001105 BasicBlock *LoopBody = *(CurLoop->block_begin());
1106 if (LoopBody->size() >= 20) {
1107 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +00001108 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001109 }
Chandler Carruth8219a502015-08-13 00:44:29 +00001110
1111 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +00001112 BasicBlock *PH = CurLoop->getLoopPreheader();
1113 if (!PH)
Chandler Carruth8219a502015-08-13 00:44:29 +00001114 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001115 if (&PH->front() != PH->getTerminator())
1116 return false;
1117 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001118 if (!EntryBI || EntryBI->isConditional())
1119 return false;
1120
1121 // It should have a precondition block where the generated popcount instrinsic
1122 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +00001123 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +00001124 if (!PreCondBB)
1125 return false;
1126 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1127 if (!PreCondBI || PreCondBI->isUnconditional())
1128 return false;
1129
1130 Instruction *CntInst;
1131 PHINode *CntPhi;
1132 Value *Val;
1133 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1134 return false;
1135
1136 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1137 return true;
1138}
1139
1140static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1141 DebugLoc DL) {
1142 Value *Ops[] = {Val};
1143 Type *Tys[] = {Val->getType()};
1144
1145 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1146 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1147 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1148 CI->setDebugLoc(DL);
1149
1150 return CI;
1151}
1152
1153void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1154 Instruction *CntInst,
1155 PHINode *CntPhi, Value *Var) {
1156 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1157 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1158 const DebugLoc DL = CntInst->getDebugLoc();
1159
1160 // Assuming before transformation, the loop is following:
1161 // if (x) // the precondition
1162 // do { cnt++; x &= x - 1; } while(x);
1163
1164 // Step 1: Insert the ctpop instruction at the end of the precondition block
1165 IRBuilder<> Builder(PreCondBr);
1166 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1167 {
1168 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1169 NewCount = PopCntZext =
1170 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1171
1172 if (NewCount != PopCnt)
1173 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1174
1175 // TripCnt is exactly the number of iterations the loop has
1176 TripCnt = NewCount;
1177
1178 // If the population counter's initial value is not zero, insert Add Inst.
1179 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1180 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1181 if (!InitConst || !InitConst->isZero()) {
1182 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1183 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1184 }
1185 }
1186
Nick Lewycky2c852542015-08-19 06:22:33 +00001187 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +00001188 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001189 // function would be partial dead code, and downstream passes will drag
1190 // it back from the precondition block to the preheader.
1191 {
1192 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1193
1194 Value *Opnd0 = PopCntZext;
1195 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1196 if (PreCond->getOperand(0) != Var)
1197 std::swap(Opnd0, Opnd1);
1198
1199 ICmpInst *NewPreCond = cast<ICmpInst>(
1200 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1201 PreCondBr->setCondition(NewPreCond);
1202
1203 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1204 }
1205
1206 // Step 3: Note that the population count is exactly the trip count of the
Nick Lewycky1098e492015-08-19 06:25:30 +00001207 // loop in question, which enable us to to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +00001208 // loop into a countable one. The benefit is twofold:
1209 //
Nick Lewycky2c852542015-08-19 06:22:33 +00001210 // - If the loop only counts population, the entire loop becomes dead after
1211 // the transformation. It is a lot easier to prove a countable loop dead
1212 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +00001213 // isn't dead even if it computes nothing useful. In general, DCE needs
1214 // to prove a noncountable loop finite before safely delete it.)
1215 //
1216 // - If the loop also performs something else, it remains alive.
1217 // Since it is transformed to countable form, it can be aggressively
1218 // optimized by some optimizations which are in general not applicable
1219 // to a noncountable loop.
1220 //
1221 // After this step, this loop (conceptually) would look like following:
1222 // newcnt = __builtin_ctpop(x);
1223 // t = newcnt;
1224 // if (x)
1225 // do { cnt++; x &= x-1; t--) } while (t > 0);
1226 BasicBlock *Body = *(CurLoop->block_begin());
1227 {
1228 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1229 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1230 Type *Ty = TripCnt->getType();
1231
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001232 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +00001233
1234 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +00001235 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +00001236 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1237 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +00001238
1239 TcPhi->addIncoming(TripCnt, PreHead);
1240 TcPhi->addIncoming(TcDec, Body);
1241
1242 CmpInst::Predicate Pred =
1243 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1244 LbCond->setPredicate(Pred);
1245 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001246 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001247 }
1248
1249 // Step 4: All the references to the original population counter outside
1250 // the loop are replaced with the NewCount -- the value returned from
1251 // __builtin_ctpop().
1252 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1253
1254 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1255 // loop. The loop would otherwise not be deleted even if it becomes empty.
1256 SE->forgetLoop(CurLoop);
1257}