blob: 055d3054222fb0df12be96a152f4ccf01a907c39 [file] [log] [blame]
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001//===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner81ae3f22010-12-26 19:39:38 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements an idiom recognizer that transforms simple loops into a
10// non-loop form. In cases that this kicks in, it can be a significant
11// performance win.
12//
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +000013// If compiling for code size we avoid idiom recognition if the resulting
14// code could be larger than the code for the original loop. One way this could
15// happen is if the loop is not removable after idiom recognition due to the
16// presence of non-idiom instructions. The initial implementation of the
17// heuristics applies to idioms in multi-block loops.
18//
Chris Lattner81ae3f22010-12-26 19:39:38 +000019//===----------------------------------------------------------------------===//
Chris Lattner0469e012011-01-02 18:32:09 +000020//
21// TODO List:
22//
23// Future loop memory idioms to recognize:
Chandler Carruth099f5cb02012-11-02 08:33:25 +000024// memcmp, memmove, strlen, etc.
Chris Lattner0469e012011-01-02 18:32:09 +000025// Future floating point idioms to recognize in -ffast-math mode:
26// fpowi
27// Future integer operation idioms to recognize:
Craig Topperc9a60002018-12-26 21:59:48 +000028// ctpop
Chris Lattner0469e012011-01-02 18:32:09 +000029//
30// Beware that isel's default lowering for ctpop is highly inefficient for
31// i64 and larger types when i64 is legal and the value has few bits set. It
32// would be good to enhance isel to emit a loop for ctpop in this case.
33//
Chris Lattner02a97762011-01-03 01:10:08 +000034// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner8fac5db2011-01-02 23:19:45 +000035// replace them with calls to BLAS (if linked in??).
36//
Chris Lattner0469e012011-01-02 18:32:09 +000037//===----------------------------------------------------------------------===//
Chris Lattner81ae3f22010-12-26 19:39:38 +000038
Roman Lebedevfae2e462019-05-30 13:01:53 +000039#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000040#include "llvm/ADT/APInt.h"
41#include "llvm/ADT/ArrayRef.h"
42#include "llvm/ADT/DenseMap.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000043#include "llvm/ADT/MapVector.h"
44#include "llvm/ADT/SetVector.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000045#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000048#include "llvm/ADT/StringRef.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000049#include "llvm/Analysis/AliasAnalysis.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000050#include "llvm/Analysis/LoopAccessAnalysis.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000051#include "llvm/Analysis/LoopInfo.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000052#include "llvm/Analysis/LoopPass.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000053#include "llvm/Analysis/MemoryLocation.h"
54#include "llvm/Analysis/ScalarEvolution.h"
Chad Rosiera15b4b62015-11-23 21:09:13 +000055#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000056#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000057#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000058#include "llvm/Analysis/TargetTransformInfo.h"
Chris Lattner7c5f9c32010-12-26 20:45:45 +000059#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000060#include "llvm/IR/Attributes.h"
61#include "llvm/IR/BasicBlock.h"
62#include "llvm/IR/Constant.h"
63#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000064#include "llvm/IR/DataLayout.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000065#include "llvm/IR/DebugLoc.h"
66#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000067#include "llvm/IR/Dominators.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000068#include "llvm/IR/GlobalValue.h"
69#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000070#include "llvm/IR/IRBuilder.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000071#include "llvm/IR/InstrTypes.h"
72#include "llvm/IR/Instruction.h"
73#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000074#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000075#include "llvm/IR/Intrinsics.h"
76#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000077#include "llvm/IR/Module.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000078#include "llvm/IR/PassManager.h"
79#include "llvm/IR/Type.h"
80#include "llvm/IR/User.h"
81#include "llvm/IR/Value.h"
82#include "llvm/IR/ValueHandle.h"
83#include "llvm/Pass.h"
84#include "llvm/Support/Casting.h"
85#include "llvm/Support/CommandLine.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000086#include "llvm/Support/Debug.h"
87#include "llvm/Support/raw_ostream.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000088#include "llvm/Transforms/Scalar.h"
Ahmed Bougachaace97c12016-04-27 19:04:50 +000089#include "llvm/Transforms/Utils/BuildLibCalls.h"
Roman Lebedevfae2e462019-05-30 13:01:53 +000090#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000091#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000092#include <algorithm>
93#include <cassert>
94#include <cstdint>
95#include <utility>
96#include <vector>
97
Chris Lattner81ae3f22010-12-26 19:39:38 +000098using namespace llvm;
99
Chandler Carruth964daaa2014-04-22 02:55:47 +0000100#define DEBUG_TYPE "loop-idiom"
101
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000102STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
103STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattner81ae3f22010-12-26 19:39:38 +0000104
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000105static cl::opt<bool> UseLIRCodeSizeHeurs(
106 "use-lir-code-size-heurs",
107 cl::desc("Use loop idiom recognition code size heuristics when compiling"
108 "with -Os/-Oz"),
109 cl::init(true), cl::Hidden);
110
Chris Lattner81ae3f22010-12-26 19:39:38 +0000111namespace {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000112
Dehao Chenb9f8e292016-07-12 18:45:51 +0000113class LoopIdiomRecognize {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000114 Loop *CurLoop = nullptr;
Chandler Carruthbf143e22015-08-14 00:21:10 +0000115 AliasAnalysis *AA;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000116 DominatorTree *DT;
Chandler Carruth18c26692015-08-13 09:27:01 +0000117 LoopInfo *LI;
Chandler Carruthbad690e2015-08-12 23:06:37 +0000118 ScalarEvolution *SE;
119 TargetLibraryInfo *TLI;
120 const TargetTransformInfo *TTI;
Chad Rosier43f9b482015-11-06 16:33:57 +0000121 const DataLayout *DL;
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000122 bool ApplyCodeSizeHeuristics;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000123
Chandler Carruthbad690e2015-08-12 23:06:37 +0000124public:
Dehao Chenb9f8e292016-07-12 18:45:51 +0000125 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
126 LoopInfo *LI, ScalarEvolution *SE,
127 TargetLibraryInfo *TLI,
128 const TargetTransformInfo *TTI,
129 const DataLayout *DL)
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000130 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL) {}
Chris Lattner81ae3f22010-12-26 19:39:38 +0000131
Dehao Chenb9f8e292016-07-12 18:45:51 +0000132 bool runOnLoop(Loop *L);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000133
Chandler Carruthbad690e2015-08-12 23:06:37 +0000134private:
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000135 using StoreList = SmallVector<StoreInst *, 8>;
136 using StoreListMap = MapVector<Value *, StoreList>;
137
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000138 StoreListMap StoreRefsForMemset;
139 StoreListMap StoreRefsForMemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000140 StoreList StoreRefsForMemcpy;
141 bool HasMemset;
142 bool HasMemsetPattern;
143 bool HasMemcpy;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000144
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000145 /// Return code for isLegalStore()
146 enum LegalStoreKind {
Anna Thomasae3f752f2017-05-19 18:00:30 +0000147 None = 0,
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000148 Memset,
149 MemsetPattern,
150 Memcpy,
Anna Thomasb2a212c2017-06-06 16:45:25 +0000151 UnorderedAtomicMemcpy,
Anna Thomasae3f752f2017-05-19 18:00:30 +0000152 DontUse // Dummy retval never to be used. Allows catching errors in retval
153 // handling.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000154 };
Chad Rosiercc9030b2015-11-11 23:00:59 +0000155
Chandler Carruthd9c60702015-08-13 00:10:03 +0000156 /// \name Countable Loop Idiom Handling
157 /// @{
158
Chandler Carruthbad690e2015-08-12 23:06:37 +0000159 bool runOnCountableLoop();
Chandler Carruthd9c60702015-08-13 00:10:03 +0000160 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
161 SmallVectorImpl<BasicBlock *> &ExitBlocks);
162
Chad Rosiercc9030b2015-11-11 23:00:59 +0000163 void collectStores(BasicBlock *BB);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000164 LegalStoreKind isLegalStore(StoreInst *SI);
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000165 enum class ForMemset { No, Yes };
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000166 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000167 ForMemset For);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000168 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
169
170 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000171 unsigned StoreAlignment, Value *StoredVal,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000172 Instruction *TheStore,
173 SmallPtrSetImpl<Instruction *> &Stores,
174 const SCEVAddRecExpr *Ev, const SCEV *BECount,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000175 bool NegStride, bool IsLoopMemset = false);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000176 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000177 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
178 bool IsLoopMemset = false);
Chandler Carruthd9c60702015-08-13 00:10:03 +0000179
180 /// @}
181 /// \name Noncountable Loop Idiom Handling
182 /// @{
183
184 bool runOnNoncountableLoop();
185
Chandler Carruth8219a502015-08-13 00:44:29 +0000186 bool recognizePopcount();
187 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
188 PHINode *CntPhi, Value *Var);
Craig Topperc9a60002018-12-26 21:59:48 +0000189 bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz
190 void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB,
191 Instruction *CntInst, PHINode *CntPhi,
192 Value *Var, Instruction *DefX,
Craig Topper28352782018-07-08 01:45:47 +0000193 const DebugLoc &DL, bool ZeroCheck,
194 bool IsCntPhiUsedOutsideLoop);
Chandler Carruth8219a502015-08-13 00:44:29 +0000195
Chandler Carruthd9c60702015-08-13 00:10:03 +0000196 /// @}
Chandler Carruthbad690e2015-08-12 23:06:37 +0000197};
198
Dehao Chenb9f8e292016-07-12 18:45:51 +0000199class LoopIdiomRecognizeLegacyPass : public LoopPass {
200public:
201 static char ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000202
Dehao Chenb9f8e292016-07-12 18:45:51 +0000203 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
204 initializeLoopIdiomRecognizeLegacyPassPass(
205 *PassRegistry::getPassRegistry());
206 }
207
208 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
209 if (skipLoop(L))
210 return false;
211
212 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
213 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
214 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
215 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
216 TargetLibraryInfo *TLI =
217 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
218 const TargetTransformInfo *TTI =
219 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
220 *L->getHeader()->getParent());
221 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
222
223 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
224 return LIR.runOnLoop(L);
225 }
226
227 /// This transformation requires natural loop information & requires that
228 /// loop preheaders be inserted into the CFG.
Dehao Chenb9f8e292016-07-12 18:45:51 +0000229 void getAnalysisUsage(AnalysisUsage &AU) const override {
230 AU.addRequired<TargetLibraryInfoWrapperPass>();
231 AU.addRequired<TargetTransformInfoWrapperPass>();
232 getLoopAnalysisUsage(AU);
233 }
234};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000235
236} // end anonymous namespace
237
238char LoopIdiomRecognizeLegacyPass::ID = 0;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000239
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000240PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
241 LoopStandardAnalysisResults &AR,
242 LPMUpdater &) {
Dehao Chenb9f8e292016-07-12 18:45:51 +0000243 const auto *DL = &L.getHeader()->getModule()->getDataLayout();
Dehao Chenb9f8e292016-07-12 18:45:51 +0000244
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000245 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, DL);
Dehao Chenb9f8e292016-07-12 18:45:51 +0000246 if (!LIR.runOnLoop(&L))
247 return PreservedAnalyses::all();
248
249 return getLoopPassPreservedAnalyses();
250}
251
Dehao Chenb9f8e292016-07-12 18:45:51 +0000252INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
253 "Recognize loop idioms", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000254INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000255INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000256INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Dehao Chenb9f8e292016-07-12 18:45:51 +0000257INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
258 "Recognize loop idioms", false, false)
Chris Lattner81ae3f22010-12-26 19:39:38 +0000259
Dehao Chenb9f8e292016-07-12 18:45:51 +0000260Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
Chris Lattner81ae3f22010-12-26 19:39:38 +0000261
David Majnemerc5601df2016-06-20 16:03:25 +0000262static void deleteDeadInstruction(Instruction *I) {
Benjamin Kramerf094d772015-02-07 21:37:08 +0000263 I->replaceAllUsesWith(UndefValue::get(I->getType()));
264 I->eraseFromParent();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000265}
266
Shuxin Yang95de7c32012-12-09 03:12:46 +0000267//===----------------------------------------------------------------------===//
268//
Shuxin Yang95de7c32012-12-09 03:12:46 +0000269// Implementation of LoopIdiomRecognize
270//
271//===----------------------------------------------------------------------===//
272
Dehao Chenb9f8e292016-07-12 18:45:51 +0000273bool LoopIdiomRecognize::runOnLoop(Loop *L) {
Chandler Carruthd9c60702015-08-13 00:10:03 +0000274 CurLoop = L;
Chandler Carruthd9c60702015-08-13 00:10:03 +0000275 // If the loop could not be converted to canonical form, it must have an
276 // indirectbr in it, just give up.
277 if (!L->getLoopPreheader())
278 return false;
279
280 // Disable loop idiom recognition if the function's name is a common idiom.
281 StringRef Name = L->getHeader()->getParent()->getName();
282 if (Name == "memset" || Name == "memcpy")
283 return false;
284
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000285 // Determine if code size heuristics need to be applied.
286 ApplyCodeSizeHeuristics =
Evandro Menezes85bd3972019-04-04 22:40:06 +0000287 L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs;
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000288
David L. Jonesd21529f2017-01-23 23:16:46 +0000289 HasMemset = TLI->has(LibFunc_memset);
290 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
291 HasMemcpy = TLI->has(LibFunc_memcpy);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000292
293 if (HasMemset || HasMemsetPattern || HasMemcpy)
294 if (SE->hasLoopInvariantBackedgeTakenCount(L))
295 return runOnCountableLoop();
Chandler Carruthdc298322015-08-13 01:03:26 +0000296
Chandler Carruthd9c60702015-08-13 00:10:03 +0000297 return runOnNoncountableLoop();
298}
299
Shuxin Yang95de7c32012-12-09 03:12:46 +0000300bool LoopIdiomRecognize::runOnCountableLoop() {
301 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
Davide Italiano8ed04462015-05-11 21:02:34 +0000302 assert(!isa<SCEVCouldNotCompute>(BECount) &&
Chandler Carruthbad690e2015-08-12 23:06:37 +0000303 "runOnCountableLoop() called on a loop without a predictable"
304 "backedge-taken count");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000305
306 // If this loop executes exactly one time, then it should be peeled, not
307 // optimized by this pass.
308 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000309 if (BECst->getAPInt() == 0)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000310 return false;
311
Chandler Carruthbad690e2015-08-12 23:06:37 +0000312 SmallVector<BasicBlock *, 8> ExitBlocks;
Shuxin Yang95de7c32012-12-09 03:12:46 +0000313 CurLoop->getUniqueExitBlocks(ExitBlocks);
314
Roman Lebedev95dec502019-05-29 20:11:53 +0000315 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000316 << CurLoop->getHeader()->getParent()->getName()
Roman Lebedev95dec502019-05-29 20:11:53 +0000317 << "] Countable Loop %" << CurLoop->getHeader()->getName()
318 << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000319
320 bool MadeChange = false;
Haicheng Wua95cd1262016-07-06 21:05:40 +0000321
322 // The following transforms hoist stores/memsets into the loop pre-header.
323 // Give up if the loop has instructions may throw.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000324 SimpleLoopSafetyInfo SafetyInfo;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000325 SafetyInfo.computeLoopSafetyInfo(CurLoop);
326 if (SafetyInfo.anyBlockMayThrow())
Haicheng Wua95cd1262016-07-06 21:05:40 +0000327 return MadeChange;
328
Shuxin Yang95de7c32012-12-09 03:12:46 +0000329 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000330 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000331 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000332 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000333 continue;
334
Davide Italiano80625af2015-05-13 19:51:21 +0000335 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000336 }
337 return MadeChange;
338}
339
Chad Rosier4acff962016-02-12 19:05:27 +0000340static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
Chad Rosiera548fe52015-11-12 19:09:16 +0000341 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
Chad Rosier4acff962016-02-12 19:05:27 +0000342 return ConstStride->getAPInt();
Chad Rosiera548fe52015-11-12 19:09:16 +0000343}
344
Chad Rosier94274fb2015-12-21 14:49:32 +0000345/// getMemSetPatternValue - If a strided store of the specified value is safe to
346/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
347/// be passed in. Otherwise, return null.
348///
349/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
350/// just replicate their input array and then pass on to memset_pattern16.
351static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
JF Bastien73d8e4e2018-09-21 05:17:42 +0000352 // FIXME: This could check for UndefValue because it can be merged into any
353 // other valid pattern.
354
Chad Rosier94274fb2015-12-21 14:49:32 +0000355 // If the value isn't a constant, we can't promote it to being in a constant
356 // array. We could theoretically do a store to an alloca or something, but
357 // that doesn't seem worthwhile.
358 Constant *C = dyn_cast<Constant>(V);
359 if (!C)
360 return nullptr;
361
362 // Only handle simple values that are a power of two bytes in size.
363 uint64_t Size = DL->getTypeSizeInBits(V->getType());
364 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
365 return nullptr;
366
367 // Don't care enough about darwin/ppc to implement this.
368 if (DL->isBigEndian())
369 return nullptr;
370
371 // Convert to size in bytes.
372 Size /= 8;
373
374 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
375 // if the top and bottom are the same (e.g. for vectors and large integers).
376 if (Size > 16)
377 return nullptr;
378
379 // If the constant is exactly 16 bytes, just use it.
380 if (Size == 16)
381 return C;
382
383 // Otherwise, we'll use an array of the constants.
384 unsigned ArraySize = 16 / Size;
385 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
386 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
387}
388
Anna Thomasae3f752f2017-05-19 18:00:30 +0000389LoopIdiomRecognize::LegalStoreKind
390LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
Chad Rosier869962f2015-12-01 14:26:35 +0000391 // Don't touch volatile stores.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000392 if (SI->isVolatile())
393 return LegalStoreKind::None;
394 // We only want simple or unordered-atomic stores.
395 if (!SI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000396 return LegalStoreKind::None;
Chad Rosier869962f2015-12-01 14:26:35 +0000397
Sanjoy Das206f65c2017-04-24 20:12:10 +0000398 // Don't convert stores of non-integral pointer types to memsets (which stores
399 // integers).
400 if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType()))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000401 return LegalStoreKind::None;
Sanjoy Das206f65c2017-04-24 20:12:10 +0000402
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000403 // Avoid merging nontemporal stores.
404 if (SI->getMetadata(LLVMContext::MD_nontemporal))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000405 return LegalStoreKind::None;
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000406
Chad Rosiera548fe52015-11-12 19:09:16 +0000407 Value *StoredVal = SI->getValueOperand();
408 Value *StorePtr = SI->getPointerOperand();
409
410 // Reject stores that are so large that they overflow an unsigned.
411 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
412 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000413 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000414
415 // See if the pointer expression is an AddRec like {base,+,1} on the current
416 // loop, which indicates a strided store. If we have something else, it's a
417 // random store we can't handle.
418 const SCEVAddRecExpr *StoreEv =
419 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
420 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000421 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000422
423 // Check to see if we have a constant stride.
424 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000425 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000426
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000427 // See if the store can be turned into a memset.
428
429 // If the stored value is a byte-wise value (like i32 -1), then it may be
430 // turned into a memset of i8 -1, assuming that all the consecutive bytes
431 // are stored. A store of i32 0x01020304 can never be turned into a memset,
432 // but it can be turned into memset_pattern if the target supports it.
433 Value *SplatValue = isBytewiseValue(StoredVal);
434 Constant *PatternValue = nullptr;
435
Anna Thomasb2a212c2017-06-06 16:45:25 +0000436 // Note: memset and memset_pattern on unordered-atomic is yet not supported
437 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
438
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000439 // If we're allowed to form a memset, and the stored value would be
440 // acceptable for memset, use it.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000441 if (!UnorderedAtomic && HasMemset && SplatValue &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000442 // Verify that the stored value is loop invariant. If not, we can't
443 // promote the memset.
444 CurLoop->isLoopInvariant(SplatValue)) {
445 // It looks like we can use SplatValue.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000446 return LegalStoreKind::Memset;
Anna Thomasb2a212c2017-06-06 16:45:25 +0000447 } else if (!UnorderedAtomic && HasMemsetPattern &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000448 // Don't create memset_pattern16s with address spaces.
449 StorePtr->getType()->getPointerAddressSpace() == 0 &&
450 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
451 // It looks like we can use PatternValue!
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000452 return LegalStoreKind::MemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000453 }
454
455 // Otherwise, see if the store can be turned into a memcpy.
456 if (HasMemcpy) {
457 // Check to see if the stride matches the size of the store. If so, then we
458 // know that every byte is touched in the loop.
Chad Rosier4acff962016-02-12 19:05:27 +0000459 APInt Stride = getStoreStride(StoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000460 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000461 if (StoreSize != Stride && StoreSize != -Stride)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000462 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000463
464 // The store must be feeding a non-volatile load.
465 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +0000466
467 // Only allow non-volatile loads
468 if (!LI || LI->isVolatile())
469 return LegalStoreKind::None;
470 // Only allow simple or unordered-atomic loads
471 if (!LI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000472 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000473
474 // See if the pointer expression is an AddRec like {base,+,1} on the current
475 // loop, which indicates a strided load. If we have something else, it's a
476 // random load we can't handle.
477 const SCEVAddRecExpr *LoadEv =
478 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
479 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000480 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000481
482 // The store and load must share the same stride.
483 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000484 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000485
486 // Success. This store can be converted into a memcpy.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000487 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
488 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
489 : LegalStoreKind::Memcpy;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000490 }
491 // This store can't be transformed into a memset/memcpy.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000492 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000493}
494
Chad Rosiercc9030b2015-11-11 23:00:59 +0000495void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000496 StoreRefsForMemset.clear();
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000497 StoreRefsForMemsetPattern.clear();
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000498 StoreRefsForMemcpy.clear();
Chad Rosiercc9030b2015-11-11 23:00:59 +0000499 for (Instruction &I : *BB) {
500 StoreInst *SI = dyn_cast<StoreInst>(&I);
501 if (!SI)
502 continue;
503
Chad Rosiera548fe52015-11-12 19:09:16 +0000504 // Make sure this is a strided store with a constant stride.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000505 switch (isLegalStore(SI)) {
506 case LegalStoreKind::None:
507 // Nothing to do
508 break;
509 case LegalStoreKind::Memset: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000510 // Find the base pointer.
511 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
512 StoreRefsForMemset[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000513 } break;
514 case LegalStoreKind::MemsetPattern: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000515 // Find the base pointer.
516 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
517 StoreRefsForMemsetPattern[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000518 } break;
519 case LegalStoreKind::Memcpy:
Anna Thomasb2a212c2017-06-06 16:45:25 +0000520 case LegalStoreKind::UnorderedAtomicMemcpy:
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000521 StoreRefsForMemcpy.push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000522 break;
523 default:
524 assert(false && "unhandled return value");
525 break;
526 }
Chad Rosiercc9030b2015-11-11 23:00:59 +0000527 }
528}
529
Chris Lattner8455b6e2011-01-02 19:01:03 +0000530/// runOnLoopBlock - Process the specified block, which lives in a counted loop
531/// with the specified backedge count. This block is known to be in the current
532/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000533bool LoopIdiomRecognize::runOnLoopBlock(
534 BasicBlock *BB, const SCEV *BECount,
535 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000536 // We can only promote stores in this block if they are unconditionally
537 // executed in the loop. For a block to be unconditionally executed, it has
538 // to dominate all the exit blocks of the loop. Verify this now.
539 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
540 if (!DT->dominates(BB, ExitBlocks[i]))
541 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000542
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000543 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000544 // Look for store instructions, which may be optimized to memset/memcpy.
545 collectStores(BB);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000546
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000547 // Look for a single store or sets of stores with a common base, which can be
548 // optimized into a memset (memset_pattern). The latter most commonly happens
549 // with structs and handunrolled loops.
550 for (auto &SL : StoreRefsForMemset)
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000551 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000552
553 for (auto &SL : StoreRefsForMemsetPattern)
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000554 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000555
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000556 // Optimize the store into a memcpy, if it feeds an similarly strided load.
557 for (auto &SI : StoreRefsForMemcpy)
558 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
559
Chandler Carruthbad690e2015-08-12 23:06:37 +0000560 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000561 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000562 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000563 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000564 WeakTrackingVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000565 if (!processLoopMemSet(MSI, BECount))
566 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000567 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000568
Chris Lattner86438102011-01-04 07:46:33 +0000569 // If processing the memset invalidated our iterator, start over from the
570 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000571 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000572 I = BB->begin();
573 continue;
574 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000575 }
Andrew Trick328b2232011-03-14 16:48:10 +0000576
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000577 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000578}
579
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000580/// See if this store(s) can be promoted to a memset.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000581bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000582 const SCEV *BECount, ForMemset For) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000583 // Try to find consecutive stores that can be transformed into memsets.
584 SetVector<StoreInst *> Heads, Tails;
585 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
Chris Lattner86438102011-01-04 07:46:33 +0000586
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000587 // Do a quadratic search on all of the given stores and find
588 // all of the pairs of stores that follow each other.
589 SmallVector<unsigned, 16> IndexQueue;
590 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
591 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
Andrew Trick328b2232011-03-14 16:48:10 +0000592
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000593 Value *FirstStoredVal = SL[i]->getValueOperand();
594 Value *FirstStorePtr = SL[i]->getPointerOperand();
595 const SCEVAddRecExpr *FirstStoreEv =
596 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000597 APInt FirstStride = getStoreStride(FirstStoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000598 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
Chad Rosier79676142015-10-28 14:38:49 +0000599
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000600 // See if we can optimize just this store in isolation.
Chad Rosier4acff962016-02-12 19:05:27 +0000601 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000602 Heads.insert(SL[i]);
603 continue;
604 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000605
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000606 Value *FirstSplatValue = nullptr;
607 Constant *FirstPatternValue = nullptr;
608
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000609 if (For == ForMemset::Yes)
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000610 FirstSplatValue = isBytewiseValue(FirstStoredVal);
611 else
612 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
613
614 assert((FirstSplatValue || FirstPatternValue) &&
615 "Expected either splat value or pattern value.");
616
617 IndexQueue.clear();
618 // If a store has multiple consecutive store candidates, search Stores
619 // array according to the sequence: from i+1 to e, then from i-1 to 0.
620 // This is because usually pairing with immediate succeeding or preceding
621 // candidate create the best chance to find memset opportunity.
622 unsigned j = 0;
623 for (j = i + 1; j < e; ++j)
624 IndexQueue.push_back(j);
625 for (j = i; j > 0; --j)
626 IndexQueue.push_back(j - 1);
627
628 for (auto &k : IndexQueue) {
629 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
630 Value *SecondStorePtr = SL[k]->getPointerOperand();
631 const SCEVAddRecExpr *SecondStoreEv =
632 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000633 APInt SecondStride = getStoreStride(SecondStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000634
635 if (FirstStride != SecondStride)
636 continue;
637
638 Value *SecondStoredVal = SL[k]->getValueOperand();
639 Value *SecondSplatValue = nullptr;
640 Constant *SecondPatternValue = nullptr;
641
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000642 if (For == ForMemset::Yes)
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000643 SecondSplatValue = isBytewiseValue(SecondStoredVal);
644 else
645 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
646
647 assert((SecondSplatValue || SecondPatternValue) &&
648 "Expected either splat value or pattern value.");
649
650 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000651 if (For == ForMemset::Yes) {
JF Bastien73d8e4e2018-09-21 05:17:42 +0000652 if (isa<UndefValue>(FirstSplatValue))
653 FirstSplatValue = SecondSplatValue;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000654 if (FirstSplatValue != SecondSplatValue)
655 continue;
656 } else {
JF Bastien73d8e4e2018-09-21 05:17:42 +0000657 if (isa<UndefValue>(FirstPatternValue))
658 FirstPatternValue = SecondPatternValue;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000659 if (FirstPatternValue != SecondPatternValue)
660 continue;
661 }
662 Tails.insert(SL[k]);
663 Heads.insert(SL[i]);
664 ConsecutiveChain[SL[i]] = SL[k];
665 break;
666 }
667 }
668 }
669
670 // We may run into multiple chains that merge into a single chain. We mark the
671 // stores that we transformed so that we don't visit the same store twice.
672 SmallPtrSet<Value *, 16> TransformedStores;
673 bool Changed = false;
674
675 // For stores that start but don't end a link in the chain:
676 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
677 it != e; ++it) {
678 if (Tails.count(*it))
679 continue;
680
681 // We found a store instr that starts a chain. Now follow the chain and try
682 // to transform it.
683 SmallPtrSet<Instruction *, 8> AdjacentStores;
684 StoreInst *I = *it;
685
686 StoreInst *HeadStore = I;
687 unsigned StoreSize = 0;
688
689 // Collect the chain into a list.
690 while (Tails.count(I) || Heads.count(I)) {
691 if (TransformedStores.count(I))
692 break;
693 AdjacentStores.insert(I);
694
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000695 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000696 // Move to the next value in the chain.
697 I = ConsecutiveChain[I];
698 }
699
700 Value *StoredVal = HeadStore->getValueOperand();
701 Value *StorePtr = HeadStore->getPointerOperand();
702 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000703 APInt Stride = getStoreStride(StoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000704
705 // Check to see if the stride matches the size of the stores. If so, then
706 // we know that every byte is touched in the loop.
707 if (StoreSize != Stride && StoreSize != -Stride)
708 continue;
709
710 bool NegStride = StoreSize == -Stride;
711
712 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
713 StoredVal, HeadStore, AdjacentStores, StoreEv,
714 BECount, NegStride)) {
715 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
716 Changed = true;
717 }
718 }
719
720 return Changed;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000721}
722
Chris Lattner86438102011-01-04 07:46:33 +0000723/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000724bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
725 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000726 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000727 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
728 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000729
Chris Lattnere6b261f2011-02-18 22:22:15 +0000730 // If we're not allowed to hack on memset, we fail.
Ahmed Bougacha7f971932016-04-27 19:04:46 +0000731 if (!HasMemset)
Chris Lattnere6b261f2011-02-18 22:22:15 +0000732 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000733
Chris Lattner86438102011-01-04 07:46:33 +0000734 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000735
Chris Lattner86438102011-01-04 07:46:33 +0000736 // See if the pointer expression is an AddRec like {base,+,1} on the current
737 // loop, which indicates a strided store. If we have something else, it's a
738 // random store we can't handle.
739 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000740 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000741 return false;
742
743 // Reject memsets that are so large that they overflow an unsigned.
744 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
745 if ((SizeInBytes >> 32) != 0)
746 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000747
Chris Lattner86438102011-01-04 07:46:33 +0000748 // Check to see if the stride matches the size of the memset. If so, then we
749 // know that every byte is touched in the loop.
Chad Rosier81362a82016-02-12 21:03:23 +0000750 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
751 if (!ConstStride)
752 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000753
Chad Rosier81362a82016-02-12 21:03:23 +0000754 APInt Stride = ConstStride->getAPInt();
755 if (SizeInBytes != Stride && SizeInBytes != -Stride)
Chris Lattner86438102011-01-04 07:46:33 +0000756 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000757
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000758 // Verify that the memset value is loop invariant. If not, we can't promote
759 // the memset.
760 Value *SplatValue = MSI->getValue();
761 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
762 return false;
763
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000764 SmallPtrSet<Instruction *, 1> MSIs;
765 MSIs.insert(MSI);
Chad Rosier81362a82016-02-12 21:03:23 +0000766 bool NegStride = SizeInBytes == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000767 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Daniel Neilsonfb99a492018-02-08 17:33:08 +0000768 MSI->getDestAlignment(), SplatValue, MSI, MSIs,
769 Ev, BECount, NegStride, /*IsLoopMemset=*/true);
Chris Lattner86438102011-01-04 07:46:33 +0000770}
771
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000772/// mayLoopAccessLocation - Return true if the specified loop might access the
773/// specified pointer location, which is a loop-strided access. The 'Access'
774/// argument specifies what the verboten forms of access are (read or write).
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000775static bool
776mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
777 const SCEV *BECount, unsigned StoreSize,
778 AliasAnalysis &AA,
779 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000780 // Get the location that may be stored across the loop. Since the access is
781 // strided positively through memory, we say that the modified location starts
782 // at the pointer and has infinite size.
George Burgess IV7e128752018-12-24 05:55:50 +0000783 LocationSize AccessSize = LocationSize::unknown();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000784
785 // If the loop iterates a fixed number of times, we can refine the access size
786 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
787 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
George Burgess IV7e128752018-12-24 05:55:50 +0000788 AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) *
789 StoreSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000790
791 // TODO: For this to be really effective, we have to dive into the pointer
792 // operand in the store. Store to &A[i] of 100 will always return may alias
793 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
794 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000795 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000796
797 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
798 ++BI)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000799 for (Instruction &I : **BI)
800 if (IgnoredStores.count(&I) == 0 &&
Alina Sbirlea18fea012017-12-06 19:56:37 +0000801 isModOrRefSet(
802 intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access)))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000803 return true;
804
805 return false;
806}
807
Chad Rosiered0c7d12015-11-13 19:11:07 +0000808// If we have a negative stride, Start refers to the end of the memory location
809// we're trying to memset. Therefore, we need to recompute the base pointer,
810// which is just Start - BECount*Size.
811static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
812 Type *IntPtr, unsigned StoreSize,
813 ScalarEvolution *SE) {
814 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
815 if (StoreSize != 1)
816 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
817 SCEV::FlagNUW);
818 return SE->getMinusSCEV(Start, Index);
819}
820
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000821/// Compute the number of bytes as a SCEV from the backedge taken count.
822///
823/// This also maps the SCEV into the provided type and tries to handle the
824/// computation in a way that will fold cleanly.
825static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
826 unsigned StoreSize, Loop *CurLoop,
827 const DataLayout *DL, ScalarEvolution *SE) {
828 const SCEV *NumBytesS;
829 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
830 // pointer size if it isn't already.
831 //
832 // If we're going to need to zero extend the BE count, check if we can add
833 // one to it prior to zero extending without overflow. Provided this is safe,
834 // it allows better simplification of the +1.
835 if (DL->getTypeSizeInBits(BECount->getType()) <
836 DL->getTypeSizeInBits(IntPtr) &&
837 SE->isLoopEntryGuardedByCond(
838 CurLoop, ICmpInst::ICMP_NE, BECount,
839 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) {
840 NumBytesS = SE->getZeroExtendExpr(
841 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW),
842 IntPtr);
843 } else {
844 NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr),
845 SE->getOne(IntPtr), SCEV::FlagNUW);
846 }
847
848 // And scale it based on the store size.
849 if (StoreSize != 1) {
850 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
851 SCEV::FlagNUW);
852 }
853 return NumBytesS;
854}
855
Chris Lattner0f4a6402011-02-19 19:31:39 +0000856/// processLoopStridedStore - We see a strided store of some value. If we can
857/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000858bool LoopIdiomRecognize::processLoopStridedStore(
859 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000860 Value *StoredVal, Instruction *TheStore,
861 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000862 const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000863 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000864 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000865
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000866 if (!SplatValue)
867 PatternValue = getMemSetPatternValue(StoredVal, DL);
868
869 assert((SplatValue || PatternValue) &&
870 "Expected either splat value or pattern value.");
Andrew Trick328b2232011-03-14 16:48:10 +0000871
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000872 // The trip count of the loop and the base pointer of the addrec SCEV is
873 // guaranteed to be loop invariant, which means that it should dominate the
874 // header. This allows us to insert code for it in the preheader.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000875 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000876 BasicBlock *Preheader = CurLoop->getLoopPreheader();
877 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000878 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000879
Matt Arsenault009faed2013-09-11 05:09:42 +0000880 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000881 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000882
883 const SCEV *Start = Ev->getStart();
Chad Rosier2fa50a72015-11-13 19:13:40 +0000884 // Handle negative strided loops.
Chad Rosiered0c7d12015-11-13 19:11:07 +0000885 if (NegStride)
886 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
Matt Arsenault009faed2013-09-11 05:09:42 +0000887
Aditya Kumar1c42d132017-05-05 14:49:45 +0000888 // TODO: ideally we should still be able to generate memset if SCEV expander
889 // is taught to generate the dependencies at the latest point.
890 if (!isSafeToExpand(Start, *SE))
891 return false;
892
Chris Lattner29e14ed2010-12-26 23:42:51 +0000893 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000894 // this into a memset in the loop preheader now if we want. However, this
895 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000896 // or write to the aliased location. Check for any overlap by generating the
897 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000898 Value *BasePtr =
899 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Alina Sbirlea193429f2017-12-07 22:41:34 +0000900 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
901 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000902 Expander.clear();
903 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000904 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000905 return false;
906 }
907
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000908 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
909 return false;
910
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000911 // Okay, everything looks good, insert the memset.
912
Chandler Carruthbad690e2015-08-12 23:06:37 +0000913 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000914 getNumBytes(BECount, IntPtr, StoreSize, CurLoop, DL, SE);
Andrew Trick328b2232011-03-14 16:48:10 +0000915
Aditya Kumar1c42d132017-05-05 14:49:45 +0000916 // TODO: ideally we should still be able to generate memset if SCEV expander
917 // is taught to generate the dependencies at the latest point.
918 if (!isSafeToExpand(NumBytesS, *SE))
919 return false;
920
Andrew Trick328b2232011-03-14 16:48:10 +0000921 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000922 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000923
Devang Pateld00c6282011-03-07 22:43:45 +0000924 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000925 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000926 NewCall =
927 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000928 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000929 // Everything is emitted in default address space
930 Type *Int8PtrTy = DestInt8PtrTy;
931
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000932 Module *M = TheStore->getModule();
David Bolvansky7c7760d2018-10-16 21:18:31 +0000933 StringRef FuncName = "memset_pattern16";
James Y Knight13680222019-02-01 02:28:03 +0000934 FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(),
935 Int8PtrTy, Int8PtrTy, IntPtr);
David Bolvansky7c7760d2018-10-16 21:18:31 +0000936 inferLibFuncAttributes(M, FuncName, *TLI);
Andrew Trick328b2232011-03-14 16:48:10 +0000937
Chris Lattner0f4a6402011-02-19 19:31:39 +0000938 // Otherwise we should form a memset_pattern16. PatternValue is known to be
939 // an constant array of 16-bytes. Plop the value into a mergable global.
940 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000941 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000942 PatternValue, ".memset_pattern");
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000943 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000944 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000945 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000946 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000947 }
Andrew Trick328b2232011-03-14 16:48:10 +0000948
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000949 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
950 << " from store to: " << *Ev << " at: " << *TheStore
951 << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000952 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000953
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000954 // Okay, the memset has been formed. Zap the original store and anything that
955 // feeds into it.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000956 for (auto *I : Stores)
David Majnemer41ff4fd2016-06-20 16:07:38 +0000957 deleteDeadInstruction(I);
Chris Lattner12f91be2011-01-02 07:36:44 +0000958 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000959 return true;
960}
961
Chad Rosier1cd3da12015-11-19 21:33:07 +0000962/// If the stored value is a strided load in the same loop with the same stride
963/// this may be transformable into a memcpy. This kicks in for stuff like
Xin Tonga41bf702017-05-01 23:08:19 +0000964/// for (i) A[i] = B[i];
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000965bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
966 const SCEV *BECount) {
Anna Thomasb2a212c2017-06-06 16:45:25 +0000967 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000968
969 Value *StorePtr = SI->getPointerOperand();
970 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000971 APInt Stride = getStoreStride(StoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000972 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000973 bool NegStride = StoreSize == -Stride;
Andrew Trick328b2232011-03-14 16:48:10 +0000974
Chad Rosierfddc01f2015-11-19 18:22:21 +0000975 // The store must be feeding a non-volatile load.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000976 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +0000977 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
Chad Rosierfddc01f2015-11-19 18:22:21 +0000978
979 // See if the pointer expression is an AddRec like {base,+,1} on the current
980 // loop, which indicates a strided load. If we have something else, it's a
981 // random load we can't handle.
Chad Rosier3ecc8d82015-11-19 18:25:11 +0000982 const SCEVAddRecExpr *LoadEv =
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000983 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
Andrew Trick328b2232011-03-14 16:48:10 +0000984
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000985 // The trip count of the loop and the base pointer of the addrec SCEV is
986 // guaranteed to be loop invariant, which means that it should dominate the
987 // header. This allows us to insert code for it in the preheader.
988 BasicBlock *Preheader = CurLoop->getLoopPreheader();
989 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000990 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000991
Chad Rosiercc299b62015-11-13 21:51:02 +0000992 const SCEV *StrStart = StoreEv->getStart();
993 unsigned StrAS = SI->getPointerAddressSpace();
994 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
995
996 // Handle negative strided loops.
997 if (NegStride)
998 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
999
Chris Lattner85b6d812011-01-02 03:37:56 +00001000 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001001 // this into a memcpy in the loop preheader now if we want. However, this
1002 // would be unsafe to do if there is anything else in the loop that may read
1003 // or write the memory region we're storing to. This includes the load that
1004 // feeds the stores. Check for an alias by generating the base address and
1005 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001006 Value *StoreBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +00001007 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001008
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001009 SmallPtrSet<Instruction *, 1> Stores;
1010 Stores.insert(SI);
Alina Sbirlea193429f2017-12-07 22:41:34 +00001011 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001012 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001013 Expander.clear();
1014 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001015 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001016 return false;
1017 }
1018
Chad Rosiercc299b62015-11-13 21:51:02 +00001019 const SCEV *LdStart = LoadEv->getStart();
1020 unsigned LdAS = LI->getPointerAddressSpace();
1021
1022 // Handle negative strided loops.
1023 if (NegStride)
1024 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
1025
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001026 // For a memcpy, we have to make sure that the input array is not being
1027 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001028 Value *LoadBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +00001029 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001030
Alina Sbirlea193429f2017-12-07 22:41:34 +00001031 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1032 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001033 Expander.clear();
1034 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001035 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1036 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001037 return false;
1038 }
1039
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001040 if (avoidLIRForMultiBlockLoop())
1041 return false;
1042
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001043 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001044
Chandler Carruthbad690e2015-08-12 23:06:37 +00001045 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +00001046 getNumBytes(BECount, IntPtrTy, StoreSize, CurLoop, DL, SE);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001047
1048 Value *NumBytes =
1049 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1050
Anna Thomasb2a212c2017-06-06 16:45:25 +00001051 CallInst *NewCall = nullptr;
1052 // Check whether to generate an unordered atomic memcpy:
Hiroshi Inouef2096492018-06-14 05:41:49 +00001053 // If the load or store are atomic, then they must necessarily be unordered
Anna Thomasb2a212c2017-06-06 16:45:25 +00001054 // by previous checks.
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001055 if (!SI->isAtomic() && !LI->isAtomic())
Daniel Neilsonfb99a492018-02-08 17:33:08 +00001056 NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlignment(),
1057 LoadBasePtr, LI->getAlignment(), NumBytes);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001058 else {
Anna Thomasb2a212c2017-06-06 16:45:25 +00001059 // We cannot allow unaligned ops for unordered load/store, so reject
1060 // anything where the alignment isn't at least the element size.
Daniel Neilsonfb99a492018-02-08 17:33:08 +00001061 unsigned Align = std::min(SI->getAlignment(), LI->getAlignment());
Anna Thomasb2a212c2017-06-06 16:45:25 +00001062 if (Align < StoreSize)
1063 return false;
1064
1065 // If the element.atomic memcpy is not lowered into explicit
1066 // loads/stores later, then it will be lowered into an element-size
1067 // specific lib call. If the lib call doesn't exist for our store size, then
1068 // we shouldn't generate the memcpy.
1069 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1070 return false;
1071
Daniel Neilson6e4aa1e2017-11-10 19:38:12 +00001072 // Create the call.
1073 // Note that unordered atomic loads/stores are *required* by the spec to
1074 // have an alignment but non-atomic loads/stores may not.
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001075 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
Daniel Neilson6e4aa1e2017-11-10 19:38:12 +00001076 StoreBasePtr, SI->getAlignment(), LoadBasePtr, LI->getAlignment(),
1077 NumBytes, StoreSize);
Anna Thomasb2a212c2017-06-06 16:45:25 +00001078 }
Devang Patel0daa07e2011-05-04 21:37:05 +00001079 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001080
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001081 LLVM_DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
1082 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1083 << " from store ptr=" << *StoreEv << " at: " << *SI
1084 << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001085
Chad Rosier7f08d802015-10-13 20:59:16 +00001086 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +00001087 // feeds into it.
David Majnemer41ff4fd2016-06-20 16:07:38 +00001088 deleteDeadInstruction(SI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001089 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +00001090 return true;
1091}
Chandler Carruthd9c60702015-08-13 00:10:03 +00001092
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001093// When compiling for codesize we avoid idiom recognition for a multi-block loop
1094// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1095//
1096bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1097 bool IsLoopMemset) {
1098 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1099 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001100 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1101 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1102 << " avoided: multi-block top-level loop\n");
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001103 return true;
1104 }
1105 }
1106
1107 return false;
1108}
1109
Chandler Carruthd9c60702015-08-13 00:10:03 +00001110bool LoopIdiomRecognize::runOnNoncountableLoop() {
Roman Lebedev95dec502019-05-29 20:11:53 +00001111 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
1112 << CurLoop->getHeader()->getParent()->getName()
1113 << "] Noncountable Loop %"
1114 << CurLoop->getHeader()->getName() << "\n");
1115
Craig Topperc9a60002018-12-26 21:59:48 +00001116 return recognizePopcount() || recognizeAndInsertFFS();
Chandler Carruthd9c60702015-08-13 00:10:03 +00001117}
Chandler Carruth8219a502015-08-13 00:44:29 +00001118
1119/// Check if the given conditional branch is based on the comparison between
Craig Topperc9a60002018-12-26 21:59:48 +00001120/// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
1121/// true), the control yields to the loop entry. If the branch matches the
1122/// behavior, the variable involved in the comparison is returned. This function
1123/// will be called to see if the precondition and postcondition of the loop are
1124/// in desirable form.
1125static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry,
1126 bool JmpOnZero = false) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001127 if (!BI || !BI->isConditional())
1128 return nullptr;
1129
1130 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1131 if (!Cond)
1132 return nullptr;
1133
1134 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1135 if (!CmpZero || !CmpZero->isZero())
1136 return nullptr;
1137
Craig Topperc9a60002018-12-26 21:59:48 +00001138 BasicBlock *TrueSucc = BI->getSuccessor(0);
1139 BasicBlock *FalseSucc = BI->getSuccessor(1);
1140 if (JmpOnZero)
1141 std::swap(TrueSucc, FalseSucc);
1142
Chandler Carruth8219a502015-08-13 00:44:29 +00001143 ICmpInst::Predicate Pred = Cond->getPredicate();
Craig Topperc9a60002018-12-26 21:59:48 +00001144 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
1145 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
Chandler Carruth8219a502015-08-13 00:44:29 +00001146 return Cond->getOperand(0);
1147
1148 return nullptr;
1149}
1150
Davide Italiano4bc91192017-05-23 22:32:56 +00001151// Check if the recurrence variable `VarX` is in the right form to create
1152// the idiom. Returns the value coerced to a PHINode if so.
1153static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1154 BasicBlock *LoopEntry) {
1155 auto *PhiX = dyn_cast<PHINode>(VarX);
1156 if (PhiX && PhiX->getParent() == LoopEntry &&
1157 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1158 return PhiX;
1159 return nullptr;
1160}
1161
Chandler Carruth8219a502015-08-13 00:44:29 +00001162/// Return true iff the idiom is detected in the loop.
1163///
1164/// Additionally:
1165/// 1) \p CntInst is set to the instruction counting the population bit.
1166/// 2) \p CntPhi is set to the corresponding phi node.
1167/// 3) \p Var is set to the value whose population bits are being counted.
1168///
1169/// The core idiom we are trying to detect is:
1170/// \code
1171/// if (x0 != 0)
1172/// goto loop-exit // the precondition of the loop
1173/// cnt0 = init-val;
1174/// do {
1175/// x1 = phi (x0, x2);
1176/// cnt1 = phi(cnt0, cnt2);
1177///
1178/// cnt2 = cnt1 + 1;
1179/// ...
1180/// x2 = x1 & (x1 - 1);
1181/// ...
1182/// } while(x != 0);
1183///
1184/// loop-exit:
1185/// \endcode
1186static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1187 Instruction *&CntInst, PHINode *&CntPhi,
1188 Value *&Var) {
1189 // step 1: Check to see if the look-back branch match this pattern:
1190 // "if (a!=0) goto loop-entry".
1191 BasicBlock *LoopEntry;
1192 Instruction *DefX2, *CountInst;
1193 Value *VarX1, *VarX0;
1194 PHINode *PhiX, *CountPhi;
1195
1196 DefX2 = CountInst = nullptr;
1197 VarX1 = VarX0 = nullptr;
1198 PhiX = CountPhi = nullptr;
1199 LoopEntry = *(CurLoop->block_begin());
1200
1201 // step 1: Check if the loop-back branch is in desirable form.
1202 {
1203 if (Value *T = matchCondition(
1204 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1205 DefX2 = dyn_cast<Instruction>(T);
1206 else
1207 return false;
1208 }
1209
1210 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1211 {
1212 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1213 return false;
1214
1215 BinaryOperator *SubOneOp;
1216
1217 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1218 VarX1 = DefX2->getOperand(1);
1219 else {
1220 VarX1 = DefX2->getOperand(0);
1221 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1222 }
Craig Topper856fd682018-05-03 05:48:49 +00001223 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001224 return false;
1225
Craig Topper8ef2abd2018-05-03 05:00:18 +00001226 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
Chandler Carruth8219a502015-08-13 00:44:29 +00001227 if (!Dec ||
Craig Topper8ef2abd2018-05-03 05:00:18 +00001228 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1229 (SubOneOp->getOpcode() == Instruction::Add &&
Craig Topper79ab6432017-07-06 18:39:47 +00001230 Dec->isMinusOne()))) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001231 return false;
1232 }
1233 }
1234
1235 // step 3: Check the recurrence of variable X
Davide Italiano4bc91192017-05-23 22:32:56 +00001236 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1237 if (!PhiX)
1238 return false;
Chandler Carruth8219a502015-08-13 00:44:29 +00001239
1240 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1241 {
1242 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001243 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +00001244 IterE = LoopEntry->end();
1245 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001246 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +00001247 if (Inst->getOpcode() != Instruction::Add)
1248 continue;
1249
1250 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1251 if (!Inc || !Inc->isOne())
1252 continue;
1253
Davide Italiano7bf95b92017-05-23 23:51:54 +00001254 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1255 if (!Phi)
Chandler Carruth8219a502015-08-13 00:44:29 +00001256 continue;
1257
1258 // Check if the result of the instruction is live of the loop.
1259 bool LiveOutLoop = false;
1260 for (User *U : Inst->users()) {
1261 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1262 LiveOutLoop = true;
1263 break;
1264 }
1265 }
1266
1267 if (LiveOutLoop) {
1268 CountInst = Inst;
1269 CountPhi = Phi;
1270 break;
1271 }
1272 }
1273
1274 if (!CountInst)
1275 return false;
1276 }
1277
1278 // step 5: check if the precondition is in this form:
1279 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1280 {
1281 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1282 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1283 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1284 return false;
1285
1286 CntInst = CountInst;
1287 CntPhi = CountPhi;
1288 Var = T;
1289 }
1290
1291 return true;
1292}
1293
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001294/// Return true if the idiom is detected in the loop.
1295///
1296/// Additionally:
1297/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1298/// or nullptr if there is no such.
1299/// 2) \p CntPhi is set to the corresponding phi node
1300/// or nullptr if there is no such.
1301/// 3) \p Var is set to the value whose CTLZ could be used.
1302/// 4) \p DefX is set to the instruction calculating Loop exit condition.
1303///
1304/// The core idiom we are trying to detect is:
1305/// \code
1306/// if (x0 == 0)
1307/// goto loop-exit // the precondition of the loop
1308/// cnt0 = init-val;
1309/// do {
1310/// x = phi (x0, x.next); //PhiX
1311/// cnt = phi(cnt0, cnt.next);
1312///
1313/// cnt.next = cnt + 1;
1314/// ...
1315/// x.next = x >> 1; // DefX
1316/// ...
1317/// } while(x.next != 0);
1318///
1319/// loop-exit:
1320/// \endcode
Craig Topperc9a60002018-12-26 21:59:48 +00001321static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
1322 Intrinsic::ID &IntrinID, Value *&InitX,
1323 Instruction *&CntInst, PHINode *&CntPhi,
1324 Instruction *&DefX) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001325 BasicBlock *LoopEntry;
1326 Value *VarX = nullptr;
1327
1328 DefX = nullptr;
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001329 CntInst = nullptr;
1330 CntPhi = nullptr;
1331 LoopEntry = *(CurLoop->block_begin());
1332
1333 // step 1: Check if the loop-back branch is in desirable form.
1334 if (Value *T = matchCondition(
1335 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1336 DefX = dyn_cast<Instruction>(T);
1337 else
1338 return false;
1339
Craig Topperc9a60002018-12-26 21:59:48 +00001340 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
1341 if (!DefX || !DefX->isShift())
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001342 return false;
Craig Topperc9a60002018-12-26 21:59:48 +00001343 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
1344 Intrinsic::ctlz;
Evgeny Stupachenkod699de22017-11-03 18:50:03 +00001345 ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));
1346 if (!Shft || !Shft->isOne())
1347 return false;
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001348 VarX = DefX->getOperand(0);
1349
1350 // step 3: Check the recurrence of variable X
Craig Topperc9a60002018-12-26 21:59:48 +00001351 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
Davide Italiano4bc91192017-05-23 22:32:56 +00001352 if (!PhiX)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001353 return false;
1354
Craig Topperc9a60002018-12-26 21:59:48 +00001355 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
1356
1357 // Make sure the initial value can't be negative otherwise the ashr in the
1358 // loop might never reach zero which would make the loop infinite.
1359 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
1360 return false;
1361
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001362 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1363 // TODO: We can skip the step. If loop trip count is known (CTLZ),
1364 // then all uses of "cnt.next" could be optimized to the trip count
1365 // plus "cnt0". Currently it is not optimized.
1366 // This step could be used to detect POPCNT instruction:
1367 // cnt.next = cnt + (x.next & 1)
1368 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1369 IterE = LoopEntry->end();
1370 Iter != IterE; Iter++) {
1371 Instruction *Inst = &*Iter;
1372 if (Inst->getOpcode() != Instruction::Add)
1373 continue;
1374
1375 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1376 if (!Inc || !Inc->isOne())
1377 continue;
1378
Davide Italiano7bf95b92017-05-23 23:51:54 +00001379 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1380 if (!Phi)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001381 continue;
1382
1383 CntInst = Inst;
1384 CntPhi = Phi;
1385 break;
1386 }
1387 if (!CntInst)
1388 return false;
1389
1390 return true;
1391}
1392
Craig Topperc9a60002018-12-26 21:59:48 +00001393/// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
1394/// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
1395/// trip count returns true; otherwise, returns false.
1396bool LoopIdiomRecognize::recognizeAndInsertFFS() {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001397 // Give up if the loop has multiple blocks or multiple backedges.
1398 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1399 return false;
1400
Craig Topperc9a60002018-12-26 21:59:48 +00001401 Intrinsic::ID IntrinID;
1402 Value *InitX;
1403 Instruction *DefX = nullptr;
1404 PHINode *CntPhi = nullptr;
1405 Instruction *CntInst = nullptr;
1406 // Help decide if transformation is profitable. For ShiftUntilZero idiom,
1407 // this is always 6.
1408 size_t IdiomCanonicalSize = 6;
1409
1410 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX,
1411 CntInst, CntPhi, DefX))
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001412 return false;
1413
1414 bool IsCntPhiUsedOutsideLoop = false;
1415 for (User *U : CntPhi->users())
Craig Topper83042312018-05-04 01:04:24 +00001416 if (!CurLoop->contains(cast<Instruction>(U))) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001417 IsCntPhiUsedOutsideLoop = true;
1418 break;
1419 }
1420 bool IsCntInstUsedOutsideLoop = false;
1421 for (User *U : CntInst->users())
Craig Topper83042312018-05-04 01:04:24 +00001422 if (!CurLoop->contains(cast<Instruction>(U))) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001423 IsCntInstUsedOutsideLoop = true;
1424 break;
1425 }
1426 // If both CntInst and CntPhi are used outside the loop the profitability
1427 // is questionable.
1428 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1429 return false;
1430
1431 // For some CPUs result of CTLZ(X) intrinsic is undefined
1432 // when X is 0. If we can not guarantee X != 0, we need to check this
1433 // when expand.
1434 bool ZeroCheck = false;
1435 // It is safe to assume Preheader exist as it was checked in
1436 // parent function RunOnLoop.
1437 BasicBlock *PH = CurLoop->getLoopPreheader();
Craig Topper9a6c0bd2018-05-31 22:16:55 +00001438
Craig Toppered6acde2018-07-11 22:35:28 +00001439 // If we are using the count instruction outside the loop, make sure we
1440 // have a zero check as a precondition. Without the check the loop would run
1441 // one iteration for before any check of the input value. This means 0 and 1
1442 // would have identical behavior in the original loop and thus
1443 if (!IsCntPhiUsedOutsideLoop) {
1444 auto *PreCondBB = PH->getSinglePredecessor();
1445 if (!PreCondBB)
1446 return false;
1447 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1448 if (!PreCondBI)
1449 return false;
1450 if (matchCondition(PreCondBI, PH) != InitX)
1451 return false;
1452 ZeroCheck = true;
1453 }
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001454
Craig Topperc9a60002018-12-26 21:59:48 +00001455 // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
1456 // profitable if we delete the loop.
1457
1458 // the loop has only 6 instructions:
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001459 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1460 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1461 // %shr = ashr %n.addr.0, 1
1462 // %tobool = icmp eq %shr, 0
1463 // %inc = add nsw %i.0, 1
1464 // br i1 %tobool
1465
Craig Toppercafae622018-05-04 01:04:26 +00001466 const Value *Args[] =
Craig Topperded8ee02018-05-04 17:39:08 +00001467 {InitX, ZeroCheck ? ConstantInt::getTrue(InitX->getContext())
1468 : ConstantInt::getFalse(InitX->getContext())};
Davide Italiano73929c42019-02-03 20:33:20 +00001469
1470 // @llvm.dbg doesn't count as they have no semantic effect.
1471 auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug();
1472 uint32_t HeaderSize =
1473 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());
1474
1475 if (HeaderSize != IdiomCanonicalSize &&
Craig Topperc9a60002018-12-26 21:59:48 +00001476 TTI->getIntrinsicCost(IntrinID, InitX->getType(), Args) >
Davide Italiano73929c42019-02-03 20:33:20 +00001477 TargetTransformInfo::TCC_Basic)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001478 return false;
1479
Craig Topperc9a60002018-12-26 21:59:48 +00001480 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
Craig Topper28352782018-07-08 01:45:47 +00001481 DefX->getDebugLoc(), ZeroCheck,
1482 IsCntPhiUsedOutsideLoop);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001483 return true;
1484}
1485
Chandler Carruth8219a502015-08-13 00:44:29 +00001486/// Recognizes a population count idiom in a non-countable loop.
1487///
1488/// If detected, transforms the relevant code to issue the popcount intrinsic
1489/// function call, and returns true; otherwise, returns false.
1490bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +00001491 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1492 return false;
1493
1494 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001495 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +00001496 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1497 // in a compact loop.
1498
Renato Golin655348f2015-08-13 11:25:38 +00001499 // Give up if the loop has multiple blocks or multiple backedges.
1500 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001501 return false;
1502
Renato Golin655348f2015-08-13 11:25:38 +00001503 BasicBlock *LoopBody = *(CurLoop->block_begin());
1504 if (LoopBody->size() >= 20) {
1505 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +00001506 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001507 }
Chandler Carruth8219a502015-08-13 00:44:29 +00001508
1509 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +00001510 BasicBlock *PH = CurLoop->getLoopPreheader();
Davide Italianoc0169fa2016-10-07 18:39:43 +00001511 if (!PH || &PH->front() != PH->getTerminator())
Renato Golin655348f2015-08-13 11:25:38 +00001512 return false;
1513 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001514 if (!EntryBI || EntryBI->isConditional())
1515 return false;
1516
Hiroshi Inouef2096492018-06-14 05:41:49 +00001517 // It should have a precondition block where the generated popcount intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001518 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +00001519 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +00001520 if (!PreCondBB)
1521 return false;
1522 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1523 if (!PreCondBI || PreCondBI->isUnconditional())
1524 return false;
1525
1526 Instruction *CntInst;
1527 PHINode *CntPhi;
1528 Value *Val;
1529 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1530 return false;
1531
1532 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1533 return true;
1534}
1535
1536static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001537 const DebugLoc &DL) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001538 Value *Ops[] = {Val};
1539 Type *Tys[] = {Val->getType()};
1540
1541 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
James Y Knight7976eb52019-02-01 20:43:25 +00001542 Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
Chandler Carruth8219a502015-08-13 00:44:29 +00001543 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1544 CI->setDebugLoc(DL);
1545
1546 return CI;
1547}
1548
Craig Topperc9a60002018-12-26 21:59:48 +00001549static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1550 const DebugLoc &DL, bool ZeroCheck,
1551 Intrinsic::ID IID) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001552 Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()};
1553 Type *Tys[] = {Val->getType()};
1554
1555 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
James Y Knight7976eb52019-02-01 20:43:25 +00001556 Function *Func = Intrinsic::getDeclaration(M, IID, Tys);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001557 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1558 CI->setDebugLoc(DL);
1559
1560 return CI;
1561}
1562
Craig Topperc9a60002018-12-26 21:59:48 +00001563/// Transform the following loop (Using CTLZ, CTTZ is similar):
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001564/// loop:
1565/// CntPhi = PHI [Cnt0, CntInst]
1566/// PhiX = PHI [InitX, DefX]
1567/// CntInst = CntPhi + 1
1568/// DefX = PhiX >> 1
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001569/// LOOP_BODY
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001570/// Br: loop if (DefX != 0)
1571/// Use(CntPhi) or Use(CntInst)
1572///
1573/// Into:
1574/// If CntPhi used outside the loop:
1575/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1576/// Count = CountPrev + 1
1577/// else
1578/// Count = BitWidth(InitX) - CTLZ(InitX)
1579/// loop:
1580/// CntPhi = PHI [Cnt0, CntInst]
1581/// PhiX = PHI [InitX, DefX]
1582/// PhiCount = PHI [Count, Dec]
1583/// CntInst = CntPhi + 1
1584/// DefX = PhiX >> 1
1585/// Dec = PhiCount - 1
1586/// LOOP_BODY
1587/// Br: loop if (Dec != 0)
1588/// Use(CountPrev + Cnt0) // Use(CntPhi)
1589/// or
1590/// Use(Count + Cnt0) // Use(CntInst)
1591///
1592/// If LOOP_BODY is empty the loop will be deleted.
1593/// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1594void LoopIdiomRecognize::transformLoopToCountable(
Craig Topperc9a60002018-12-26 21:59:48 +00001595 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
1596 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
1597 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
Craig Topper9510f702018-05-04 01:04:28 +00001598 BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001599
Craig Topperc9a60002018-12-26 21:59:48 +00001600 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
1601 IRBuilder<> Builder(PreheaderBr);
1602 Builder.SetCurrentDebugLocation(DL);
1603 Value *FFS, *Count, *CountPrev, *NewCount, *InitXNext;
1604
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001605 // Count = BitWidth - CTLZ(InitX);
1606 // If there are uses of CntPhi create:
1607 // CountPrev = BitWidth - CTLZ(InitX >> 1);
Craig Topper28352782018-07-08 01:45:47 +00001608 if (IsCntPhiUsedOutsideLoop) {
1609 if (DefX->getOpcode() == Instruction::AShr)
1610 InitXNext =
1611 Builder.CreateAShr(InitX, ConstantInt::get(InitX->getType(), 1));
1612 else if (DefX->getOpcode() == Instruction::LShr)
1613 InitXNext =
1614 Builder.CreateLShr(InitX, ConstantInt::get(InitX->getType(), 1));
Craig Topperc9a60002018-12-26 21:59:48 +00001615 else if (DefX->getOpcode() == Instruction::Shl) // cttz
1616 InitXNext =
1617 Builder.CreateShl(InitX, ConstantInt::get(InitX->getType(), 1));
Craig Topper28352782018-07-08 01:45:47 +00001618 else
Fangrui Songf78650a2018-07-30 19:41:25 +00001619 llvm_unreachable("Unexpected opcode!");
Craig Topper28352782018-07-08 01:45:47 +00001620 } else
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001621 InitXNext = InitX;
Craig Topperc9a60002018-12-26 21:59:48 +00001622 FFS = createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001623 Count = Builder.CreateSub(
Craig Topperc9a60002018-12-26 21:59:48 +00001624 ConstantInt::get(FFS->getType(),
1625 FFS->getType()->getIntegerBitWidth()),
1626 FFS);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001627 if (IsCntPhiUsedOutsideLoop) {
1628 CountPrev = Count;
1629 Count = Builder.CreateAdd(
1630 CountPrev,
1631 ConstantInt::get(CountPrev->getType(), 1));
1632 }
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001633
Craig Topperc9a60002018-12-26 21:59:48 +00001634 NewCount = Builder.CreateZExtOrTrunc(
1635 IsCntPhiUsedOutsideLoop ? CountPrev : Count,
1636 cast<IntegerType>(CntInst->getType()));
1637
1638 // If the counter's initial value is not zero, insert Add Inst.
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001639 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1640 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1641 if (!InitConst || !InitConst->isZero())
1642 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1643
1644 // Step 2: Insert new IV and loop condition:
1645 // loop:
1646 // ...
1647 // PhiCount = PHI [Count, Dec]
1648 // ...
1649 // Dec = PhiCount - 1
1650 // ...
1651 // Br: loop if (Dec != 0)
1652 BasicBlock *Body = *(CurLoop->block_begin());
Craig Topper9510f702018-05-04 01:04:28 +00001653 auto *LbBr = cast<BranchInst>(Body->getTerminator());
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001654 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1655 Type *Ty = Count->getType();
1656
1657 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1658
1659 Builder.SetInsertPoint(LbCond);
1660 Instruction *TcDec = cast<Instruction>(
1661 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1662 "tcdec", false, true));
1663
1664 TcPhi->addIncoming(Count, Preheader);
1665 TcPhi->addIncoming(TcDec, Body);
1666
1667 CmpInst::Predicate Pred =
1668 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
1669 LbCond->setPredicate(Pred);
1670 LbCond->setOperand(0, TcDec);
1671 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1672
1673 // Step 3: All the references to the original counter outside
Craig Topperc9a60002018-12-26 21:59:48 +00001674 // the loop are replaced with the NewCount
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001675 if (IsCntPhiUsedOutsideLoop)
1676 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
1677 else
1678 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1679
1680 // step 4: Forget the "non-computable" trip-count SCEV associated with the
1681 // loop. The loop would otherwise not be deleted even if it becomes empty.
1682 SE->forgetLoop(CurLoop);
1683}
1684
Chandler Carruth8219a502015-08-13 00:44:29 +00001685void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1686 Instruction *CntInst,
1687 PHINode *CntPhi, Value *Var) {
1688 BasicBlock *PreHead = CurLoop->getLoopPreheader();
Craig Topper9510f702018-05-04 01:04:28 +00001689 auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());
Craig Topper27847862018-06-25 20:45:45 +00001690 const DebugLoc &DL = CntInst->getDebugLoc();
Chandler Carruth8219a502015-08-13 00:44:29 +00001691
1692 // Assuming before transformation, the loop is following:
1693 // if (x) // the precondition
1694 // do { cnt++; x &= x - 1; } while(x);
1695
1696 // Step 1: Insert the ctpop instruction at the end of the precondition block
1697 IRBuilder<> Builder(PreCondBr);
1698 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1699 {
1700 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1701 NewCount = PopCntZext =
1702 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1703
1704 if (NewCount != PopCnt)
1705 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1706
1707 // TripCnt is exactly the number of iterations the loop has
1708 TripCnt = NewCount;
1709
1710 // If the population counter's initial value is not zero, insert Add Inst.
1711 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1712 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1713 if (!InitConst || !InitConst->isZero()) {
1714 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1715 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1716 }
1717 }
1718
Nick Lewycky2c852542015-08-19 06:22:33 +00001719 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +00001720 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001721 // function would be partial dead code, and downstream passes will drag
1722 // it back from the precondition block to the preheader.
1723 {
1724 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1725
1726 Value *Opnd0 = PopCntZext;
1727 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1728 if (PreCond->getOperand(0) != Var)
1729 std::swap(Opnd0, Opnd1);
1730
1731 ICmpInst *NewPreCond = cast<ICmpInst>(
1732 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1733 PreCondBr->setCondition(NewPreCond);
1734
1735 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1736 }
1737
1738 // Step 3: Note that the population count is exactly the trip count of the
Hiroshi Inouec8e92452018-01-29 05:17:03 +00001739 // loop in question, which enable us to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +00001740 // loop into a countable one. The benefit is twofold:
1741 //
Nick Lewycky2c852542015-08-19 06:22:33 +00001742 // - If the loop only counts population, the entire loop becomes dead after
1743 // the transformation. It is a lot easier to prove a countable loop dead
1744 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +00001745 // isn't dead even if it computes nothing useful. In general, DCE needs
1746 // to prove a noncountable loop finite before safely delete it.)
1747 //
1748 // - If the loop also performs something else, it remains alive.
1749 // Since it is transformed to countable form, it can be aggressively
1750 // optimized by some optimizations which are in general not applicable
1751 // to a noncountable loop.
1752 //
1753 // After this step, this loop (conceptually) would look like following:
1754 // newcnt = __builtin_ctpop(x);
1755 // t = newcnt;
1756 // if (x)
1757 // do { cnt++; x &= x-1; t--) } while (t > 0);
1758 BasicBlock *Body = *(CurLoop->block_begin());
1759 {
Craig Topper9510f702018-05-04 01:04:28 +00001760 auto *LbBr = cast<BranchInst>(Body->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001761 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1762 Type *Ty = TripCnt->getType();
1763
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001764 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +00001765
1766 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +00001767 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +00001768 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1769 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +00001770
1771 TcPhi->addIncoming(TripCnt, PreHead);
1772 TcPhi->addIncoming(TcDec, Body);
1773
1774 CmpInst::Predicate Pred =
1775 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1776 LbCond->setPredicate(Pred);
1777 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001778 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001779 }
1780
1781 // Step 4: All the references to the original population counter outside
1782 // the loop are replaced with the NewCount -- the value returned from
1783 // __builtin_ctpop().
1784 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1785
1786 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1787 // loop. The loop would otherwise not be deleted even if it becomes empty.
1788 SE->forgetLoop(CurLoop);
1789}