blob: 799f40d8724ec9b0cdf363f640d3b44be4a1ff09 [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
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000039#include "llvm/ADT/APInt.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/DenseMap.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000042#include "llvm/ADT/MapVector.h"
43#include "llvm/ADT/SetVector.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000044#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/SmallVector.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000047#include "llvm/ADT/StringRef.h"
Chris Lattnercb18bfa2010-12-27 18:39:08 +000048#include "llvm/Analysis/AliasAnalysis.h"
Haicheng Wuf1c00a22016-01-26 02:27:47 +000049#include "llvm/Analysis/LoopAccessAnalysis.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000050#include "llvm/Analysis/LoopInfo.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +000051#include "llvm/Analysis/LoopPass.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000052#include "llvm/Analysis/MemoryLocation.h"
53#include "llvm/Analysis/ScalarEvolution.h"
Chad Rosiera15b4b62015-11-23 21:09:13 +000054#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000055#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000056#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000057#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000058#include "llvm/Transforms/Utils/Local.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"
Xin Tong99c4e2f2018-04-08 13:19:53 +000089#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Ahmed Bougachaace97c12016-04-27 19:04:50 +000090#include "llvm/Transforms/Utils/BuildLibCalls.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 =
287 L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs;
288
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
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000315 LLVM_DEBUG(dbgs() << "loop-idiom Scanning: F["
316 << CurLoop->getHeader()->getParent()->getName()
317 << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
Shuxin Yang95de7c32012-12-09 03:12:46 +0000318
319 bool MadeChange = false;
Haicheng Wua95cd1262016-07-06 21:05:40 +0000320
321 // The following transforms hoist stores/memsets into the loop pre-header.
322 // Give up if the loop has instructions may throw.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000323 SimpleLoopSafetyInfo SafetyInfo;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000324 SafetyInfo.computeLoopSafetyInfo(CurLoop);
325 if (SafetyInfo.anyBlockMayThrow())
Haicheng Wua95cd1262016-07-06 21:05:40 +0000326 return MadeChange;
327
Shuxin Yang95de7c32012-12-09 03:12:46 +0000328 // Scan all the blocks in the loop that are not in subloops.
Davide Italiano95a77e82015-05-14 21:52:12 +0000329 for (auto *BB : CurLoop->getBlocks()) {
Shuxin Yang95de7c32012-12-09 03:12:46 +0000330 // Ignore blocks in subloops.
Chandler Carruth18c26692015-08-13 09:27:01 +0000331 if (LI->getLoopFor(BB) != CurLoop)
Shuxin Yang95de7c32012-12-09 03:12:46 +0000332 continue;
333
Davide Italiano80625af2015-05-13 19:51:21 +0000334 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
Shuxin Yang95de7c32012-12-09 03:12:46 +0000335 }
336 return MadeChange;
337}
338
Chad Rosier4acff962016-02-12 19:05:27 +0000339static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
Chad Rosiera548fe52015-11-12 19:09:16 +0000340 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
Chad Rosier4acff962016-02-12 19:05:27 +0000341 return ConstStride->getAPInt();
Chad Rosiera548fe52015-11-12 19:09:16 +0000342}
343
Chad Rosier94274fb2015-12-21 14:49:32 +0000344/// getMemSetPatternValue - If a strided store of the specified value is safe to
345/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
346/// be passed in. Otherwise, return null.
347///
348/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
349/// just replicate their input array and then pass on to memset_pattern16.
350static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
JF Bastien73d8e4e2018-09-21 05:17:42 +0000351 // FIXME: This could check for UndefValue because it can be merged into any
352 // other valid pattern.
353
Chad Rosier94274fb2015-12-21 14:49:32 +0000354 // If the value isn't a constant, we can't promote it to being in a constant
355 // array. We could theoretically do a store to an alloca or something, but
356 // that doesn't seem worthwhile.
357 Constant *C = dyn_cast<Constant>(V);
358 if (!C)
359 return nullptr;
360
361 // Only handle simple values that are a power of two bytes in size.
362 uint64_t Size = DL->getTypeSizeInBits(V->getType());
363 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
364 return nullptr;
365
366 // Don't care enough about darwin/ppc to implement this.
367 if (DL->isBigEndian())
368 return nullptr;
369
370 // Convert to size in bytes.
371 Size /= 8;
372
373 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
374 // if the top and bottom are the same (e.g. for vectors and large integers).
375 if (Size > 16)
376 return nullptr;
377
378 // If the constant is exactly 16 bytes, just use it.
379 if (Size == 16)
380 return C;
381
382 // Otherwise, we'll use an array of the constants.
383 unsigned ArraySize = 16 / Size;
384 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
385 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
386}
387
Anna Thomasae3f752f2017-05-19 18:00:30 +0000388LoopIdiomRecognize::LegalStoreKind
389LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
Chad Rosier869962f2015-12-01 14:26:35 +0000390 // Don't touch volatile stores.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000391 if (SI->isVolatile())
392 return LegalStoreKind::None;
393 // We only want simple or unordered-atomic stores.
394 if (!SI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000395 return LegalStoreKind::None;
Chad Rosier869962f2015-12-01 14:26:35 +0000396
Sanjoy Das206f65c2017-04-24 20:12:10 +0000397 // Don't convert stores of non-integral pointer types to memsets (which stores
398 // integers).
399 if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType()))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000400 return LegalStoreKind::None;
Sanjoy Das206f65c2017-04-24 20:12:10 +0000401
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000402 // Avoid merging nontemporal stores.
403 if (SI->getMetadata(LLVMContext::MD_nontemporal))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000404 return LegalStoreKind::None;
Haicheng Wu57e1a3e2016-02-17 21:00:06 +0000405
Chad Rosiera548fe52015-11-12 19:09:16 +0000406 Value *StoredVal = SI->getValueOperand();
407 Value *StorePtr = SI->getPointerOperand();
408
409 // Reject stores that are so large that they overflow an unsigned.
410 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
411 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000412 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000413
414 // See if the pointer expression is an AddRec like {base,+,1} on the current
415 // loop, which indicates a strided store. If we have something else, it's a
416 // random store we can't handle.
417 const SCEVAddRecExpr *StoreEv =
418 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
419 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000420 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000421
422 // Check to see if we have a constant stride.
423 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000424 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000425
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000426 // See if the store can be turned into a memset.
427
428 // If the stored value is a byte-wise value (like i32 -1), then it may be
429 // turned into a memset of i8 -1, assuming that all the consecutive bytes
430 // are stored. A store of i32 0x01020304 can never be turned into a memset,
431 // but it can be turned into memset_pattern if the target supports it.
432 Value *SplatValue = isBytewiseValue(StoredVal);
433 Constant *PatternValue = nullptr;
434
Anna Thomasb2a212c2017-06-06 16:45:25 +0000435 // Note: memset and memset_pattern on unordered-atomic is yet not supported
436 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
437
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000438 // If we're allowed to form a memset, and the stored value would be
439 // acceptable for memset, use it.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000440 if (!UnorderedAtomic && HasMemset && SplatValue &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000441 // Verify that the stored value is loop invariant. If not, we can't
442 // promote the memset.
443 CurLoop->isLoopInvariant(SplatValue)) {
444 // It looks like we can use SplatValue.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000445 return LegalStoreKind::Memset;
Anna Thomasb2a212c2017-06-06 16:45:25 +0000446 } else if (!UnorderedAtomic && HasMemsetPattern &&
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000447 // Don't create memset_pattern16s with address spaces.
448 StorePtr->getType()->getPointerAddressSpace() == 0 &&
449 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
450 // It looks like we can use PatternValue!
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000451 return LegalStoreKind::MemsetPattern;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000452 }
453
454 // Otherwise, see if the store can be turned into a memcpy.
455 if (HasMemcpy) {
456 // Check to see if the stride matches the size of the store. If so, then we
457 // know that every byte is touched in the loop.
Chad Rosier4acff962016-02-12 19:05:27 +0000458 APInt Stride = getStoreStride(StoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000459 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000460 if (StoreSize != Stride && StoreSize != -Stride)
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000461 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000462
463 // The store must be feeding a non-volatile load.
464 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +0000465
466 // Only allow non-volatile loads
467 if (!LI || LI->isVolatile())
468 return LegalStoreKind::None;
469 // Only allow simple or unordered-atomic loads
470 if (!LI->isUnordered())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000471 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000472
473 // See if the pointer expression is an AddRec like {base,+,1} on the current
474 // loop, which indicates a strided load. If we have something else, it's a
475 // random load we can't handle.
476 const SCEVAddRecExpr *LoadEv =
477 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
478 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000479 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000480
481 // The store and load must share the same stride.
482 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000483 return LegalStoreKind::None;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000484
485 // Success. This store can be converted into a memcpy.
Anna Thomasb2a212c2017-06-06 16:45:25 +0000486 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
487 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
488 : LegalStoreKind::Memcpy;
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000489 }
490 // This store can't be transformed into a memset/memcpy.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000491 return LegalStoreKind::None;
Chad Rosiera548fe52015-11-12 19:09:16 +0000492}
493
Chad Rosiercc9030b2015-11-11 23:00:59 +0000494void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000495 StoreRefsForMemset.clear();
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000496 StoreRefsForMemsetPattern.clear();
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000497 StoreRefsForMemcpy.clear();
Chad Rosiercc9030b2015-11-11 23:00:59 +0000498 for (Instruction &I : *BB) {
499 StoreInst *SI = dyn_cast<StoreInst>(&I);
500 if (!SI)
501 continue;
502
Chad Rosiera548fe52015-11-12 19:09:16 +0000503 // Make sure this is a strided store with a constant stride.
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000504 switch (isLegalStore(SI)) {
505 case LegalStoreKind::None:
506 // Nothing to do
507 break;
508 case LegalStoreKind::Memset: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000509 // Find the base pointer.
510 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
511 StoreRefsForMemset[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000512 } break;
513 case LegalStoreKind::MemsetPattern: {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000514 // Find the base pointer.
515 Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
516 StoreRefsForMemsetPattern[Ptr].push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000517 } break;
518 case LegalStoreKind::Memcpy:
Anna Thomasb2a212c2017-06-06 16:45:25 +0000519 case LegalStoreKind::UnorderedAtomicMemcpy:
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000520 StoreRefsForMemcpy.push_back(SI);
Anna Thomas5ecb8f72017-05-19 17:05:36 +0000521 break;
522 default:
523 assert(false && "unhandled return value");
524 break;
525 }
Chad Rosiercc9030b2015-11-11 23:00:59 +0000526 }
527}
528
Chris Lattner8455b6e2011-01-02 19:01:03 +0000529/// runOnLoopBlock - Process the specified block, which lives in a counted loop
530/// with the specified backedge count. This block is known to be in the current
531/// loop and not in any subloops.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000532bool LoopIdiomRecognize::runOnLoopBlock(
533 BasicBlock *BB, const SCEV *BECount,
534 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner8455b6e2011-01-02 19:01:03 +0000535 // We can only promote stores in this block if they are unconditionally
536 // executed in the loop. For a block to be unconditionally executed, it has
537 // to dominate all the exit blocks of the loop. Verify this now.
538 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
539 if (!DT->dominates(BB, ExitBlocks[i]))
540 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000541
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000542 bool MadeChange = false;
Chad Rosiercc9030b2015-11-11 23:00:59 +0000543 // Look for store instructions, which may be optimized to memset/memcpy.
544 collectStores(BB);
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000545
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000546 // Look for a single store or sets of stores with a common base, which can be
547 // optimized into a memset (memset_pattern). The latter most commonly happens
548 // with structs and handunrolled loops.
549 for (auto &SL : StoreRefsForMemset)
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000550 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000551
552 for (auto &SL : StoreRefsForMemsetPattern)
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000553 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
Chad Rosiercc9030b2015-11-11 23:00:59 +0000554
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000555 // Optimize the store into a memcpy, if it feeds an similarly strided load.
556 for (auto &SI : StoreRefsForMemcpy)
557 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
558
Chandler Carruthbad690e2015-08-12 23:06:37 +0000559 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000560 Instruction *Inst = &*I++;
Chris Lattner86438102011-01-04 07:46:33 +0000561 // Look for memset instructions, which may be optimized to a larger memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000562 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000563 WeakTrackingVH InstPtr(&*I);
Chandler Carruthbad690e2015-08-12 23:06:37 +0000564 if (!processLoopMemSet(MSI, BECount))
565 continue;
Chris Lattner86438102011-01-04 07:46:33 +0000566 MadeChange = true;
Andrew Trick328b2232011-03-14 16:48:10 +0000567
Chris Lattner86438102011-01-04 07:46:33 +0000568 // If processing the memset invalidated our iterator, start over from the
569 // top of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000570 if (!InstPtr)
Chris Lattner86438102011-01-04 07:46:33 +0000571 I = BB->begin();
572 continue;
573 }
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000574 }
Andrew Trick328b2232011-03-14 16:48:10 +0000575
Chris Lattner7c5f9c32010-12-26 20:45:45 +0000576 return MadeChange;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000577}
578
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000579/// See if this store(s) can be promoted to a memset.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000580bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000581 const SCEV *BECount, ForMemset For) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000582 // Try to find consecutive stores that can be transformed into memsets.
583 SetVector<StoreInst *> Heads, Tails;
584 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
Chris Lattner86438102011-01-04 07:46:33 +0000585
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000586 // Do a quadratic search on all of the given stores and find
587 // all of the pairs of stores that follow each other.
588 SmallVector<unsigned, 16> IndexQueue;
589 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
590 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
Andrew Trick328b2232011-03-14 16:48:10 +0000591
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000592 Value *FirstStoredVal = SL[i]->getValueOperand();
593 Value *FirstStorePtr = SL[i]->getPointerOperand();
594 const SCEVAddRecExpr *FirstStoreEv =
595 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000596 APInt FirstStride = getStoreStride(FirstStoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000597 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
Chad Rosier79676142015-10-28 14:38:49 +0000598
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000599 // See if we can optimize just this store in isolation.
Chad Rosier4acff962016-02-12 19:05:27 +0000600 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000601 Heads.insert(SL[i]);
602 continue;
603 }
Chris Lattner0f4a6402011-02-19 19:31:39 +0000604
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000605 Value *FirstSplatValue = nullptr;
606 Constant *FirstPatternValue = nullptr;
607
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000608 if (For == ForMemset::Yes)
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000609 FirstSplatValue = isBytewiseValue(FirstStoredVal);
610 else
611 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
612
613 assert((FirstSplatValue || FirstPatternValue) &&
614 "Expected either splat value or pattern value.");
615
616 IndexQueue.clear();
617 // If a store has multiple consecutive store candidates, search Stores
618 // array according to the sequence: from i+1 to e, then from i-1 to 0.
619 // This is because usually pairing with immediate succeeding or preceding
620 // candidate create the best chance to find memset opportunity.
621 unsigned j = 0;
622 for (j = i + 1; j < e; ++j)
623 IndexQueue.push_back(j);
624 for (j = i; j > 0; --j)
625 IndexQueue.push_back(j - 1);
626
627 for (auto &k : IndexQueue) {
628 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
629 Value *SecondStorePtr = SL[k]->getPointerOperand();
630 const SCEVAddRecExpr *SecondStoreEv =
631 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000632 APInt SecondStride = getStoreStride(SecondStoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000633
634 if (FirstStride != SecondStride)
635 continue;
636
637 Value *SecondStoredVal = SL[k]->getValueOperand();
638 Value *SecondSplatValue = nullptr;
639 Constant *SecondPatternValue = nullptr;
640
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000641 if (For == ForMemset::Yes)
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000642 SecondSplatValue = isBytewiseValue(SecondStoredVal);
643 else
644 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
645
646 assert((SecondSplatValue || SecondPatternValue) &&
647 "Expected either splat value or pattern value.");
648
649 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
JF Bastien7e2dd2d2018-09-07 18:17:59 +0000650 if (For == ForMemset::Yes) {
JF Bastien73d8e4e2018-09-21 05:17:42 +0000651 if (isa<UndefValue>(FirstSplatValue))
652 FirstSplatValue = SecondSplatValue;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000653 if (FirstSplatValue != SecondSplatValue)
654 continue;
655 } else {
JF Bastien73d8e4e2018-09-21 05:17:42 +0000656 if (isa<UndefValue>(FirstPatternValue))
657 FirstPatternValue = SecondPatternValue;
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000658 if (FirstPatternValue != SecondPatternValue)
659 continue;
660 }
661 Tails.insert(SL[k]);
662 Heads.insert(SL[i]);
663 ConsecutiveChain[SL[i]] = SL[k];
664 break;
665 }
666 }
667 }
668
669 // We may run into multiple chains that merge into a single chain. We mark the
670 // stores that we transformed so that we don't visit the same store twice.
671 SmallPtrSet<Value *, 16> TransformedStores;
672 bool Changed = false;
673
674 // For stores that start but don't end a link in the chain:
675 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
676 it != e; ++it) {
677 if (Tails.count(*it))
678 continue;
679
680 // We found a store instr that starts a chain. Now follow the chain and try
681 // to transform it.
682 SmallPtrSet<Instruction *, 8> AdjacentStores;
683 StoreInst *I = *it;
684
685 StoreInst *HeadStore = I;
686 unsigned StoreSize = 0;
687
688 // Collect the chain into a list.
689 while (Tails.count(I) || Heads.count(I)) {
690 if (TransformedStores.count(I))
691 break;
692 AdjacentStores.insert(I);
693
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000694 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000695 // Move to the next value in the chain.
696 I = ConsecutiveChain[I];
697 }
698
699 Value *StoredVal = HeadStore->getValueOperand();
700 Value *StorePtr = HeadStore->getPointerOperand();
701 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000702 APInt Stride = getStoreStride(StoreEv);
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000703
704 // Check to see if the stride matches the size of the stores. If so, then
705 // we know that every byte is touched in the loop.
706 if (StoreSize != Stride && StoreSize != -Stride)
707 continue;
708
709 bool NegStride = StoreSize == -Stride;
710
711 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
712 StoredVal, HeadStore, AdjacentStores, StoreEv,
713 BECount, NegStride)) {
714 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
715 Changed = true;
716 }
717 }
718
719 return Changed;
Chris Lattner81ae3f22010-12-26 19:39:38 +0000720}
721
Chris Lattner86438102011-01-04 07:46:33 +0000722/// processLoopMemSet - See if this memset can be promoted to a large memset.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000723bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
724 const SCEV *BECount) {
Chris Lattner86438102011-01-04 07:46:33 +0000725 // We can only handle non-volatile memsets with a constant size.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000726 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
727 return false;
Chris Lattner86438102011-01-04 07:46:33 +0000728
Chris Lattnere6b261f2011-02-18 22:22:15 +0000729 // If we're not allowed to hack on memset, we fail.
Ahmed Bougacha7f971932016-04-27 19:04:46 +0000730 if (!HasMemset)
Chris Lattnere6b261f2011-02-18 22:22:15 +0000731 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000732
Chris Lattner86438102011-01-04 07:46:33 +0000733 Value *Pointer = MSI->getDest();
Andrew Trick328b2232011-03-14 16:48:10 +0000734
Chris Lattner86438102011-01-04 07:46:33 +0000735 // See if the pointer expression is an AddRec like {base,+,1} on the current
736 // loop, which indicates a strided store. If we have something else, it's a
737 // random store we can't handle.
738 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
Craig Topperf40110f2014-04-25 05:29:35 +0000739 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
Chris Lattner86438102011-01-04 07:46:33 +0000740 return false;
741
742 // Reject memsets that are so large that they overflow an unsigned.
743 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
744 if ((SizeInBytes >> 32) != 0)
745 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000746
Chris Lattner86438102011-01-04 07:46:33 +0000747 // Check to see if the stride matches the size of the memset. If so, then we
748 // know that every byte is touched in the loop.
Chad Rosier81362a82016-02-12 21:03:23 +0000749 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
750 if (!ConstStride)
751 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000752
Chad Rosier81362a82016-02-12 21:03:23 +0000753 APInt Stride = ConstStride->getAPInt();
754 if (SizeInBytes != Stride && SizeInBytes != -Stride)
Chris Lattner86438102011-01-04 07:46:33 +0000755 return false;
Andrew Trick328b2232011-03-14 16:48:10 +0000756
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000757 // Verify that the memset value is loop invariant. If not, we can't promote
758 // the memset.
759 Value *SplatValue = MSI->getValue();
760 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
761 return false;
762
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000763 SmallPtrSet<Instruction *, 1> MSIs;
764 MSIs.insert(MSI);
Chad Rosier81362a82016-02-12 21:03:23 +0000765 bool NegStride = SizeInBytes == -Stride;
Chris Lattner0f4a6402011-02-19 19:31:39 +0000766 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
Daniel Neilsonfb99a492018-02-08 17:33:08 +0000767 MSI->getDestAlignment(), SplatValue, MSI, MSIs,
768 Ev, BECount, NegStride, /*IsLoopMemset=*/true);
Chris Lattner86438102011-01-04 07:46:33 +0000769}
770
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000771/// mayLoopAccessLocation - Return true if the specified loop might access the
772/// specified pointer location, which is a loop-strided access. The 'Access'
773/// argument specifies what the verboten forms of access are (read or write).
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000774static bool
775mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
776 const SCEV *BECount, unsigned StoreSize,
777 AliasAnalysis &AA,
778 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000779 // Get the location that may be stored across the loop. Since the access is
780 // strided positively through memory, we say that the modified location starts
781 // at the pointer and has infinite size.
George Burgess IV7e128752018-12-24 05:55:50 +0000782 LocationSize AccessSize = LocationSize::unknown();
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000783
784 // If the loop iterates a fixed number of times, we can refine the access size
785 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
786 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
George Burgess IV7e128752018-12-24 05:55:50 +0000787 AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) *
788 StoreSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000789
790 // TODO: For this to be really effective, we have to dive into the pointer
791 // operand in the store. Store to &A[i] of 100 will always return may alias
792 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
793 // which will then no-alias a store to &A[100].
Chandler Carruthac80dc72015-06-17 07:18:54 +0000794 MemoryLocation StoreLoc(Ptr, AccessSize);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000795
796 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
797 ++BI)
Benjamin Kramer135f7352016-06-26 12:28:59 +0000798 for (Instruction &I : **BI)
799 if (IgnoredStores.count(&I) == 0 &&
Alina Sbirlea18fea012017-12-06 19:56:37 +0000800 isModOrRefSet(
801 intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access)))
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000802 return true;
803
804 return false;
805}
806
Chad Rosiered0c7d12015-11-13 19:11:07 +0000807// If we have a negative stride, Start refers to the end of the memory location
808// we're trying to memset. Therefore, we need to recompute the base pointer,
809// which is just Start - BECount*Size.
810static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
811 Type *IntPtr, unsigned StoreSize,
812 ScalarEvolution *SE) {
813 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
814 if (StoreSize != 1)
815 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
816 SCEV::FlagNUW);
817 return SE->getMinusSCEV(Start, Index);
818}
819
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000820/// Compute the number of bytes as a SCEV from the backedge taken count.
821///
822/// This also maps the SCEV into the provided type and tries to handle the
823/// computation in a way that will fold cleanly.
824static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
825 unsigned StoreSize, Loop *CurLoop,
826 const DataLayout *DL, ScalarEvolution *SE) {
827 const SCEV *NumBytesS;
828 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
829 // pointer size if it isn't already.
830 //
831 // If we're going to need to zero extend the BE count, check if we can add
832 // one to it prior to zero extending without overflow. Provided this is safe,
833 // it allows better simplification of the +1.
834 if (DL->getTypeSizeInBits(BECount->getType()) <
835 DL->getTypeSizeInBits(IntPtr) &&
836 SE->isLoopEntryGuardedByCond(
837 CurLoop, ICmpInst::ICMP_NE, BECount,
838 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) {
839 NumBytesS = SE->getZeroExtendExpr(
840 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW),
841 IntPtr);
842 } else {
843 NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr),
844 SE->getOne(IntPtr), SCEV::FlagNUW);
845 }
846
847 // And scale it based on the store size.
848 if (StoreSize != 1) {
849 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
850 SCEV::FlagNUW);
851 }
852 return NumBytesS;
853}
854
Chris Lattner0f4a6402011-02-19 19:31:39 +0000855/// processLoopStridedStore - We see a strided store of some value. If we can
856/// transform this into a memset or memset_pattern in the loop preheader, do so.
Chandler Carruthbad690e2015-08-12 23:06:37 +0000857bool LoopIdiomRecognize::processLoopStridedStore(
858 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000859 Value *StoredVal, Instruction *TheStore,
860 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000861 const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
Chris Lattner0f4a6402011-02-19 19:31:39 +0000862 Value *SplatValue = isBytewiseValue(StoredVal);
Craig Topperf40110f2014-04-25 05:29:35 +0000863 Constant *PatternValue = nullptr;
Matt Arsenault009faed2013-09-11 05:09:42 +0000864
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000865 if (!SplatValue)
866 PatternValue = getMemSetPatternValue(StoredVal, DL);
867
868 assert((SplatValue || PatternValue) &&
869 "Expected either splat value or pattern value.");
Andrew Trick328b2232011-03-14 16:48:10 +0000870
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000871 // The trip count of the loop and the base pointer of the addrec SCEV is
872 // guaranteed to be loop invariant, which means that it should dominate the
873 // header. This allows us to insert code for it in the preheader.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000874 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000875 BasicBlock *Preheader = CurLoop->getLoopPreheader();
876 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000877 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000878
Matt Arsenault009faed2013-09-11 05:09:42 +0000879 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
Chad Rosier43f9b482015-11-06 16:33:57 +0000880 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
Chad Rosier79676142015-10-28 14:38:49 +0000881
882 const SCEV *Start = Ev->getStart();
Chad Rosier2fa50a72015-11-13 19:13:40 +0000883 // Handle negative strided loops.
Chad Rosiered0c7d12015-11-13 19:11:07 +0000884 if (NegStride)
885 Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
Matt Arsenault009faed2013-09-11 05:09:42 +0000886
Aditya Kumar1c42d132017-05-05 14:49:45 +0000887 // TODO: ideally we should still be able to generate memset if SCEV expander
888 // is taught to generate the dependencies at the latest point.
889 if (!isSafeToExpand(Start, *SE))
890 return false;
891
Chris Lattner29e14ed2010-12-26 23:42:51 +0000892 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
Benjamin Kramerf77f2242012-10-21 19:31:16 +0000893 // this into a memset in the loop preheader now if we want. However, this
894 // would be unsafe to do if there is anything else in the loop that may read
Chandler Carruth7ec50852012-11-01 08:07:29 +0000895 // or write to the aliased location. Check for any overlap by generating the
896 // base pointer and checking the region.
Chad Rosier79676142015-10-28 14:38:49 +0000897 Value *BasePtr =
898 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
Alina Sbirlea193429f2017-12-07 22:41:34 +0000899 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
900 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000901 Expander.clear();
902 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +0000903 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +0000904 return false;
905 }
906
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +0000907 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
908 return false;
909
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000910 // Okay, everything looks good, insert the memset.
911
Chandler Carruthbad690e2015-08-12 23:06:37 +0000912 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +0000913 getNumBytes(BECount, IntPtr, StoreSize, CurLoop, DL, SE);
Andrew Trick328b2232011-03-14 16:48:10 +0000914
Aditya Kumar1c42d132017-05-05 14:49:45 +0000915 // TODO: ideally we should still be able to generate memset if SCEV expander
916 // is taught to generate the dependencies at the latest point.
917 if (!isSafeToExpand(NumBytesS, *SE))
918 return false;
919
Andrew Trick328b2232011-03-14 16:48:10 +0000920 Value *NumBytes =
Chandler Carruthbad690e2015-08-12 23:06:37 +0000921 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
Andrew Trick328b2232011-03-14 16:48:10 +0000922
Devang Pateld00c6282011-03-07 22:43:45 +0000923 CallInst *NewCall;
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000924 if (SplatValue) {
Chandler Carruthbad690e2015-08-12 23:06:37 +0000925 NewCall =
926 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
Matt Arsenault5df49bd2013-09-11 05:09:35 +0000927 } else {
Matt Arsenault009faed2013-09-11 05:09:42 +0000928 // Everything is emitted in default address space
929 Type *Int8PtrTy = DestInt8PtrTy;
930
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000931 Module *M = TheStore->getModule();
David Bolvansky7c7760d2018-10-16 21:18:31 +0000932 StringRef FuncName = "memset_pattern16";
James Y Knight13680222019-02-01 02:28:03 +0000933 FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(),
934 Int8PtrTy, Int8PtrTy, IntPtr);
David Bolvansky7c7760d2018-10-16 21:18:31 +0000935 inferLibFuncAttributes(M, FuncName, *TLI);
Andrew Trick328b2232011-03-14 16:48:10 +0000936
Chris Lattner0f4a6402011-02-19 19:31:39 +0000937 // Otherwise we should form a memset_pattern16. PatternValue is known to be
938 // an constant array of 16-bytes. Plop the value into a mergable global.
939 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
Benjamin Kramer838752d2015-03-03 00:17:09 +0000940 GlobalValue::PrivateLinkage,
Chris Lattner0f4a6402011-02-19 19:31:39 +0000941 PatternValue, ".memset_pattern");
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000942 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
Chris Lattner0f4a6402011-02-19 19:31:39 +0000943 GV->setAlignment(16);
Matt Arsenault009faed2013-09-11 05:09:42 +0000944 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
David Blaikieff6409d2015-05-18 22:13:54 +0000945 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
Chris Lattner0f4a6402011-02-19 19:31:39 +0000946 }
Andrew Trick328b2232011-03-14 16:48:10 +0000947
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000948 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
949 << " from store to: " << *Ev << " at: " << *TheStore
950 << "\n");
Devang Pateld00c6282011-03-07 22:43:45 +0000951 NewCall->setDebugLoc(TheStore->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +0000952
Chris Lattnerb9fe6852010-12-27 00:03:23 +0000953 // Okay, the memset has been formed. Zap the original store and anything that
954 // feeds into it.
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000955 for (auto *I : Stores)
David Majnemer41ff4fd2016-06-20 16:07:38 +0000956 deleteDeadInstruction(I);
Chris Lattner12f91be2011-01-02 07:36:44 +0000957 ++NumMemSet;
Chris Lattner29e14ed2010-12-26 23:42:51 +0000958 return true;
959}
960
Chad Rosier1cd3da12015-11-19 21:33:07 +0000961/// If the stored value is a strided load in the same loop with the same stride
962/// this may be transformable into a memcpy. This kicks in for stuff like
Xin Tonga41bf702017-05-01 23:08:19 +0000963/// for (i) A[i] = B[i];
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000964bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
965 const SCEV *BECount) {
Anna Thomasb2a212c2017-06-06 16:45:25 +0000966 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000967
968 Value *StorePtr = SI->getPointerOperand();
969 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chad Rosier4acff962016-02-12 19:05:27 +0000970 APInt Stride = getStoreStride(StoreEv);
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +0000971 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000972 bool NegStride = StoreSize == -Stride;
Andrew Trick328b2232011-03-14 16:48:10 +0000973
Chad Rosierfddc01f2015-11-19 18:22:21 +0000974 // The store must be feeding a non-volatile load.
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000975 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
Anna Thomasb2a212c2017-06-06 16:45:25 +0000976 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
Chad Rosierfddc01f2015-11-19 18:22:21 +0000977
978 // See if the pointer expression is an AddRec like {base,+,1} on the current
979 // loop, which indicates a strided load. If we have something else, it's a
980 // random load we can't handle.
Chad Rosier3ecc8d82015-11-19 18:25:11 +0000981 const SCEVAddRecExpr *LoadEv =
Haicheng Wu9d6c9402016-01-04 21:43:14 +0000982 cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
Andrew Trick328b2232011-03-14 16:48:10 +0000983
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +0000984 // The trip count of the loop and the base pointer of the addrec SCEV is
985 // guaranteed to be loop invariant, which means that it should dominate the
986 // header. This allows us to insert code for it in the preheader.
987 BasicBlock *Preheader = CurLoop->getLoopPreheader();
988 IRBuilder<> Builder(Preheader->getTerminator());
Chad Rosier43f9b482015-11-06 16:33:57 +0000989 SCEVExpander Expander(*SE, *DL, "loop-idiom");
Andrew Trick60ab3ef2011-06-28 05:04:16 +0000990
Chad Rosiercc299b62015-11-13 21:51:02 +0000991 const SCEV *StrStart = StoreEv->getStart();
992 unsigned StrAS = SI->getPointerAddressSpace();
993 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
994
995 // Handle negative strided loops.
996 if (NegStride)
997 StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
998
Chris Lattner85b6d812011-01-02 03:37:56 +0000999 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001000 // this into a memcpy in the loop preheader now if we want. However, this
1001 // would be unsafe to do if there is anything else in the loop that may read
1002 // or write the memory region we're storing to. This includes the load that
1003 // feeds the stores. Check for an alias by generating the base address and
1004 // checking everything.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001005 Value *StoreBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +00001006 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001007
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001008 SmallPtrSet<Instruction *, 1> Stores;
1009 Stores.insert(SI);
Alina Sbirlea193429f2017-12-07 22:41:34 +00001010 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001011 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001012 Expander.clear();
1013 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001014 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001015 return false;
1016 }
1017
Chad Rosiercc299b62015-11-13 21:51:02 +00001018 const SCEV *LdStart = LoadEv->getStart();
1019 unsigned LdAS = LI->getPointerAddressSpace();
1020
1021 // Handle negative strided loops.
1022 if (NegStride)
1023 LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
1024
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001025 // For a memcpy, we have to make sure that the input array is not being
1026 // mutated by the loop.
Chandler Carruthbad690e2015-08-12 23:06:37 +00001027 Value *LoadBasePtr = Expander.expandCodeFor(
Chad Rosiercc299b62015-11-13 21:51:02 +00001028 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001029
Alina Sbirlea193429f2017-12-07 22:41:34 +00001030 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1031 StoreSize, *AA, Stores)) {
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001032 Expander.clear();
1033 // If we generated new code for the base pointer, clean up.
Benjamin Kramerf094d772015-02-07 21:37:08 +00001034 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1035 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001036 return false;
1037 }
1038
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001039 if (avoidLIRForMultiBlockLoop())
1040 return false;
1041
Chris Lattnerc4ca7ab2011-05-22 17:39:56 +00001042 // Okay, everything is safe, we can transform this!
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001043
Chandler Carruthbad690e2015-08-12 23:06:37 +00001044 const SCEV *NumBytesS =
Chandler Carruth1dc34c62017-07-25 10:48:32 +00001045 getNumBytes(BECount, IntPtrTy, StoreSize, CurLoop, DL, SE);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001046
1047 Value *NumBytes =
1048 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1049
Anna Thomasb2a212c2017-06-06 16:45:25 +00001050 CallInst *NewCall = nullptr;
1051 // Check whether to generate an unordered atomic memcpy:
Hiroshi Inouef2096492018-06-14 05:41:49 +00001052 // If the load or store are atomic, then they must necessarily be unordered
Anna Thomasb2a212c2017-06-06 16:45:25 +00001053 // by previous checks.
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001054 if (!SI->isAtomic() && !LI->isAtomic())
Daniel Neilsonfb99a492018-02-08 17:33:08 +00001055 NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlignment(),
1056 LoadBasePtr, LI->getAlignment(), NumBytes);
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001057 else {
Anna Thomasb2a212c2017-06-06 16:45:25 +00001058 // We cannot allow unaligned ops for unordered load/store, so reject
1059 // anything where the alignment isn't at least the element size.
Daniel Neilsonfb99a492018-02-08 17:33:08 +00001060 unsigned Align = std::min(SI->getAlignment(), LI->getAlignment());
Anna Thomasb2a212c2017-06-06 16:45:25 +00001061 if (Align < StoreSize)
1062 return false;
1063
1064 // If the element.atomic memcpy is not lowered into explicit
1065 // loads/stores later, then it will be lowered into an element-size
1066 // specific lib call. If the lib call doesn't exist for our store size, then
1067 // we shouldn't generate the memcpy.
1068 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1069 return false;
1070
Daniel Neilson6e4aa1e2017-11-10 19:38:12 +00001071 // Create the call.
1072 // Note that unordered atomic loads/stores are *required* by the spec to
1073 // have an alignment but non-atomic loads/stores may not.
Daniel Neilson3faabbb2017-06-16 14:43:59 +00001074 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
Daniel Neilson6e4aa1e2017-11-10 19:38:12 +00001075 StoreBasePtr, SI->getAlignment(), LoadBasePtr, LI->getAlignment(),
1076 NumBytes, StoreSize);
Anna Thomasb2a212c2017-06-06 16:45:25 +00001077 }
Devang Patel0daa07e2011-05-04 21:37:05 +00001078 NewCall->setDebugLoc(SI->getDebugLoc());
Andrew Trick328b2232011-03-14 16:48:10 +00001079
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001080 LLVM_DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
1081 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1082 << " from store ptr=" << *StoreEv << " at: " << *SI
1083 << "\n");
Andrew Trick60ab3ef2011-06-28 05:04:16 +00001084
Chad Rosier7f08d802015-10-13 20:59:16 +00001085 // Okay, the memcpy has been formed. Zap the original store and anything that
Chris Lattner85b6d812011-01-02 03:37:56 +00001086 // feeds into it.
David Majnemer41ff4fd2016-06-20 16:07:38 +00001087 deleteDeadInstruction(SI);
Chandler Carruth099f5cb02012-11-02 08:33:25 +00001088 ++NumMemCpy;
Chris Lattner85b6d812011-01-02 03:37:56 +00001089 return true;
1090}
Chandler Carruthd9c60702015-08-13 00:10:03 +00001091
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001092// When compiling for codesize we avoid idiom recognition for a multi-block loop
1093// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1094//
1095bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1096 bool IsLoopMemset) {
1097 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1098 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001099 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1100 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1101 << " avoided: multi-block top-level loop\n");
Andrew Kaylor7cdf01e2016-08-11 18:28:33 +00001102 return true;
1103 }
1104 }
1105
1106 return false;
1107}
1108
Chandler Carruthd9c60702015-08-13 00:10:03 +00001109bool LoopIdiomRecognize::runOnNoncountableLoop() {
Craig Topperc9a60002018-12-26 21:59:48 +00001110 return recognizePopcount() || recognizeAndInsertFFS();
Chandler Carruthd9c60702015-08-13 00:10:03 +00001111}
Chandler Carruth8219a502015-08-13 00:44:29 +00001112
1113/// Check if the given conditional branch is based on the comparison between
Craig Topperc9a60002018-12-26 21:59:48 +00001114/// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
1115/// true), the control yields to the loop entry. If the branch matches the
1116/// behavior, the variable involved in the comparison is returned. This function
1117/// will be called to see if the precondition and postcondition of the loop are
1118/// in desirable form.
1119static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry,
1120 bool JmpOnZero = false) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001121 if (!BI || !BI->isConditional())
1122 return nullptr;
1123
1124 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1125 if (!Cond)
1126 return nullptr;
1127
1128 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1129 if (!CmpZero || !CmpZero->isZero())
1130 return nullptr;
1131
Craig Topperc9a60002018-12-26 21:59:48 +00001132 BasicBlock *TrueSucc = BI->getSuccessor(0);
1133 BasicBlock *FalseSucc = BI->getSuccessor(1);
1134 if (JmpOnZero)
1135 std::swap(TrueSucc, FalseSucc);
1136
Chandler Carruth8219a502015-08-13 00:44:29 +00001137 ICmpInst::Predicate Pred = Cond->getPredicate();
Craig Topperc9a60002018-12-26 21:59:48 +00001138 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
1139 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
Chandler Carruth8219a502015-08-13 00:44:29 +00001140 return Cond->getOperand(0);
1141
1142 return nullptr;
1143}
1144
Davide Italiano4bc91192017-05-23 22:32:56 +00001145// Check if the recurrence variable `VarX` is in the right form to create
1146// the idiom. Returns the value coerced to a PHINode if so.
1147static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1148 BasicBlock *LoopEntry) {
1149 auto *PhiX = dyn_cast<PHINode>(VarX);
1150 if (PhiX && PhiX->getParent() == LoopEntry &&
1151 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1152 return PhiX;
1153 return nullptr;
1154}
1155
Chandler Carruth8219a502015-08-13 00:44:29 +00001156/// Return true iff the idiom is detected in the loop.
1157///
1158/// Additionally:
1159/// 1) \p CntInst is set to the instruction counting the population bit.
1160/// 2) \p CntPhi is set to the corresponding phi node.
1161/// 3) \p Var is set to the value whose population bits are being counted.
1162///
1163/// The core idiom we are trying to detect is:
1164/// \code
1165/// if (x0 != 0)
1166/// goto loop-exit // the precondition of the loop
1167/// cnt0 = init-val;
1168/// do {
1169/// x1 = phi (x0, x2);
1170/// cnt1 = phi(cnt0, cnt2);
1171///
1172/// cnt2 = cnt1 + 1;
1173/// ...
1174/// x2 = x1 & (x1 - 1);
1175/// ...
1176/// } while(x != 0);
1177///
1178/// loop-exit:
1179/// \endcode
1180static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1181 Instruction *&CntInst, PHINode *&CntPhi,
1182 Value *&Var) {
1183 // step 1: Check to see if the look-back branch match this pattern:
1184 // "if (a!=0) goto loop-entry".
1185 BasicBlock *LoopEntry;
1186 Instruction *DefX2, *CountInst;
1187 Value *VarX1, *VarX0;
1188 PHINode *PhiX, *CountPhi;
1189
1190 DefX2 = CountInst = nullptr;
1191 VarX1 = VarX0 = nullptr;
1192 PhiX = CountPhi = nullptr;
1193 LoopEntry = *(CurLoop->block_begin());
1194
1195 // step 1: Check if the loop-back branch is in desirable form.
1196 {
1197 if (Value *T = matchCondition(
1198 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1199 DefX2 = dyn_cast<Instruction>(T);
1200 else
1201 return false;
1202 }
1203
1204 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1205 {
1206 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1207 return false;
1208
1209 BinaryOperator *SubOneOp;
1210
1211 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1212 VarX1 = DefX2->getOperand(1);
1213 else {
1214 VarX1 = DefX2->getOperand(0);
1215 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1216 }
Craig Topper856fd682018-05-03 05:48:49 +00001217 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001218 return false;
1219
Craig Topper8ef2abd2018-05-03 05:00:18 +00001220 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
Chandler Carruth8219a502015-08-13 00:44:29 +00001221 if (!Dec ||
Craig Topper8ef2abd2018-05-03 05:00:18 +00001222 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1223 (SubOneOp->getOpcode() == Instruction::Add &&
Craig Topper79ab6432017-07-06 18:39:47 +00001224 Dec->isMinusOne()))) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001225 return false;
1226 }
1227 }
1228
1229 // step 3: Check the recurrence of variable X
Davide Italiano4bc91192017-05-23 22:32:56 +00001230 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1231 if (!PhiX)
1232 return false;
Chandler Carruth8219a502015-08-13 00:44:29 +00001233
1234 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1235 {
1236 CountInst = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001237 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
Chandler Carruth8219a502015-08-13 00:44:29 +00001238 IterE = LoopEntry->end();
1239 Iter != IterE; Iter++) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001240 Instruction *Inst = &*Iter;
Chandler Carruth8219a502015-08-13 00:44:29 +00001241 if (Inst->getOpcode() != Instruction::Add)
1242 continue;
1243
1244 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1245 if (!Inc || !Inc->isOne())
1246 continue;
1247
Davide Italiano7bf95b92017-05-23 23:51:54 +00001248 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1249 if (!Phi)
Chandler Carruth8219a502015-08-13 00:44:29 +00001250 continue;
1251
1252 // Check if the result of the instruction is live of the loop.
1253 bool LiveOutLoop = false;
1254 for (User *U : Inst->users()) {
1255 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1256 LiveOutLoop = true;
1257 break;
1258 }
1259 }
1260
1261 if (LiveOutLoop) {
1262 CountInst = Inst;
1263 CountPhi = Phi;
1264 break;
1265 }
1266 }
1267
1268 if (!CountInst)
1269 return false;
1270 }
1271
1272 // step 5: check if the precondition is in this form:
1273 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1274 {
1275 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1276 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1277 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1278 return false;
1279
1280 CntInst = CountInst;
1281 CntPhi = CountPhi;
1282 Var = T;
1283 }
1284
1285 return true;
1286}
1287
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001288/// Return true if the idiom is detected in the loop.
1289///
1290/// Additionally:
1291/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1292/// or nullptr if there is no such.
1293/// 2) \p CntPhi is set to the corresponding phi node
1294/// or nullptr if there is no such.
1295/// 3) \p Var is set to the value whose CTLZ could be used.
1296/// 4) \p DefX is set to the instruction calculating Loop exit condition.
1297///
1298/// The core idiom we are trying to detect is:
1299/// \code
1300/// if (x0 == 0)
1301/// goto loop-exit // the precondition of the loop
1302/// cnt0 = init-val;
1303/// do {
1304/// x = phi (x0, x.next); //PhiX
1305/// cnt = phi(cnt0, cnt.next);
1306///
1307/// cnt.next = cnt + 1;
1308/// ...
1309/// x.next = x >> 1; // DefX
1310/// ...
1311/// } while(x.next != 0);
1312///
1313/// loop-exit:
1314/// \endcode
Craig Topperc9a60002018-12-26 21:59:48 +00001315static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
1316 Intrinsic::ID &IntrinID, Value *&InitX,
1317 Instruction *&CntInst, PHINode *&CntPhi,
1318 Instruction *&DefX) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001319 BasicBlock *LoopEntry;
1320 Value *VarX = nullptr;
1321
1322 DefX = nullptr;
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001323 CntInst = nullptr;
1324 CntPhi = nullptr;
1325 LoopEntry = *(CurLoop->block_begin());
1326
1327 // step 1: Check if the loop-back branch is in desirable form.
1328 if (Value *T = matchCondition(
1329 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1330 DefX = dyn_cast<Instruction>(T);
1331 else
1332 return false;
1333
Craig Topperc9a60002018-12-26 21:59:48 +00001334 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
1335 if (!DefX || !DefX->isShift())
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001336 return false;
Craig Topperc9a60002018-12-26 21:59:48 +00001337 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
1338 Intrinsic::ctlz;
Evgeny Stupachenkod699de22017-11-03 18:50:03 +00001339 ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));
1340 if (!Shft || !Shft->isOne())
1341 return false;
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001342 VarX = DefX->getOperand(0);
1343
1344 // step 3: Check the recurrence of variable X
Craig Topperc9a60002018-12-26 21:59:48 +00001345 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
Davide Italiano4bc91192017-05-23 22:32:56 +00001346 if (!PhiX)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001347 return false;
1348
Craig Topperc9a60002018-12-26 21:59:48 +00001349 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
1350
1351 // Make sure the initial value can't be negative otherwise the ashr in the
1352 // loop might never reach zero which would make the loop infinite.
1353 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
1354 return false;
1355
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001356 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1357 // TODO: We can skip the step. If loop trip count is known (CTLZ),
1358 // then all uses of "cnt.next" could be optimized to the trip count
1359 // plus "cnt0". Currently it is not optimized.
1360 // This step could be used to detect POPCNT instruction:
1361 // cnt.next = cnt + (x.next & 1)
1362 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1363 IterE = LoopEntry->end();
1364 Iter != IterE; Iter++) {
1365 Instruction *Inst = &*Iter;
1366 if (Inst->getOpcode() != Instruction::Add)
1367 continue;
1368
1369 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1370 if (!Inc || !Inc->isOne())
1371 continue;
1372
Davide Italiano7bf95b92017-05-23 23:51:54 +00001373 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1374 if (!Phi)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001375 continue;
1376
1377 CntInst = Inst;
1378 CntPhi = Phi;
1379 break;
1380 }
1381 if (!CntInst)
1382 return false;
1383
1384 return true;
1385}
1386
Craig Topperc9a60002018-12-26 21:59:48 +00001387/// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
1388/// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
1389/// trip count returns true; otherwise, returns false.
1390bool LoopIdiomRecognize::recognizeAndInsertFFS() {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001391 // Give up if the loop has multiple blocks or multiple backedges.
1392 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1393 return false;
1394
Craig Topperc9a60002018-12-26 21:59:48 +00001395 Intrinsic::ID IntrinID;
1396 Value *InitX;
1397 Instruction *DefX = nullptr;
1398 PHINode *CntPhi = nullptr;
1399 Instruction *CntInst = nullptr;
1400 // Help decide if transformation is profitable. For ShiftUntilZero idiom,
1401 // this is always 6.
1402 size_t IdiomCanonicalSize = 6;
1403
1404 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX,
1405 CntInst, CntPhi, DefX))
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001406 return false;
1407
1408 bool IsCntPhiUsedOutsideLoop = false;
1409 for (User *U : CntPhi->users())
Craig Topper83042312018-05-04 01:04:24 +00001410 if (!CurLoop->contains(cast<Instruction>(U))) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001411 IsCntPhiUsedOutsideLoop = true;
1412 break;
1413 }
1414 bool IsCntInstUsedOutsideLoop = false;
1415 for (User *U : CntInst->users())
Craig Topper83042312018-05-04 01:04:24 +00001416 if (!CurLoop->contains(cast<Instruction>(U))) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001417 IsCntInstUsedOutsideLoop = true;
1418 break;
1419 }
1420 // If both CntInst and CntPhi are used outside the loop the profitability
1421 // is questionable.
1422 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1423 return false;
1424
1425 // For some CPUs result of CTLZ(X) intrinsic is undefined
1426 // when X is 0. If we can not guarantee X != 0, we need to check this
1427 // when expand.
1428 bool ZeroCheck = false;
1429 // It is safe to assume Preheader exist as it was checked in
1430 // parent function RunOnLoop.
1431 BasicBlock *PH = CurLoop->getLoopPreheader();
Craig Topper9a6c0bd2018-05-31 22:16:55 +00001432
Craig Toppered6acde2018-07-11 22:35:28 +00001433 // If we are using the count instruction outside the loop, make sure we
1434 // have a zero check as a precondition. Without the check the loop would run
1435 // one iteration for before any check of the input value. This means 0 and 1
1436 // would have identical behavior in the original loop and thus
1437 if (!IsCntPhiUsedOutsideLoop) {
1438 auto *PreCondBB = PH->getSinglePredecessor();
1439 if (!PreCondBB)
1440 return false;
1441 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1442 if (!PreCondBI)
1443 return false;
1444 if (matchCondition(PreCondBI, PH) != InitX)
1445 return false;
1446 ZeroCheck = true;
1447 }
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001448
Craig Topperc9a60002018-12-26 21:59:48 +00001449 // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
1450 // profitable if we delete the loop.
1451
1452 // the loop has only 6 instructions:
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001453 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1454 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1455 // %shr = ashr %n.addr.0, 1
1456 // %tobool = icmp eq %shr, 0
1457 // %inc = add nsw %i.0, 1
1458 // br i1 %tobool
1459
Craig Toppercafae622018-05-04 01:04:26 +00001460 const Value *Args[] =
Craig Topperded8ee02018-05-04 17:39:08 +00001461 {InitX, ZeroCheck ? ConstantInt::getTrue(InitX->getContext())
1462 : ConstantInt::getFalse(InitX->getContext())};
Craig Topperc9a60002018-12-26 21:59:48 +00001463 if (CurLoop->getHeader()->size() != IdiomCanonicalSize &&
1464 TTI->getIntrinsicCost(IntrinID, InitX->getType(), Args) >
1465 TargetTransformInfo::TCC_Basic)
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001466 return false;
1467
Craig Topperc9a60002018-12-26 21:59:48 +00001468 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
Craig Topper28352782018-07-08 01:45:47 +00001469 DefX->getDebugLoc(), ZeroCheck,
1470 IsCntPhiUsedOutsideLoop);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001471 return true;
1472}
1473
Chandler Carruth8219a502015-08-13 00:44:29 +00001474/// Recognizes a population count idiom in a non-countable loop.
1475///
1476/// If detected, transforms the relevant code to issue the popcount intrinsic
1477/// function call, and returns true; otherwise, returns false.
1478bool LoopIdiomRecognize::recognizePopcount() {
Chandler Carruth8219a502015-08-13 00:44:29 +00001479 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1480 return false;
1481
1482 // Counting population are usually conducted by few arithmetic instructions.
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001483 // Such instructions can be easily "absorbed" by vacant slots in a
Chandler Carruth8219a502015-08-13 00:44:29 +00001484 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1485 // in a compact loop.
1486
Renato Golin655348f2015-08-13 11:25:38 +00001487 // Give up if the loop has multiple blocks or multiple backedges.
1488 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
Chandler Carruth8219a502015-08-13 00:44:29 +00001489 return false;
1490
Renato Golin655348f2015-08-13 11:25:38 +00001491 BasicBlock *LoopBody = *(CurLoop->block_begin());
1492 if (LoopBody->size() >= 20) {
1493 // The loop is too big, bail out.
Chandler Carruth8219a502015-08-13 00:44:29 +00001494 return false;
Renato Golin655348f2015-08-13 11:25:38 +00001495 }
Chandler Carruth8219a502015-08-13 00:44:29 +00001496
1497 // It should have a preheader containing nothing but an unconditional branch.
Renato Golin655348f2015-08-13 11:25:38 +00001498 BasicBlock *PH = CurLoop->getLoopPreheader();
Davide Italianoc0169fa2016-10-07 18:39:43 +00001499 if (!PH || &PH->front() != PH->getTerminator())
Renato Golin655348f2015-08-13 11:25:38 +00001500 return false;
1501 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001502 if (!EntryBI || EntryBI->isConditional())
1503 return false;
1504
Hiroshi Inouef2096492018-06-14 05:41:49 +00001505 // It should have a precondition block where the generated popcount intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001506 // function can be inserted.
Renato Golin655348f2015-08-13 11:25:38 +00001507 auto *PreCondBB = PH->getSinglePredecessor();
Chandler Carruth8219a502015-08-13 00:44:29 +00001508 if (!PreCondBB)
1509 return false;
1510 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1511 if (!PreCondBI || PreCondBI->isUnconditional())
1512 return false;
1513
1514 Instruction *CntInst;
1515 PHINode *CntPhi;
1516 Value *Val;
1517 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1518 return false;
1519
1520 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1521 return true;
1522}
1523
1524static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001525 const DebugLoc &DL) {
Chandler Carruth8219a502015-08-13 00:44:29 +00001526 Value *Ops[] = {Val};
1527 Type *Tys[] = {Val->getType()};
1528
1529 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
James Y Knight7976eb52019-02-01 20:43:25 +00001530 Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
Chandler Carruth8219a502015-08-13 00:44:29 +00001531 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1532 CI->setDebugLoc(DL);
1533
1534 return CI;
1535}
1536
Craig Topperc9a60002018-12-26 21:59:48 +00001537static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1538 const DebugLoc &DL, bool ZeroCheck,
1539 Intrinsic::ID IID) {
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001540 Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()};
1541 Type *Tys[] = {Val->getType()};
1542
1543 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
James Y Knight7976eb52019-02-01 20:43:25 +00001544 Function *Func = Intrinsic::getDeclaration(M, IID, Tys);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001545 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1546 CI->setDebugLoc(DL);
1547
1548 return CI;
1549}
1550
Craig Topperc9a60002018-12-26 21:59:48 +00001551/// Transform the following loop (Using CTLZ, CTTZ is similar):
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001552/// loop:
1553/// CntPhi = PHI [Cnt0, CntInst]
1554/// PhiX = PHI [InitX, DefX]
1555/// CntInst = CntPhi + 1
1556/// DefX = PhiX >> 1
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001557/// LOOP_BODY
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001558/// Br: loop if (DefX != 0)
1559/// Use(CntPhi) or Use(CntInst)
1560///
1561/// Into:
1562/// If CntPhi used outside the loop:
1563/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1564/// Count = CountPrev + 1
1565/// else
1566/// Count = BitWidth(InitX) - CTLZ(InitX)
1567/// loop:
1568/// CntPhi = PHI [Cnt0, CntInst]
1569/// PhiX = PHI [InitX, DefX]
1570/// PhiCount = PHI [Count, Dec]
1571/// CntInst = CntPhi + 1
1572/// DefX = PhiX >> 1
1573/// Dec = PhiCount - 1
1574/// LOOP_BODY
1575/// Br: loop if (Dec != 0)
1576/// Use(CountPrev + Cnt0) // Use(CntPhi)
1577/// or
1578/// Use(Count + Cnt0) // Use(CntInst)
1579///
1580/// If LOOP_BODY is empty the loop will be deleted.
1581/// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1582void LoopIdiomRecognize::transformLoopToCountable(
Craig Topperc9a60002018-12-26 21:59:48 +00001583 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
1584 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
1585 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
Craig Topper9510f702018-05-04 01:04:28 +00001586 BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001587
Craig Topperc9a60002018-12-26 21:59:48 +00001588 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
1589 IRBuilder<> Builder(PreheaderBr);
1590 Builder.SetCurrentDebugLocation(DL);
1591 Value *FFS, *Count, *CountPrev, *NewCount, *InitXNext;
1592
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001593 // Count = BitWidth - CTLZ(InitX);
1594 // If there are uses of CntPhi create:
1595 // CountPrev = BitWidth - CTLZ(InitX >> 1);
Craig Topper28352782018-07-08 01:45:47 +00001596 if (IsCntPhiUsedOutsideLoop) {
1597 if (DefX->getOpcode() == Instruction::AShr)
1598 InitXNext =
1599 Builder.CreateAShr(InitX, ConstantInt::get(InitX->getType(), 1));
1600 else if (DefX->getOpcode() == Instruction::LShr)
1601 InitXNext =
1602 Builder.CreateLShr(InitX, ConstantInt::get(InitX->getType(), 1));
Craig Topperc9a60002018-12-26 21:59:48 +00001603 else if (DefX->getOpcode() == Instruction::Shl) // cttz
1604 InitXNext =
1605 Builder.CreateShl(InitX, ConstantInt::get(InitX->getType(), 1));
Craig Topper28352782018-07-08 01:45:47 +00001606 else
Fangrui Songf78650a2018-07-30 19:41:25 +00001607 llvm_unreachable("Unexpected opcode!");
Craig Topper28352782018-07-08 01:45:47 +00001608 } else
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001609 InitXNext = InitX;
Craig Topperc9a60002018-12-26 21:59:48 +00001610 FFS = createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001611 Count = Builder.CreateSub(
Craig Topperc9a60002018-12-26 21:59:48 +00001612 ConstantInt::get(FFS->getType(),
1613 FFS->getType()->getIntegerBitWidth()),
1614 FFS);
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001615 if (IsCntPhiUsedOutsideLoop) {
1616 CountPrev = Count;
1617 Count = Builder.CreateAdd(
1618 CountPrev,
1619 ConstantInt::get(CountPrev->getType(), 1));
1620 }
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001621
Craig Topperc9a60002018-12-26 21:59:48 +00001622 NewCount = Builder.CreateZExtOrTrunc(
1623 IsCntPhiUsedOutsideLoop ? CountPrev : Count,
1624 cast<IntegerType>(CntInst->getType()));
1625
1626 // If the counter's initial value is not zero, insert Add Inst.
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001627 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1628 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1629 if (!InitConst || !InitConst->isZero())
1630 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1631
1632 // Step 2: Insert new IV and loop condition:
1633 // loop:
1634 // ...
1635 // PhiCount = PHI [Count, Dec]
1636 // ...
1637 // Dec = PhiCount - 1
1638 // ...
1639 // Br: loop if (Dec != 0)
1640 BasicBlock *Body = *(CurLoop->block_begin());
Craig Topper9510f702018-05-04 01:04:28 +00001641 auto *LbBr = cast<BranchInst>(Body->getTerminator());
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001642 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1643 Type *Ty = Count->getType();
1644
1645 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1646
1647 Builder.SetInsertPoint(LbCond);
1648 Instruction *TcDec = cast<Instruction>(
1649 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1650 "tcdec", false, true));
1651
1652 TcPhi->addIncoming(Count, Preheader);
1653 TcPhi->addIncoming(TcDec, Body);
1654
1655 CmpInst::Predicate Pred =
1656 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
1657 LbCond->setPredicate(Pred);
1658 LbCond->setOperand(0, TcDec);
1659 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1660
1661 // Step 3: All the references to the original counter outside
Craig Topperc9a60002018-12-26 21:59:48 +00001662 // the loop are replaced with the NewCount
Evgeny Stupachenko2fecd382017-05-15 19:08:56 +00001663 if (IsCntPhiUsedOutsideLoop)
1664 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
1665 else
1666 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1667
1668 // step 4: Forget the "non-computable" trip-count SCEV associated with the
1669 // loop. The loop would otherwise not be deleted even if it becomes empty.
1670 SE->forgetLoop(CurLoop);
1671}
1672
Chandler Carruth8219a502015-08-13 00:44:29 +00001673void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1674 Instruction *CntInst,
1675 PHINode *CntPhi, Value *Var) {
1676 BasicBlock *PreHead = CurLoop->getLoopPreheader();
Craig Topper9510f702018-05-04 01:04:28 +00001677 auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());
Craig Topper27847862018-06-25 20:45:45 +00001678 const DebugLoc &DL = CntInst->getDebugLoc();
Chandler Carruth8219a502015-08-13 00:44:29 +00001679
1680 // Assuming before transformation, the loop is following:
1681 // if (x) // the precondition
1682 // do { cnt++; x &= x - 1; } while(x);
1683
1684 // Step 1: Insert the ctpop instruction at the end of the precondition block
1685 IRBuilder<> Builder(PreCondBr);
1686 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1687 {
1688 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1689 NewCount = PopCntZext =
1690 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1691
1692 if (NewCount != PopCnt)
1693 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1694
1695 // TripCnt is exactly the number of iterations the loop has
1696 TripCnt = NewCount;
1697
1698 // If the population counter's initial value is not zero, insert Add Inst.
1699 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1700 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1701 if (!InitConst || !InitConst->isZero()) {
1702 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1703 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1704 }
1705 }
1706
Nick Lewycky2c852542015-08-19 06:22:33 +00001707 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
Nick Lewycky1098e492015-08-19 06:25:30 +00001708 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
Chandler Carruth8219a502015-08-13 00:44:29 +00001709 // function would be partial dead code, and downstream passes will drag
1710 // it back from the precondition block to the preheader.
1711 {
1712 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1713
1714 Value *Opnd0 = PopCntZext;
1715 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1716 if (PreCond->getOperand(0) != Var)
1717 std::swap(Opnd0, Opnd1);
1718
1719 ICmpInst *NewPreCond = cast<ICmpInst>(
1720 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1721 PreCondBr->setCondition(NewPreCond);
1722
1723 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1724 }
1725
1726 // Step 3: Note that the population count is exactly the trip count of the
Hiroshi Inouec8e92452018-01-29 05:17:03 +00001727 // loop in question, which enable us to convert the loop from noncountable
Chandler Carruth8219a502015-08-13 00:44:29 +00001728 // loop into a countable one. The benefit is twofold:
1729 //
Nick Lewycky2c852542015-08-19 06:22:33 +00001730 // - If the loop only counts population, the entire loop becomes dead after
1731 // the transformation. It is a lot easier to prove a countable loop dead
1732 // than to prove a noncountable one. (In some C dialects, an infinite loop
Chandler Carruth8219a502015-08-13 00:44:29 +00001733 // isn't dead even if it computes nothing useful. In general, DCE needs
1734 // to prove a noncountable loop finite before safely delete it.)
1735 //
1736 // - If the loop also performs something else, it remains alive.
1737 // Since it is transformed to countable form, it can be aggressively
1738 // optimized by some optimizations which are in general not applicable
1739 // to a noncountable loop.
1740 //
1741 // After this step, this loop (conceptually) would look like following:
1742 // newcnt = __builtin_ctpop(x);
1743 // t = newcnt;
1744 // if (x)
1745 // do { cnt++; x &= x-1; t--) } while (t > 0);
1746 BasicBlock *Body = *(CurLoop->block_begin());
1747 {
Craig Topper9510f702018-05-04 01:04:28 +00001748 auto *LbBr = cast<BranchInst>(Body->getTerminator());
Chandler Carruth8219a502015-08-13 00:44:29 +00001749 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1750 Type *Ty = TripCnt->getType();
1751
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001752 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
Chandler Carruth8219a502015-08-13 00:44:29 +00001753
1754 Builder.SetInsertPoint(LbCond);
Chandler Carruth8219a502015-08-13 00:44:29 +00001755 Instruction *TcDec = cast<Instruction>(
Nick Lewycky1098e492015-08-19 06:25:30 +00001756 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1757 "tcdec", false, true));
Chandler Carruth8219a502015-08-13 00:44:29 +00001758
1759 TcPhi->addIncoming(TripCnt, PreHead);
1760 TcPhi->addIncoming(TcDec, Body);
1761
1762 CmpInst::Predicate Pred =
1763 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1764 LbCond->setPredicate(Pred);
1765 LbCond->setOperand(0, TcDec);
Nick Lewycky2c852542015-08-19 06:22:33 +00001766 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
Chandler Carruth8219a502015-08-13 00:44:29 +00001767 }
1768
1769 // Step 4: All the references to the original population counter outside
1770 // the loop are replaced with the NewCount -- the value returned from
1771 // __builtin_ctpop().
1772 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1773
1774 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1775 // loop. The loop would otherwise not be deleted even if it becomes empty.
1776 SE->forgetLoop(CurLoop);
1777}