Bug Summary

File:llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp
Warning:line 2520, column 5
Value stored to 'Pred' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LoopIdiomRecognize.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Transforms/Scalar -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/lib/Transforms/Scalar -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-06-13-111025-38230-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp
1//===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===//
2//
3// 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
6//
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//
13// 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//
19//===----------------------------------------------------------------------===//
20//
21// TODO List:
22//
23// Future loop memory idioms to recognize:
24// memcmp, memmove, strlen, etc.
25// Future floating point idioms to recognize in -ffast-math mode:
26// fpowi
27// Future integer operation idioms to recognize:
28// ctpop
29//
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//
34// This could recognize common matrix multiplies and dot product idioms and
35// replace them with calls to BLAS (if linked in??).
36//
37//===----------------------------------------------------------------------===//
38
39#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
40#include "llvm/ADT/APInt.h"
41#include "llvm/ADT/ArrayRef.h"
42#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/MapVector.h"
44#include "llvm/ADT/SetVector.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/ADT/Statistic.h"
48#include "llvm/ADT/StringRef.h"
49#include "llvm/Analysis/AliasAnalysis.h"
50#include "llvm/Analysis/CmpInstAnalysis.h"
51#include "llvm/Analysis/LoopAccessAnalysis.h"
52#include "llvm/Analysis/LoopInfo.h"
53#include "llvm/Analysis/LoopPass.h"
54#include "llvm/Analysis/MemoryLocation.h"
55#include "llvm/Analysis/MemorySSA.h"
56#include "llvm/Analysis/MemorySSAUpdater.h"
57#include "llvm/Analysis/MustExecute.h"
58#include "llvm/Analysis/OptimizationRemarkEmitter.h"
59#include "llvm/Analysis/ScalarEvolution.h"
60#include "llvm/Analysis/ScalarEvolutionExpressions.h"
61#include "llvm/Analysis/TargetLibraryInfo.h"
62#include "llvm/Analysis/TargetTransformInfo.h"
63#include "llvm/Analysis/ValueTracking.h"
64#include "llvm/IR/Attributes.h"
65#include "llvm/IR/BasicBlock.h"
66#include "llvm/IR/Constant.h"
67#include "llvm/IR/Constants.h"
68#include "llvm/IR/DataLayout.h"
69#include "llvm/IR/DebugLoc.h"
70#include "llvm/IR/DerivedTypes.h"
71#include "llvm/IR/Dominators.h"
72#include "llvm/IR/GlobalValue.h"
73#include "llvm/IR/GlobalVariable.h"
74#include "llvm/IR/IRBuilder.h"
75#include "llvm/IR/InstrTypes.h"
76#include "llvm/IR/Instruction.h"
77#include "llvm/IR/Instructions.h"
78#include "llvm/IR/IntrinsicInst.h"
79#include "llvm/IR/Intrinsics.h"
80#include "llvm/IR/LLVMContext.h"
81#include "llvm/IR/Module.h"
82#include "llvm/IR/PassManager.h"
83#include "llvm/IR/PatternMatch.h"
84#include "llvm/IR/Type.h"
85#include "llvm/IR/User.h"
86#include "llvm/IR/Value.h"
87#include "llvm/IR/ValueHandle.h"
88#include "llvm/InitializePasses.h"
89#include "llvm/Pass.h"
90#include "llvm/Support/Casting.h"
91#include "llvm/Support/CommandLine.h"
92#include "llvm/Support/Debug.h"
93#include "llvm/Support/InstructionCost.h"
94#include "llvm/Support/raw_ostream.h"
95#include "llvm/Transforms/Scalar.h"
96#include "llvm/Transforms/Utils/BuildLibCalls.h"
97#include "llvm/Transforms/Utils/Local.h"
98#include "llvm/Transforms/Utils/LoopUtils.h"
99#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
100#include <algorithm>
101#include <cassert>
102#include <cstdint>
103#include <utility>
104#include <vector>
105
106using namespace llvm;
107
108#define DEBUG_TYPE"loop-idiom" "loop-idiom"
109
110STATISTIC(NumMemSet, "Number of memset's formed from loop stores")static llvm::Statistic NumMemSet = {"loop-idiom", "NumMemSet"
, "Number of memset's formed from loop stores"}
;
111STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores")static llvm::Statistic NumMemCpy = {"loop-idiom", "NumMemCpy"
, "Number of memcpy's formed from loop load+stores"}
;
112STATISTIC(static llvm::Statistic NumShiftUntilBitTest = {"loop-idiom", "NumShiftUntilBitTest"
, "Number of uncountable loops recognized as 'shift until bitttest' idiom"
}
113 NumShiftUntilBitTest,static llvm::Statistic NumShiftUntilBitTest = {"loop-idiom", "NumShiftUntilBitTest"
, "Number of uncountable loops recognized as 'shift until bitttest' idiom"
}
114 "Number of uncountable loops recognized as 'shift until bitttest' idiom")static llvm::Statistic NumShiftUntilBitTest = {"loop-idiom", "NumShiftUntilBitTest"
, "Number of uncountable loops recognized as 'shift until bitttest' idiom"
}
;
115STATISTIC(NumShiftUntilZero,static llvm::Statistic NumShiftUntilZero = {"loop-idiom", "NumShiftUntilZero"
, "Number of uncountable loops recognized as 'shift until zero' idiom"
}
116 "Number of uncountable loops recognized as 'shift until zero' idiom")static llvm::Statistic NumShiftUntilZero = {"loop-idiom", "NumShiftUntilZero"
, "Number of uncountable loops recognized as 'shift until zero' idiom"
}
;
117
118bool DisableLIRP::All;
119static cl::opt<bool, true>
120 DisableLIRPAll("disable-" DEBUG_TYPE"loop-idiom" "-all",
121 cl::desc("Options to disable Loop Idiom Recognize Pass."),
122 cl::location(DisableLIRP::All), cl::init(false),
123 cl::ReallyHidden);
124
125bool DisableLIRP::Memset;
126static cl::opt<bool, true>
127 DisableLIRPMemset("disable-" DEBUG_TYPE"loop-idiom" "-memset",
128 cl::desc("Proceed with loop idiom recognize pass, but do "
129 "not convert loop(s) to memset."),
130 cl::location(DisableLIRP::Memset), cl::init(false),
131 cl::ReallyHidden);
132
133bool DisableLIRP::Memcpy;
134static cl::opt<bool, true>
135 DisableLIRPMemcpy("disable-" DEBUG_TYPE"loop-idiom" "-memcpy",
136 cl::desc("Proceed with loop idiom recognize pass, but do "
137 "not convert loop(s) to memcpy."),
138 cl::location(DisableLIRP::Memcpy), cl::init(false),
139 cl::ReallyHidden);
140
141static cl::opt<bool> UseLIRCodeSizeHeurs(
142 "use-lir-code-size-heurs",
143 cl::desc("Use loop idiom recognition code size heuristics when compiling"
144 "with -Os/-Oz"),
145 cl::init(true), cl::Hidden);
146
147namespace {
148
149class LoopIdiomRecognize {
150 Loop *CurLoop = nullptr;
151 AliasAnalysis *AA;
152 DominatorTree *DT;
153 LoopInfo *LI;
154 ScalarEvolution *SE;
155 TargetLibraryInfo *TLI;
156 const TargetTransformInfo *TTI;
157 const DataLayout *DL;
158 OptimizationRemarkEmitter &ORE;
159 bool ApplyCodeSizeHeuristics;
160 std::unique_ptr<MemorySSAUpdater> MSSAU;
161
162public:
163 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
164 LoopInfo *LI, ScalarEvolution *SE,
165 TargetLibraryInfo *TLI,
166 const TargetTransformInfo *TTI, MemorySSA *MSSA,
167 const DataLayout *DL,
168 OptimizationRemarkEmitter &ORE)
169 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) {
170 if (MSSA)
171 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
172 }
173
174 bool runOnLoop(Loop *L);
175
176private:
177 using StoreList = SmallVector<StoreInst *, 8>;
178 using StoreListMap = MapVector<Value *, StoreList>;
179
180 StoreListMap StoreRefsForMemset;
181 StoreListMap StoreRefsForMemsetPattern;
182 StoreList StoreRefsForMemcpy;
183 bool HasMemset;
184 bool HasMemsetPattern;
185 bool HasMemcpy;
186
187 /// Return code for isLegalStore()
188 enum LegalStoreKind {
189 None = 0,
190 Memset,
191 MemsetPattern,
192 Memcpy,
193 UnorderedAtomicMemcpy,
194 DontUse // Dummy retval never to be used. Allows catching errors in retval
195 // handling.
196 };
197
198 /// \name Countable Loop Idiom Handling
199 /// @{
200
201 bool runOnCountableLoop();
202 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
203 SmallVectorImpl<BasicBlock *> &ExitBlocks);
204
205 void collectStores(BasicBlock *BB);
206 LegalStoreKind isLegalStore(StoreInst *SI);
207 enum class ForMemset { No, Yes };
208 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
209 ForMemset For);
210
211 template <typename MemInst>
212 bool processLoopMemIntrinsic(
213 BasicBlock *BB,
214 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
215 const SCEV *BECount);
216 bool processLoopMemCpy(MemCpyInst *MCI, const SCEV *BECount);
217 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
218
219 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
220 MaybeAlign StoreAlignment, Value *StoredVal,
221 Instruction *TheStore,
222 SmallPtrSetImpl<Instruction *> &Stores,
223 const SCEVAddRecExpr *Ev, const SCEV *BECount,
224 bool NegStride, bool IsLoopMemset = false);
225 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
226 bool processLoopStoreOfLoopLoad(Value *DestPtr, Value *SourcePtr,
227 unsigned StoreSize, MaybeAlign StoreAlign,
228 MaybeAlign LoadAlign, Instruction *TheStore,
229 Instruction *TheLoad,
230 const SCEVAddRecExpr *StoreEv,
231 const SCEVAddRecExpr *LoadEv,
232 const SCEV *BECount);
233 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
234 bool IsLoopMemset = false);
235
236 /// @}
237 /// \name Noncountable Loop Idiom Handling
238 /// @{
239
240 bool runOnNoncountableLoop();
241
242 bool recognizePopcount();
243 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
244 PHINode *CntPhi, Value *Var);
245 bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz
246 void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB,
247 Instruction *CntInst, PHINode *CntPhi,
248 Value *Var, Instruction *DefX,
249 const DebugLoc &DL, bool ZeroCheck,
250 bool IsCntPhiUsedOutsideLoop);
251
252 bool recognizeShiftUntilBitTest();
253 bool recognizeShiftUntilZero();
254
255 /// @}
256};
257
258class LoopIdiomRecognizeLegacyPass : public LoopPass {
259public:
260 static char ID;
261
262 explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
263 initializeLoopIdiomRecognizeLegacyPassPass(
264 *PassRegistry::getPassRegistry());
265 }
266
267 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
268 if (DisableLIRP::All)
269 return false;
270
271 if (skipLoop(L))
272 return false;
273
274 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
275 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
276 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
277 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
278 TargetLibraryInfo *TLI =
279 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
280 *L->getHeader()->getParent());
281 const TargetTransformInfo *TTI =
282 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
283 *L->getHeader()->getParent());
284 const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
285 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
286 MemorySSA *MSSA = nullptr;
287 if (MSSAAnalysis)
288 MSSA = &MSSAAnalysis->getMSSA();
289
290 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
291 // pass. Function analyses need to be preserved across loop transformations
292 // but ORE cannot be preserved (see comment before the pass definition).
293 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
294
295 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, MSSA, DL, ORE);
296 return LIR.runOnLoop(L);
297 }
298
299 /// This transformation requires natural loop information & requires that
300 /// loop preheaders be inserted into the CFG.
301 void getAnalysisUsage(AnalysisUsage &AU) const override {
302 AU.addRequired<TargetLibraryInfoWrapperPass>();
303 AU.addRequired<TargetTransformInfoWrapperPass>();
304 AU.addPreserved<MemorySSAWrapperPass>();
305 getLoopAnalysisUsage(AU);
306 }
307};
308
309} // end anonymous namespace
310
311char LoopIdiomRecognizeLegacyPass::ID = 0;
312
313PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
314 LoopStandardAnalysisResults &AR,
315 LPMUpdater &) {
316 if (DisableLIRP::All)
317 return PreservedAnalyses::all();
318
319 const auto *DL = &L.getHeader()->getModule()->getDataLayout();
320
321 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
322 // pass. Function analyses need to be preserved across loop transformations
323 // but ORE cannot be preserved (see comment before the pass definition).
324 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
325
326 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI,
327 AR.MSSA, DL, ORE);
328 if (!LIR.runOnLoop(&L))
329 return PreservedAnalyses::all();
330
331 auto PA = getLoopPassPreservedAnalyses();
332 if (AR.MSSA)
333 PA.preserve<MemorySSAAnalysis>();
334 return PA;
335}
336
337INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",static void *initializeLoopIdiomRecognizeLegacyPassPassOnce(PassRegistry
&Registry) {
338 "Recognize loop idioms", false, false)static void *initializeLoopIdiomRecognizeLegacyPassPassOnce(PassRegistry
&Registry) {
339INITIALIZE_PASS_DEPENDENCY(LoopPass)initializeLoopPassPass(Registry);
340INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
341INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
342INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",PassInfo *PI = new PassInfo( "Recognize loop idioms", "loop-idiom"
, &LoopIdiomRecognizeLegacyPass::ID, PassInfo::NormalCtor_t
(callDefaultCtor<LoopIdiomRecognizeLegacyPass>), false,
false); Registry.registerPass(*PI, true); return PI; } static
llvm::once_flag InitializeLoopIdiomRecognizeLegacyPassPassFlag
; void llvm::initializeLoopIdiomRecognizeLegacyPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeLoopIdiomRecognizeLegacyPassPassFlag
, initializeLoopIdiomRecognizeLegacyPassPassOnce, std::ref(Registry
)); }
343 "Recognize loop idioms", false, false)PassInfo *PI = new PassInfo( "Recognize loop idioms", "loop-idiom"
, &LoopIdiomRecognizeLegacyPass::ID, PassInfo::NormalCtor_t
(callDefaultCtor<LoopIdiomRecognizeLegacyPass>), false,
false); Registry.registerPass(*PI, true); return PI; } static
llvm::once_flag InitializeLoopIdiomRecognizeLegacyPassPassFlag
; void llvm::initializeLoopIdiomRecognizeLegacyPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeLoopIdiomRecognizeLegacyPassPassFlag
, initializeLoopIdiomRecognizeLegacyPassPassOnce, std::ref(Registry
)); }
344
345Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
346
347static void deleteDeadInstruction(Instruction *I) {
348 I->replaceAllUsesWith(UndefValue::get(I->getType()));
349 I->eraseFromParent();
350}
351
352//===----------------------------------------------------------------------===//
353//
354// Implementation of LoopIdiomRecognize
355//
356//===----------------------------------------------------------------------===//
357
358bool LoopIdiomRecognize::runOnLoop(Loop *L) {
359 CurLoop = L;
360 // If the loop could not be converted to canonical form, it must have an
361 // indirectbr in it, just give up.
362 if (!L->getLoopPreheader())
363 return false;
364
365 // Disable loop idiom recognition if the function's name is a common idiom.
366 StringRef Name = L->getHeader()->getParent()->getName();
367 if (Name == "memset" || Name == "memcpy")
368 return false;
369
370 // Determine if code size heuristics need to be applied.
371 ApplyCodeSizeHeuristics =
372 L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs;
373
374 HasMemset = TLI->has(LibFunc_memset);
375 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
376 HasMemcpy = TLI->has(LibFunc_memcpy);
377
378 if (HasMemset || HasMemsetPattern || HasMemcpy)
379 if (SE->hasLoopInvariantBackedgeTakenCount(L))
380 return runOnCountableLoop();
381
382 return runOnNoncountableLoop();
383}
384
385bool LoopIdiomRecognize::runOnCountableLoop() {
386 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
387 assert(!isa<SCEVCouldNotCompute>(BECount) &&(static_cast <bool> (!isa<SCEVCouldNotCompute>(BECount
) && "runOnCountableLoop() called on a loop without a predictable"
"backedge-taken count") ? void (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(BECount) && \"runOnCountableLoop() called on a loop without a predictable\" \"backedge-taken count\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 389, __extension__ __PRETTY_FUNCTION__))
388 "runOnCountableLoop() called on a loop without a predictable"(static_cast <bool> (!isa<SCEVCouldNotCompute>(BECount
) && "runOnCountableLoop() called on a loop without a predictable"
"backedge-taken count") ? void (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(BECount) && \"runOnCountableLoop() called on a loop without a predictable\" \"backedge-taken count\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 389, __extension__ __PRETTY_FUNCTION__))
389 "backedge-taken count")(static_cast <bool> (!isa<SCEVCouldNotCompute>(BECount
) && "runOnCountableLoop() called on a loop without a predictable"
"backedge-taken count") ? void (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(BECount) && \"runOnCountableLoop() called on a loop without a predictable\" \"backedge-taken count\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 389, __extension__ __PRETTY_FUNCTION__))
;
390
391 // If this loop executes exactly one time, then it should be peeled, not
392 // optimized by this pass.
393 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
394 if (BECst->getAPInt() == 0)
395 return false;
396
397 SmallVector<BasicBlock *, 8> ExitBlocks;
398 CurLoop->getUniqueExitBlocks(ExitBlocks);
399
400 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Scanning: F["
<< CurLoop->getHeader()->getParent()->getName
() << "] Countable Loop %" << CurLoop->getHeader
()->getName() << "\n"; } } while (false)
401 << CurLoop->getHeader()->getParent()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Scanning: F["
<< CurLoop->getHeader()->getParent()->getName
() << "] Countable Loop %" << CurLoop->getHeader
()->getName() << "\n"; } } while (false)
402 << "] Countable Loop %" << CurLoop->getHeader()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Scanning: F["
<< CurLoop->getHeader()->getParent()->getName
() << "] Countable Loop %" << CurLoop->getHeader
()->getName() << "\n"; } } while (false)
403 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Scanning: F["
<< CurLoop->getHeader()->getParent()->getName
() << "] Countable Loop %" << CurLoop->getHeader
()->getName() << "\n"; } } while (false)
;
404
405 // The following transforms hoist stores/memsets into the loop pre-header.
406 // Give up if the loop has instructions that may throw.
407 SimpleLoopSafetyInfo SafetyInfo;
408 SafetyInfo.computeLoopSafetyInfo(CurLoop);
409 if (SafetyInfo.anyBlockMayThrow())
410 return false;
411
412 bool MadeChange = false;
413
414 // Scan all the blocks in the loop that are not in subloops.
415 for (auto *BB : CurLoop->getBlocks()) {
416 // Ignore blocks in subloops.
417 if (LI->getLoopFor(BB) != CurLoop)
418 continue;
419
420 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
421 }
422 return MadeChange;
423}
424
425static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
426 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
427 return ConstStride->getAPInt();
428}
429
430/// getMemSetPatternValue - If a strided store of the specified value is safe to
431/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
432/// be passed in. Otherwise, return null.
433///
434/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
435/// just replicate their input array and then pass on to memset_pattern16.
436static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
437 // FIXME: This could check for UndefValue because it can be merged into any
438 // other valid pattern.
439
440 // If the value isn't a constant, we can't promote it to being in a constant
441 // array. We could theoretically do a store to an alloca or something, but
442 // that doesn't seem worthwhile.
443 Constant *C = dyn_cast<Constant>(V);
444 if (!C)
445 return nullptr;
446
447 // Only handle simple values that are a power of two bytes in size.
448 uint64_t Size = DL->getTypeSizeInBits(V->getType());
449 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
450 return nullptr;
451
452 // Don't care enough about darwin/ppc to implement this.
453 if (DL->isBigEndian())
454 return nullptr;
455
456 // Convert to size in bytes.
457 Size /= 8;
458
459 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
460 // if the top and bottom are the same (e.g. for vectors and large integers).
461 if (Size > 16)
462 return nullptr;
463
464 // If the constant is exactly 16 bytes, just use it.
465 if (Size == 16)
466 return C;
467
468 // Otherwise, we'll use an array of the constants.
469 unsigned ArraySize = 16 / Size;
470 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
471 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
472}
473
474LoopIdiomRecognize::LegalStoreKind
475LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
476 // Don't touch volatile stores.
477 if (SI->isVolatile())
478 return LegalStoreKind::None;
479 // We only want simple or unordered-atomic stores.
480 if (!SI->isUnordered())
481 return LegalStoreKind::None;
482
483 // Avoid merging nontemporal stores.
484 if (SI->getMetadata(LLVMContext::MD_nontemporal))
485 return LegalStoreKind::None;
486
487 Value *StoredVal = SI->getValueOperand();
488 Value *StorePtr = SI->getPointerOperand();
489
490 // Don't convert stores of non-integral pointer types to memsets (which stores
491 // integers).
492 if (DL->isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
493 return LegalStoreKind::None;
494
495 // Reject stores that are so large that they overflow an unsigned.
496 // When storing out scalable vectors we bail out for now, since the code
497 // below currently only works for constant strides.
498 TypeSize SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
499 if (SizeInBits.isScalable() || (SizeInBits.getFixedSize() & 7) ||
500 (SizeInBits.getFixedSize() >> 32) != 0)
501 return LegalStoreKind::None;
502
503 // See if the pointer expression is an AddRec like {base,+,1} on the current
504 // loop, which indicates a strided store. If we have something else, it's a
505 // random store we can't handle.
506 const SCEVAddRecExpr *StoreEv =
507 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
508 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
509 return LegalStoreKind::None;
510
511 // Check to see if we have a constant stride.
512 if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
513 return LegalStoreKind::None;
514
515 // See if the store can be turned into a memset.
516
517 // If the stored value is a byte-wise value (like i32 -1), then it may be
518 // turned into a memset of i8 -1, assuming that all the consecutive bytes
519 // are stored. A store of i32 0x01020304 can never be turned into a memset,
520 // but it can be turned into memset_pattern if the target supports it.
521 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
522
523 // Note: memset and memset_pattern on unordered-atomic is yet not supported
524 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
525
526 // If we're allowed to form a memset, and the stored value would be
527 // acceptable for memset, use it.
528 if (!UnorderedAtomic && HasMemset && SplatValue && !DisableLIRP::Memset &&
529 // Verify that the stored value is loop invariant. If not, we can't
530 // promote the memset.
531 CurLoop->isLoopInvariant(SplatValue)) {
532 // It looks like we can use SplatValue.
533 return LegalStoreKind::Memset;
534 }
535 if (!UnorderedAtomic && HasMemsetPattern && !DisableLIRP::Memset &&
536 // Don't create memset_pattern16s with address spaces.
537 StorePtr->getType()->getPointerAddressSpace() == 0 &&
538 getMemSetPatternValue(StoredVal, DL)) {
539 // It looks like we can use PatternValue!
540 return LegalStoreKind::MemsetPattern;
541 }
542
543 // Otherwise, see if the store can be turned into a memcpy.
544 if (HasMemcpy && !DisableLIRP::Memcpy) {
545 // Check to see if the stride matches the size of the store. If so, then we
546 // know that every byte is touched in the loop.
547 APInt Stride = getStoreStride(StoreEv);
548 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
549 if (StoreSize != Stride && StoreSize != -Stride)
550 return LegalStoreKind::None;
551
552 // The store must be feeding a non-volatile load.
553 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
554
555 // Only allow non-volatile loads
556 if (!LI || LI->isVolatile())
557 return LegalStoreKind::None;
558 // Only allow simple or unordered-atomic loads
559 if (!LI->isUnordered())
560 return LegalStoreKind::None;
561
562 // See if the pointer expression is an AddRec like {base,+,1} on the current
563 // loop, which indicates a strided load. If we have something else, it's a
564 // random load we can't handle.
565 const SCEVAddRecExpr *LoadEv =
566 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
567 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
568 return LegalStoreKind::None;
569
570 // The store and load must share the same stride.
571 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
572 return LegalStoreKind::None;
573
574 // Success. This store can be converted into a memcpy.
575 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
576 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
577 : LegalStoreKind::Memcpy;
578 }
579 // This store can't be transformed into a memset/memcpy.
580 return LegalStoreKind::None;
581}
582
583void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
584 StoreRefsForMemset.clear();
585 StoreRefsForMemsetPattern.clear();
586 StoreRefsForMemcpy.clear();
587 for (Instruction &I : *BB) {
588 StoreInst *SI = dyn_cast<StoreInst>(&I);
589 if (!SI)
590 continue;
591
592 // Make sure this is a strided store with a constant stride.
593 switch (isLegalStore(SI)) {
594 case LegalStoreKind::None:
595 // Nothing to do
596 break;
597 case LegalStoreKind::Memset: {
598 // Find the base pointer.
599 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
600 StoreRefsForMemset[Ptr].push_back(SI);
601 } break;
602 case LegalStoreKind::MemsetPattern: {
603 // Find the base pointer.
604 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
605 StoreRefsForMemsetPattern[Ptr].push_back(SI);
606 } break;
607 case LegalStoreKind::Memcpy:
608 case LegalStoreKind::UnorderedAtomicMemcpy:
609 StoreRefsForMemcpy.push_back(SI);
610 break;
611 default:
612 assert(false && "unhandled return value")(static_cast <bool> (false && "unhandled return value"
) ? void (0) : __assert_fail ("false && \"unhandled return value\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 612, __extension__ __PRETTY_FUNCTION__))
;
613 break;
614 }
615 }
616}
617
618/// runOnLoopBlock - Process the specified block, which lives in a counted loop
619/// with the specified backedge count. This block is known to be in the current
620/// loop and not in any subloops.
621bool LoopIdiomRecognize::runOnLoopBlock(
622 BasicBlock *BB, const SCEV *BECount,
623 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
624 // We can only promote stores in this block if they are unconditionally
625 // executed in the loop. For a block to be unconditionally executed, it has
626 // to dominate all the exit blocks of the loop. Verify this now.
627 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
628 if (!DT->dominates(BB, ExitBlocks[i]))
629 return false;
630
631 bool MadeChange = false;
632 // Look for store instructions, which may be optimized to memset/memcpy.
633 collectStores(BB);
634
635 // Look for a single store or sets of stores with a common base, which can be
636 // optimized into a memset (memset_pattern). The latter most commonly happens
637 // with structs and handunrolled loops.
638 for (auto &SL : StoreRefsForMemset)
639 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
640
641 for (auto &SL : StoreRefsForMemsetPattern)
642 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
643
644 // Optimize the store into a memcpy, if it feeds an similarly strided load.
645 for (auto &SI : StoreRefsForMemcpy)
646 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
647
648 MadeChange |= processLoopMemIntrinsic<MemCpyInst>(
649 BB, &LoopIdiomRecognize::processLoopMemCpy, BECount);
650 MadeChange |= processLoopMemIntrinsic<MemSetInst>(
651 BB, &LoopIdiomRecognize::processLoopMemSet, BECount);
652
653 return MadeChange;
654}
655
656/// See if this store(s) can be promoted to a memset.
657bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
658 const SCEV *BECount, ForMemset For) {
659 // Try to find consecutive stores that can be transformed into memsets.
660 SetVector<StoreInst *> Heads, Tails;
661 SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
662
663 // Do a quadratic search on all of the given stores and find
664 // all of the pairs of stores that follow each other.
665 SmallVector<unsigned, 16> IndexQueue;
666 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
667 assert(SL[i]->isSimple() && "Expected only non-volatile stores.")(static_cast <bool> (SL[i]->isSimple() && "Expected only non-volatile stores."
) ? void (0) : __assert_fail ("SL[i]->isSimple() && \"Expected only non-volatile stores.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 667, __extension__ __PRETTY_FUNCTION__))
;
668
669 Value *FirstStoredVal = SL[i]->getValueOperand();
670 Value *FirstStorePtr = SL[i]->getPointerOperand();
671 const SCEVAddRecExpr *FirstStoreEv =
672 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
673 APInt FirstStride = getStoreStride(FirstStoreEv);
674 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
675
676 // See if we can optimize just this store in isolation.
677 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
678 Heads.insert(SL[i]);
679 continue;
680 }
681
682 Value *FirstSplatValue = nullptr;
683 Constant *FirstPatternValue = nullptr;
684
685 if (For == ForMemset::Yes)
686 FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL);
687 else
688 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
689
690 assert((FirstSplatValue || FirstPatternValue) &&(static_cast <bool> ((FirstSplatValue || FirstPatternValue
) && "Expected either splat value or pattern value.")
? void (0) : __assert_fail ("(FirstSplatValue || FirstPatternValue) && \"Expected either splat value or pattern value.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 691, __extension__ __PRETTY_FUNCTION__))
691 "Expected either splat value or pattern value.")(static_cast <bool> ((FirstSplatValue || FirstPatternValue
) && "Expected either splat value or pattern value.")
? void (0) : __assert_fail ("(FirstSplatValue || FirstPatternValue) && \"Expected either splat value or pattern value.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 691, __extension__ __PRETTY_FUNCTION__))
;
692
693 IndexQueue.clear();
694 // If a store has multiple consecutive store candidates, search Stores
695 // array according to the sequence: from i+1 to e, then from i-1 to 0.
696 // This is because usually pairing with immediate succeeding or preceding
697 // candidate create the best chance to find memset opportunity.
698 unsigned j = 0;
699 for (j = i + 1; j < e; ++j)
700 IndexQueue.push_back(j);
701 for (j = i; j > 0; --j)
702 IndexQueue.push_back(j - 1);
703
704 for (auto &k : IndexQueue) {
705 assert(SL[k]->isSimple() && "Expected only non-volatile stores.")(static_cast <bool> (SL[k]->isSimple() && "Expected only non-volatile stores."
) ? void (0) : __assert_fail ("SL[k]->isSimple() && \"Expected only non-volatile stores.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 705, __extension__ __PRETTY_FUNCTION__))
;
706 Value *SecondStorePtr = SL[k]->getPointerOperand();
707 const SCEVAddRecExpr *SecondStoreEv =
708 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
709 APInt SecondStride = getStoreStride(SecondStoreEv);
710
711 if (FirstStride != SecondStride)
712 continue;
713
714 Value *SecondStoredVal = SL[k]->getValueOperand();
715 Value *SecondSplatValue = nullptr;
716 Constant *SecondPatternValue = nullptr;
717
718 if (For == ForMemset::Yes)
719 SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL);
720 else
721 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
722
723 assert((SecondSplatValue || SecondPatternValue) &&(static_cast <bool> ((SecondSplatValue || SecondPatternValue
) && "Expected either splat value or pattern value.")
? void (0) : __assert_fail ("(SecondSplatValue || SecondPatternValue) && \"Expected either splat value or pattern value.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 724, __extension__ __PRETTY_FUNCTION__))
724 "Expected either splat value or pattern value.")(static_cast <bool> ((SecondSplatValue || SecondPatternValue
) && "Expected either splat value or pattern value.")
? void (0) : __assert_fail ("(SecondSplatValue || SecondPatternValue) && \"Expected either splat value or pattern value.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 724, __extension__ __PRETTY_FUNCTION__))
;
725
726 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
727 if (For == ForMemset::Yes) {
728 if (isa<UndefValue>(FirstSplatValue))
729 FirstSplatValue = SecondSplatValue;
730 if (FirstSplatValue != SecondSplatValue)
731 continue;
732 } else {
733 if (isa<UndefValue>(FirstPatternValue))
734 FirstPatternValue = SecondPatternValue;
735 if (FirstPatternValue != SecondPatternValue)
736 continue;
737 }
738 Tails.insert(SL[k]);
739 Heads.insert(SL[i]);
740 ConsecutiveChain[SL[i]] = SL[k];
741 break;
742 }
743 }
744 }
745
746 // We may run into multiple chains that merge into a single chain. We mark the
747 // stores that we transformed so that we don't visit the same store twice.
748 SmallPtrSet<Value *, 16> TransformedStores;
749 bool Changed = false;
750
751 // For stores that start but don't end a link in the chain:
752 for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
753 it != e; ++it) {
754 if (Tails.count(*it))
755 continue;
756
757 // We found a store instr that starts a chain. Now follow the chain and try
758 // to transform it.
759 SmallPtrSet<Instruction *, 8> AdjacentStores;
760 StoreInst *I = *it;
761
762 StoreInst *HeadStore = I;
763 unsigned StoreSize = 0;
764
765 // Collect the chain into a list.
766 while (Tails.count(I) || Heads.count(I)) {
767 if (TransformedStores.count(I))
768 break;
769 AdjacentStores.insert(I);
770
771 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
772 // Move to the next value in the chain.
773 I = ConsecutiveChain[I];
774 }
775
776 Value *StoredVal = HeadStore->getValueOperand();
777 Value *StorePtr = HeadStore->getPointerOperand();
778 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
779 APInt Stride = getStoreStride(StoreEv);
780
781 // Check to see if the stride matches the size of the stores. If so, then
782 // we know that every byte is touched in the loop.
783 if (StoreSize != Stride && StoreSize != -Stride)
784 continue;
785
786 bool NegStride = StoreSize == -Stride;
787
788 if (processLoopStridedStore(StorePtr, StoreSize,
789 MaybeAlign(HeadStore->getAlignment()),
790 StoredVal, HeadStore, AdjacentStores, StoreEv,
791 BECount, NegStride)) {
792 TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
793 Changed = true;
794 }
795 }
796
797 return Changed;
798}
799
800/// processLoopMemIntrinsic - Template function for calling different processor
801/// functions based on mem instrinsic type.
802template <typename MemInst>
803bool LoopIdiomRecognize::processLoopMemIntrinsic(
804 BasicBlock *BB,
805 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
806 const SCEV *BECount) {
807 bool MadeChange = false;
808 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
809 Instruction *Inst = &*I++;
810 // Look for memory instructions, which may be optimized to a larger one.
811 if (MemInst *MI = dyn_cast<MemInst>(Inst)) {
812 WeakTrackingVH InstPtr(&*I);
813 if (!(this->*Processor)(MI, BECount))
814 continue;
815 MadeChange = true;
816
817 // If processing the instruction invalidated our iterator, start over from
818 // the top of the block.
819 if (!InstPtr)
820 I = BB->begin();
821 }
822 }
823 return MadeChange;
824}
825
826/// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy
827bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI,
828 const SCEV *BECount) {
829 // We can only handle non-volatile memcpys with a constant size.
830 if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength()))
831 return false;
832
833 // If we're not allowed to hack on memcpy, we fail.
834 if (!HasMemcpy || DisableLIRP::Memcpy)
835 return false;
836
837 Value *Dest = MCI->getDest();
838 Value *Source = MCI->getSource();
839 if (!Dest || !Source)
840 return false;
841
842 // See if the load and store pointer expressions are AddRec like {base,+,1} on
843 // the current loop, which indicates a strided load and store. If we have
844 // something else, it's a random load or store we can't handle.
845 const SCEVAddRecExpr *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Dest));
846 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
847 return false;
848 const SCEVAddRecExpr *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Source));
849 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
850 return false;
851
852 // Reject memcpys that are so large that they overflow an unsigned.
853 uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue();
854 if ((SizeInBytes >> 32) != 0)
855 return false;
856
857 // Check if the stride matches the size of the memcpy. If so, then we know
858 // that every byte is touched in the loop.
859 const SCEVConstant *StoreStride =
860 dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
861 const SCEVConstant *LoadStride =
862 dyn_cast<SCEVConstant>(LoadEv->getOperand(1));
863 if (!StoreStride || !LoadStride)
864 return false;
865
866 APInt StoreStrideValue = StoreStride->getAPInt();
867 APInt LoadStrideValue = LoadStride->getAPInt();
868 // Huge stride value - give up
869 if (StoreStrideValue.getBitWidth() > 64 || LoadStrideValue.getBitWidth() > 64)
870 return false;
871
872 if (SizeInBytes != StoreStrideValue && SizeInBytes != -StoreStrideValue) {
873 ORE.emit([&]() {
874 return OptimizationRemarkMissed(DEBUG_TYPE"loop-idiom", "SizeStrideUnequal", MCI)
875 << ore::NV("Inst", "memcpy") << " in "
876 << ore::NV("Function", MCI->getFunction())
877 << " function will not be hoised: "
878 << ore::NV("Reason", "memcpy size is not equal to stride");
879 });
880 return false;
881 }
882
883 int64_t StoreStrideInt = StoreStrideValue.getSExtValue();
884 int64_t LoadStrideInt = LoadStrideValue.getSExtValue();
885 // Check if the load stride matches the store stride.
886 if (StoreStrideInt != LoadStrideInt)
887 return false;
888
889 return processLoopStoreOfLoopLoad(Dest, Source, (unsigned)SizeInBytes,
890 MCI->getDestAlign(), MCI->getSourceAlign(),
891 MCI, MCI, StoreEv, LoadEv, BECount);
892}
893
894/// processLoopMemSet - See if this memset can be promoted to a large memset.
895bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
896 const SCEV *BECount) {
897 // We can only handle non-volatile memsets with a constant size.
898 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
899 return false;
900
901 // If we're not allowed to hack on memset, we fail.
902 if (!HasMemset || DisableLIRP::Memset)
903 return false;
904
905 Value *Pointer = MSI->getDest();
906
907 // See if the pointer expression is an AddRec like {base,+,1} on the current
908 // loop, which indicates a strided store. If we have something else, it's a
909 // random store we can't handle.
910 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
911 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
912 return false;
913
914 // Reject memsets that are so large that they overflow an unsigned.
915 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
916 if ((SizeInBytes >> 32) != 0)
917 return false;
918
919 // Check to see if the stride matches the size of the memset. If so, then we
920 // know that every byte is touched in the loop.
921 const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
922 if (!ConstStride)
923 return false;
924
925 APInt Stride = ConstStride->getAPInt();
926 if (SizeInBytes != Stride && SizeInBytes != -Stride)
927 return false;
928
929 // Verify that the memset value is loop invariant. If not, we can't promote
930 // the memset.
931 Value *SplatValue = MSI->getValue();
932 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
933 return false;
934
935 SmallPtrSet<Instruction *, 1> MSIs;
936 MSIs.insert(MSI);
937 bool NegStride = SizeInBytes == -Stride;
938 return processLoopStridedStore(
939 Pointer, (unsigned)SizeInBytes, MaybeAlign(MSI->getDestAlignment()),
940 SplatValue, MSI, MSIs, Ev, BECount, NegStride, /*IsLoopMemset=*/true);
941}
942
943/// mayLoopAccessLocation - Return true if the specified loop might access the
944/// specified pointer location, which is a loop-strided access. The 'Access'
945/// argument specifies what the verboten forms of access are (read or write).
946static bool
947mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
948 const SCEV *BECount, unsigned StoreSize,
949 AliasAnalysis &AA,
950 SmallPtrSetImpl<Instruction *> &IgnoredStores) {
951 // Get the location that may be stored across the loop. Since the access is
952 // strided positively through memory, we say that the modified location starts
953 // at the pointer and has infinite size.
954 LocationSize AccessSize = LocationSize::afterPointer();
955
956 // If the loop iterates a fixed number of times, we can refine the access size
957 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
958 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
959 AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) *
960 StoreSize);
961
962 // TODO: For this to be really effective, we have to dive into the pointer
963 // operand in the store. Store to &A[i] of 100 will always return may alias
964 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
965 // which will then no-alias a store to &A[100].
966 MemoryLocation StoreLoc(Ptr, AccessSize);
967
968 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
969 ++BI)
970 for (Instruction &I : **BI)
971 if (IgnoredStores.count(&I) == 0 &&
972 isModOrRefSet(
973 intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access)))
974 return true;
975
976 return false;
977}
978
979// If we have a negative stride, Start refers to the end of the memory location
980// we're trying to memset. Therefore, we need to recompute the base pointer,
981// which is just Start - BECount*Size.
982static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
983 Type *IntPtr, unsigned StoreSize,
984 ScalarEvolution *SE) {
985 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
986 if (StoreSize != 1)
987 Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
988 SCEV::FlagNUW);
989 return SE->getMinusSCEV(Start, Index);
990}
991
992/// Compute the number of bytes as a SCEV from the backedge taken count.
993///
994/// This also maps the SCEV into the provided type and tries to handle the
995/// computation in a way that will fold cleanly.
996static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
997 unsigned StoreSize, Loop *CurLoop,
998 const DataLayout *DL, ScalarEvolution *SE) {
999 const SCEV *NumBytesS;
1000 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1001 // pointer size if it isn't already.
1002 //
1003 // If we're going to need to zero extend the BE count, check if we can add
1004 // one to it prior to zero extending without overflow. Provided this is safe,
1005 // it allows better simplification of the +1.
1006 if (DL->getTypeSizeInBits(BECount->getType()).getFixedSize() <
1007 DL->getTypeSizeInBits(IntPtr).getFixedSize() &&
1008 SE->isLoopEntryGuardedByCond(
1009 CurLoop, ICmpInst::ICMP_NE, BECount,
1010 SE->getNegativeSCEV(SE->getOne(BECount->getType())))) {
1011 NumBytesS = SE->getZeroExtendExpr(
1012 SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW),
1013 IntPtr);
1014 } else {
1015 NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr),
1016 SE->getOne(IntPtr), SCEV::FlagNUW);
1017 }
1018
1019 // And scale it based on the store size.
1020 if (StoreSize != 1) {
1021 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
1022 SCEV::FlagNUW);
1023 }
1024 return NumBytesS;
1025}
1026
1027/// processLoopStridedStore - We see a strided store of some value. If we can
1028/// transform this into a memset or memset_pattern in the loop preheader, do so.
1029bool LoopIdiomRecognize::processLoopStridedStore(
1030 Value *DestPtr, unsigned StoreSize, MaybeAlign StoreAlignment,
1031 Value *StoredVal, Instruction *TheStore,
1032 SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
1033 const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
1034 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
1035 Constant *PatternValue = nullptr;
1036
1037 if (!SplatValue)
1038 PatternValue = getMemSetPatternValue(StoredVal, DL);
1039
1040 assert((SplatValue || PatternValue) &&(static_cast <bool> ((SplatValue || PatternValue) &&
"Expected either splat value or pattern value.") ? void (0) :
__assert_fail ("(SplatValue || PatternValue) && \"Expected either splat value or pattern value.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 1041, __extension__ __PRETTY_FUNCTION__))
1041 "Expected either splat value or pattern value.")(static_cast <bool> ((SplatValue || PatternValue) &&
"Expected either splat value or pattern value.") ? void (0) :
__assert_fail ("(SplatValue || PatternValue) && \"Expected either splat value or pattern value.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 1041, __extension__ __PRETTY_FUNCTION__))
;
1042
1043 // The trip count of the loop and the base pointer of the addrec SCEV is
1044 // guaranteed to be loop invariant, which means that it should dominate the
1045 // header. This allows us to insert code for it in the preheader.
1046 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
1047 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1048 IRBuilder<> Builder(Preheader->getTerminator());
1049 SCEVExpander Expander(*SE, *DL, "loop-idiom");
1050 SCEVExpanderCleaner ExpCleaner(Expander, *DT);
1051
1052 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
1053 Type *IntIdxTy = DL->getIndexType(DestPtr->getType());
1054
1055 bool Changed = false;
1056 const SCEV *Start = Ev->getStart();
1057 // Handle negative strided loops.
1058 if (NegStride)
1059 Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSize, SE);
1060
1061 // TODO: ideally we should still be able to generate memset if SCEV expander
1062 // is taught to generate the dependencies at the latest point.
1063 if (!isSafeToExpand(Start, *SE))
1064 return Changed;
1065
1066 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
1067 // this into a memset in the loop preheader now if we want. However, this
1068 // would be unsafe to do if there is anything else in the loop that may read
1069 // or write to the aliased location. Check for any overlap by generating the
1070 // base pointer and checking the region.
1071 Value *BasePtr =
1072 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
1073
1074 // From here on out, conservatively report to the pass manager that we've
1075 // changed the IR, even if we later clean up these added instructions. There
1076 // may be structural differences e.g. in the order of use lists not accounted
1077 // for in just a textual dump of the IR. This is written as a variable, even
1078 // though statically all the places this dominates could be replaced with
1079 // 'true', with the hope that anyone trying to be clever / "more precise" with
1080 // the return value will read this comment, and leave them alone.
1081 Changed = true;
1082
1083 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1084 StoreSize, *AA, Stores))
1085 return Changed;
1086
1087 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
1088 return Changed;
1089
1090 // Okay, everything looks good, insert the memset.
1091
1092 const SCEV *NumBytesS =
1093 getNumBytes(BECount, IntIdxTy, StoreSize, CurLoop, DL, SE);
1094
1095 // TODO: ideally we should still be able to generate memset if SCEV expander
1096 // is taught to generate the dependencies at the latest point.
1097 if (!isSafeToExpand(NumBytesS, *SE))
1098 return Changed;
1099
1100 Value *NumBytes =
1101 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1102
1103 CallInst *NewCall;
1104 if (SplatValue) {
1105 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, NumBytes,
1106 MaybeAlign(StoreAlignment));
1107 } else {
1108 // Everything is emitted in default address space
1109 Type *Int8PtrTy = DestInt8PtrTy;
1110
1111 Module *M = TheStore->getModule();
1112 StringRef FuncName = "memset_pattern16";
1113 FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(),
1114 Int8PtrTy, Int8PtrTy, IntIdxTy);
1115 inferLibFuncAttributes(M, FuncName, *TLI);
1116
1117 // Otherwise we should form a memset_pattern16. PatternValue is known to be
1118 // an constant array of 16-bytes. Plop the value into a mergable global.
1119 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1120 GlobalValue::PrivateLinkage,
1121 PatternValue, ".memset_pattern");
1122 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
1123 GV->setAlignment(Align(16));
1124 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
1125 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
1126 }
1127 NewCall->setDebugLoc(TheStore->getDebugLoc());
1128
1129 if (MSSAU) {
1130 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1131 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1132 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1133 }
1134
1135 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " Formed memset: " <<
*NewCall << "\n" << " from store to: " <<
*Ev << " at: " << *TheStore << "\n"; } } while
(false)
1136 << " from store to: " << *Ev << " at: " << *TheStoredo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " Formed memset: " <<
*NewCall << "\n" << " from store to: " <<
*Ev << " at: " << *TheStore << "\n"; } } while
(false)
1137 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " Formed memset: " <<
*NewCall << "\n" << " from store to: " <<
*Ev << " at: " << *TheStore << "\n"; } } while
(false)
;
1138
1139 ORE.emit([&]() {
1140 return OptimizationRemark(DEBUG_TYPE"loop-idiom", "ProcessLoopStridedStore",
1141 NewCall->getDebugLoc(), Preheader)
1142 << "Transformed loop-strided store in "
1143 << ore::NV("Function", TheStore->getFunction())
1144 << " function into a call to "
1145 << ore::NV("NewFunction", NewCall->getCalledFunction())
1146 << "() intrinsic";
1147 });
1148
1149 // Okay, the memset has been formed. Zap the original store and anything that
1150 // feeds into it.
1151 for (auto *I : Stores) {
1152 if (MSSAU)
1153 MSSAU->removeMemoryAccess(I, true);
1154 deleteDeadInstruction(I);
1155 }
1156 if (MSSAU && VerifyMemorySSA)
1157 MSSAU->getMemorySSA()->verifyMemorySSA();
1158 ++NumMemSet;
1159 ExpCleaner.markResultUsed();
1160 return true;
1161}
1162
1163/// If the stored value is a strided load in the same loop with the same stride
1164/// this may be transformable into a memcpy. This kicks in for stuff like
1165/// for (i) A[i] = B[i];
1166bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
1167 const SCEV *BECount) {
1168 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.")(static_cast <bool> (SI->isUnordered() && "Expected only non-volatile non-ordered stores."
) ? void (0) : __assert_fail ("SI->isUnordered() && \"Expected only non-volatile non-ordered stores.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 1168, __extension__ __PRETTY_FUNCTION__))
;
1169
1170 Value *StorePtr = SI->getPointerOperand();
1171 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1172 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
1173
1174 // The store must be feeding a non-volatile load.
1175 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1176 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.")(static_cast <bool> (LI->isUnordered() && "Expected only non-volatile non-ordered loads."
) ? void (0) : __assert_fail ("LI->isUnordered() && \"Expected only non-volatile non-ordered loads.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 1176, __extension__ __PRETTY_FUNCTION__))
;
1177
1178 // See if the pointer expression is an AddRec like {base,+,1} on the current
1179 // loop, which indicates a strided load. If we have something else, it's a
1180 // random load we can't handle.
1181 Value *LoadPtr = LI->getPointerOperand();
1182 const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1183 return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSize,
1184 SI->getAlign(), LI->getAlign(), SI, LI,
1185 StoreEv, LoadEv, BECount);
1186}
1187
1188bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
1189 Value *DestPtr, Value *SourcePtr, unsigned StoreSize, MaybeAlign StoreAlign,
1190 MaybeAlign LoadAlign, Instruction *TheStore, Instruction *TheLoad,
1191 const SCEVAddRecExpr *StoreEv, const SCEVAddRecExpr *LoadEv,
1192 const SCEV *BECount) {
1193 // The trip count of the loop and the base pointer of the addrec SCEV is
1194 // guaranteed to be loop invariant, which means that it should dominate the
1195 // header. This allows us to insert code for it in the preheader.
1196 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1197 IRBuilder<> Builder(Preheader->getTerminator());
1198 SCEVExpander Expander(*SE, *DL, "loop-idiom");
1199
1200 SCEVExpanderCleaner ExpCleaner(Expander, *DT);
1201
1202 bool Changed = false;
1203 const SCEV *StrStart = StoreEv->getStart();
1204 unsigned StrAS = DestPtr->getType()->getPointerAddressSpace();
1205 Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS));
1206
1207 APInt Stride = getStoreStride(StoreEv);
1208 bool NegStride = StoreSize == -Stride;
1209
1210 // Handle negative strided loops.
1211 if (NegStride)
1212 StrStart = getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSize, SE);
1213
1214 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
1215 // this into a memcpy in the loop preheader now if we want. However, this
1216 // would be unsafe to do if there is anything else in the loop that may read
1217 // or write the memory region we're storing to. This includes the load that
1218 // feeds the stores. Check for an alias by generating the base address and
1219 // checking everything.
1220 Value *StoreBasePtr = Expander.expandCodeFor(
1221 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
1222
1223 // From here on out, conservatively report to the pass manager that we've
1224 // changed the IR, even if we later clean up these added instructions. There
1225 // may be structural differences e.g. in the order of use lists not accounted
1226 // for in just a textual dump of the IR. This is written as a variable, even
1227 // though statically all the places this dominates could be replaced with
1228 // 'true', with the hope that anyone trying to be clever / "more precise" with
1229 // the return value will read this comment, and leave them alone.
1230 Changed = true;
1231
1232 SmallPtrSet<Instruction *, 1> Stores;
1233 Stores.insert(TheStore);
1234
1235 bool IsMemCpy = isa<MemCpyInst>(TheStore);
1236 const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store";
1237
1238 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1239 StoreSize, *AA, Stores)) {
1240 ORE.emit([&]() {
1241 return OptimizationRemarkMissed(DEBUG_TYPE"loop-idiom", "LoopMayAccessStore",
1242 TheStore)
1243 << ore::NV("Inst", InstRemark) << " in "
1244 << ore::NV("Function", TheStore->getFunction())
1245 << " function will not be hoisted: "
1246 << ore::NV("Reason", "The loop may access store location");
1247 });
1248 return Changed;
1249 }
1250
1251 const SCEV *LdStart = LoadEv->getStart();
1252 unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace();
1253
1254 // Handle negative strided loops.
1255 if (NegStride)
1256 LdStart = getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSize, SE);
1257
1258 // For a memcpy, we have to make sure that the input array is not being
1259 // mutated by the loop.
1260 Value *LoadBasePtr = Expander.expandCodeFor(
1261 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
1262
1263 // If the store is a memcpy instruction, we must check if it will write to
1264 // the load memory locations. So remove it from the ignored stores.
1265 if (IsMemCpy)
1266 Stores.erase(TheStore);
1267 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1268 StoreSize, *AA, Stores)) {
1269 ORE.emit([&]() {
1270 return OptimizationRemarkMissed(DEBUG_TYPE"loop-idiom", "LoopMayAccessLoad", TheLoad)
1271 << ore::NV("Inst", InstRemark) << " in "
1272 << ore::NV("Function", TheStore->getFunction())
1273 << " function will not be hoisted: "
1274 << ore::NV("Reason", "The loop may access load location");
1275 });
1276 return Changed;
1277 }
1278
1279 if (avoidLIRForMultiBlockLoop())
1280 return Changed;
1281
1282 // Okay, everything is safe, we can transform this!
1283
1284 const SCEV *NumBytesS =
1285 getNumBytes(BECount, IntIdxTy, StoreSize, CurLoop, DL, SE);
1286
1287 Value *NumBytes =
1288 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1289
1290 CallInst *NewCall = nullptr;
1291 // Check whether to generate an unordered atomic memcpy:
1292 // If the load or store are atomic, then they must necessarily be unordered
1293 // by previous checks.
1294 if (!TheStore->isAtomic() && !TheLoad->isAtomic())
1295 NewCall = Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr,
1296 LoadAlign, NumBytes);
1297 else {
1298 // We cannot allow unaligned ops for unordered load/store, so reject
1299 // anything where the alignment isn't at least the element size.
1300 assert((StoreAlign.hasValue() && LoadAlign.hasValue()) &&(static_cast <bool> ((StoreAlign.hasValue() && LoadAlign
.hasValue()) && "Expect unordered load/store to have align."
) ? void (0) : __assert_fail ("(StoreAlign.hasValue() && LoadAlign.hasValue()) && \"Expect unordered load/store to have align.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 1301, __extension__ __PRETTY_FUNCTION__))
1301 "Expect unordered load/store to have align.")(static_cast <bool> ((StoreAlign.hasValue() && LoadAlign
.hasValue()) && "Expect unordered load/store to have align."
) ? void (0) : __assert_fail ("(StoreAlign.hasValue() && LoadAlign.hasValue()) && \"Expect unordered load/store to have align.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 1301, __extension__ __PRETTY_FUNCTION__))
;
1302 if (StoreAlign.getValue() < StoreSize || LoadAlign.getValue() < StoreSize)
1303 return Changed;
1304
1305 // If the element.atomic memcpy is not lowered into explicit
1306 // loads/stores later, then it will be lowered into an element-size
1307 // specific lib call. If the lib call doesn't exist for our store size, then
1308 // we shouldn't generate the memcpy.
1309 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1310 return Changed;
1311
1312 // Create the call.
1313 // Note that unordered atomic loads/stores are *required* by the spec to
1314 // have an alignment but non-atomic loads/stores may not.
1315 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1316 StoreBasePtr, StoreAlign.getValue(), LoadBasePtr, LoadAlign.getValue(),
1317 NumBytes, StoreSize);
1318 }
1319 NewCall->setDebugLoc(TheStore->getDebugLoc());
1320
1321 if (MSSAU) {
1322 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1323 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1324 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1325 }
1326
1327 LLVM_DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " Formed memcpy: " <<
*NewCall << "\n" << " from load ptr=" <<
*LoadEv << " at: " << *TheLoad << "\n" <<
" from store ptr=" << *StoreEv << " at: " <<
*TheStore << "\n"; } } while (false)
1328 << " from load ptr=" << *LoadEv << " at: " << *TheLoaddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " Formed memcpy: " <<
*NewCall << "\n" << " from load ptr=" <<
*LoadEv << " at: " << *TheLoad << "\n" <<
" from store ptr=" << *StoreEv << " at: " <<
*TheStore << "\n"; } } while (false)
1329 << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " Formed memcpy: " <<
*NewCall << "\n" << " from load ptr=" <<
*LoadEv << " at: " << *TheLoad << "\n" <<
" from store ptr=" << *StoreEv << " at: " <<
*TheStore << "\n"; } } while (false)
1330 << " from store ptr=" << *StoreEv << " at: " << *TheStoredo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " Formed memcpy: " <<
*NewCall << "\n" << " from load ptr=" <<
*LoadEv << " at: " << *TheLoad << "\n" <<
" from store ptr=" << *StoreEv << " at: " <<
*TheStore << "\n"; } } while (false)
1331 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " Formed memcpy: " <<
*NewCall << "\n" << " from load ptr=" <<
*LoadEv << " at: " << *TheLoad << "\n" <<
" from store ptr=" << *StoreEv << " at: " <<
*TheStore << "\n"; } } while (false)
;
1332
1333 ORE.emit([&]() {
1334 return OptimizationRemark(DEBUG_TYPE"loop-idiom", "ProcessLoopStoreOfLoopLoad",
1335 NewCall->getDebugLoc(), Preheader)
1336 << "Formed a call to "
1337 << ore::NV("NewFunction", NewCall->getCalledFunction())
1338 << "() intrinsic from " << ore::NV("Inst", InstRemark)
1339 << " instruction in " << ore::NV("Function", TheStore->getFunction())
1340 << " function";
1341 });
1342
1343 // Okay, the memcpy has been formed. Zap the original store and anything that
1344 // feeds into it.
1345 if (MSSAU)
1346 MSSAU->removeMemoryAccess(TheStore, true);
1347 deleteDeadInstruction(TheStore);
1348 if (MSSAU && VerifyMemorySSA)
1349 MSSAU->getMemorySSA()->verifyMemorySSA();
1350 ++NumMemCpy;
1351 ExpCleaner.markResultUsed();
1352 return true;
1353}
1354
1355// When compiling for codesize we avoid idiom recognition for a multi-block loop
1356// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1357//
1358bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1359 bool IsLoopMemset) {
1360 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1361 if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) {
1362 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " " << CurLoop->getHeader
()->getParent()->getName() << " : LIR " << (
IsMemset ? "Memset" : "Memcpy") << " avoided: multi-block top-level loop\n"
; } } while (false)
1363 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " " << CurLoop->getHeader
()->getParent()->getName() << " : LIR " << (
IsMemset ? "Memset" : "Memcpy") << " avoided: multi-block top-level loop\n"
; } } while (false)
1364 << " avoided: multi-block top-level loop\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << " " << CurLoop->getHeader
()->getParent()->getName() << " : LIR " << (
IsMemset ? "Memset" : "Memcpy") << " avoided: multi-block top-level loop\n"
; } } while (false)
;
1365 return true;
1366 }
1367 }
1368
1369 return false;
1370}
1371
1372bool LoopIdiomRecognize::runOnNoncountableLoop() {
1373 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Scanning: F["
<< CurLoop->getHeader()->getParent()->getName
() << "] Noncountable Loop %" << CurLoop->getHeader
()->getName() << "\n"; } } while (false)
1374 << CurLoop->getHeader()->getParent()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Scanning: F["
<< CurLoop->getHeader()->getParent()->getName
() << "] Noncountable Loop %" << CurLoop->getHeader
()->getName() << "\n"; } } while (false)
1375 << "] Noncountable Loop %"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Scanning: F["
<< CurLoop->getHeader()->getParent()->getName
() << "] Noncountable Loop %" << CurLoop->getHeader
()->getName() << "\n"; } } while (false)
1376 << CurLoop->getHeader()->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Scanning: F["
<< CurLoop->getHeader()->getParent()->getName
() << "] Noncountable Loop %" << CurLoop->getHeader
()->getName() << "\n"; } } while (false)
;
1377
1378 return recognizePopcount() || recognizeAndInsertFFS() ||
1379 recognizeShiftUntilBitTest() || recognizeShiftUntilZero();
1380}
1381
1382/// Check if the given conditional branch is based on the comparison between
1383/// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
1384/// true), the control yields to the loop entry. If the branch matches the
1385/// behavior, the variable involved in the comparison is returned. This function
1386/// will be called to see if the precondition and postcondition of the loop are
1387/// in desirable form.
1388static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry,
1389 bool JmpOnZero = false) {
1390 if (!BI || !BI->isConditional())
1391 return nullptr;
1392
1393 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1394 if (!Cond)
1395 return nullptr;
1396
1397 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1398 if (!CmpZero || !CmpZero->isZero())
1399 return nullptr;
1400
1401 BasicBlock *TrueSucc = BI->getSuccessor(0);
1402 BasicBlock *FalseSucc = BI->getSuccessor(1);
1403 if (JmpOnZero)
1404 std::swap(TrueSucc, FalseSucc);
1405
1406 ICmpInst::Predicate Pred = Cond->getPredicate();
1407 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
1408 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
1409 return Cond->getOperand(0);
1410
1411 return nullptr;
1412}
1413
1414// Check if the recurrence variable `VarX` is in the right form to create
1415// the idiom. Returns the value coerced to a PHINode if so.
1416static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1417 BasicBlock *LoopEntry) {
1418 auto *PhiX = dyn_cast<PHINode>(VarX);
1419 if (PhiX && PhiX->getParent() == LoopEntry &&
1420 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1421 return PhiX;
1422 return nullptr;
1423}
1424
1425/// Return true iff the idiom is detected in the loop.
1426///
1427/// Additionally:
1428/// 1) \p CntInst is set to the instruction counting the population bit.
1429/// 2) \p CntPhi is set to the corresponding phi node.
1430/// 3) \p Var is set to the value whose population bits are being counted.
1431///
1432/// The core idiom we are trying to detect is:
1433/// \code
1434/// if (x0 != 0)
1435/// goto loop-exit // the precondition of the loop
1436/// cnt0 = init-val;
1437/// do {
1438/// x1 = phi (x0, x2);
1439/// cnt1 = phi(cnt0, cnt2);
1440///
1441/// cnt2 = cnt1 + 1;
1442/// ...
1443/// x2 = x1 & (x1 - 1);
1444/// ...
1445/// } while(x != 0);
1446///
1447/// loop-exit:
1448/// \endcode
1449static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1450 Instruction *&CntInst, PHINode *&CntPhi,
1451 Value *&Var) {
1452 // step 1: Check to see if the look-back branch match this pattern:
1453 // "if (a!=0) goto loop-entry".
1454 BasicBlock *LoopEntry;
1455 Instruction *DefX2, *CountInst;
1456 Value *VarX1, *VarX0;
1457 PHINode *PhiX, *CountPhi;
1458
1459 DefX2 = CountInst = nullptr;
1460 VarX1 = VarX0 = nullptr;
1461 PhiX = CountPhi = nullptr;
1462 LoopEntry = *(CurLoop->block_begin());
1463
1464 // step 1: Check if the loop-back branch is in desirable form.
1465 {
1466 if (Value *T = matchCondition(
1467 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1468 DefX2 = dyn_cast<Instruction>(T);
1469 else
1470 return false;
1471 }
1472
1473 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1474 {
1475 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1476 return false;
1477
1478 BinaryOperator *SubOneOp;
1479
1480 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1481 VarX1 = DefX2->getOperand(1);
1482 else {
1483 VarX1 = DefX2->getOperand(0);
1484 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1485 }
1486 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
1487 return false;
1488
1489 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
1490 if (!Dec ||
1491 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1492 (SubOneOp->getOpcode() == Instruction::Add &&
1493 Dec->isMinusOne()))) {
1494 return false;
1495 }
1496 }
1497
1498 // step 3: Check the recurrence of variable X
1499 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1500 if (!PhiX)
1501 return false;
1502
1503 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1504 {
1505 CountInst = nullptr;
1506 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1507 IterE = LoopEntry->end();
1508 Iter != IterE; Iter++) {
1509 Instruction *Inst = &*Iter;
1510 if (Inst->getOpcode() != Instruction::Add)
1511 continue;
1512
1513 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1514 if (!Inc || !Inc->isOne())
1515 continue;
1516
1517 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1518 if (!Phi)
1519 continue;
1520
1521 // Check if the result of the instruction is live of the loop.
1522 bool LiveOutLoop = false;
1523 for (User *U : Inst->users()) {
1524 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1525 LiveOutLoop = true;
1526 break;
1527 }
1528 }
1529
1530 if (LiveOutLoop) {
1531 CountInst = Inst;
1532 CountPhi = Phi;
1533 break;
1534 }
1535 }
1536
1537 if (!CountInst)
1538 return false;
1539 }
1540
1541 // step 5: check if the precondition is in this form:
1542 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1543 {
1544 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1545 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1546 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1547 return false;
1548
1549 CntInst = CountInst;
1550 CntPhi = CountPhi;
1551 Var = T;
1552 }
1553
1554 return true;
1555}
1556
1557/// Return true if the idiom is detected in the loop.
1558///
1559/// Additionally:
1560/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1561/// or nullptr if there is no such.
1562/// 2) \p CntPhi is set to the corresponding phi node
1563/// or nullptr if there is no such.
1564/// 3) \p Var is set to the value whose CTLZ could be used.
1565/// 4) \p DefX is set to the instruction calculating Loop exit condition.
1566///
1567/// The core idiom we are trying to detect is:
1568/// \code
1569/// if (x0 == 0)
1570/// goto loop-exit // the precondition of the loop
1571/// cnt0 = init-val;
1572/// do {
1573/// x = phi (x0, x.next); //PhiX
1574/// cnt = phi(cnt0, cnt.next);
1575///
1576/// cnt.next = cnt + 1;
1577/// ...
1578/// x.next = x >> 1; // DefX
1579/// ...
1580/// } while(x.next != 0);
1581///
1582/// loop-exit:
1583/// \endcode
1584static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
1585 Intrinsic::ID &IntrinID, Value *&InitX,
1586 Instruction *&CntInst, PHINode *&CntPhi,
1587 Instruction *&DefX) {
1588 BasicBlock *LoopEntry;
1589 Value *VarX = nullptr;
1590
1591 DefX = nullptr;
1592 CntInst = nullptr;
1593 CntPhi = nullptr;
1594 LoopEntry = *(CurLoop->block_begin());
1595
1596 // step 1: Check if the loop-back branch is in desirable form.
1597 if (Value *T = matchCondition(
1598 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1599 DefX = dyn_cast<Instruction>(T);
1600 else
1601 return false;
1602
1603 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
1604 if (!DefX || !DefX->isShift())
1605 return false;
1606 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
1607 Intrinsic::ctlz;
1608 ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));
1609 if (!Shft || !Shft->isOne())
1610 return false;
1611 VarX = DefX->getOperand(0);
1612
1613 // step 3: Check the recurrence of variable X
1614 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
1615 if (!PhiX)
1616 return false;
1617
1618 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
1619
1620 // Make sure the initial value can't be negative otherwise the ashr in the
1621 // loop might never reach zero which would make the loop infinite.
1622 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
1623 return false;
1624
1625 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1626 // or cnt.next = cnt + -1.
1627 // TODO: We can skip the step. If loop trip count is known (CTLZ),
1628 // then all uses of "cnt.next" could be optimized to the trip count
1629 // plus "cnt0". Currently it is not optimized.
1630 // This step could be used to detect POPCNT instruction:
1631 // cnt.next = cnt + (x.next & 1)
1632 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1633 IterE = LoopEntry->end();
1634 Iter != IterE; Iter++) {
1635 Instruction *Inst = &*Iter;
1636 if (Inst->getOpcode() != Instruction::Add)
1637 continue;
1638
1639 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1640 if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
1641 continue;
1642
1643 PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1644 if (!Phi)
1645 continue;
1646
1647 CntInst = Inst;
1648 CntPhi = Phi;
1649 break;
1650 }
1651 if (!CntInst)
1652 return false;
1653
1654 return true;
1655}
1656
1657/// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
1658/// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
1659/// trip count returns true; otherwise, returns false.
1660bool LoopIdiomRecognize::recognizeAndInsertFFS() {
1661 // Give up if the loop has multiple blocks or multiple backedges.
1662 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1663 return false;
1664
1665 Intrinsic::ID IntrinID;
1666 Value *InitX;
1667 Instruction *DefX = nullptr;
1668 PHINode *CntPhi = nullptr;
1669 Instruction *CntInst = nullptr;
1670 // Help decide if transformation is profitable. For ShiftUntilZero idiom,
1671 // this is always 6.
1672 size_t IdiomCanonicalSize = 6;
1673
1674 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX,
1675 CntInst, CntPhi, DefX))
1676 return false;
1677
1678 bool IsCntPhiUsedOutsideLoop = false;
1679 for (User *U : CntPhi->users())
1680 if (!CurLoop->contains(cast<Instruction>(U))) {
1681 IsCntPhiUsedOutsideLoop = true;
1682 break;
1683 }
1684 bool IsCntInstUsedOutsideLoop = false;
1685 for (User *U : CntInst->users())
1686 if (!CurLoop->contains(cast<Instruction>(U))) {
1687 IsCntInstUsedOutsideLoop = true;
1688 break;
1689 }
1690 // If both CntInst and CntPhi are used outside the loop the profitability
1691 // is questionable.
1692 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1693 return false;
1694
1695 // For some CPUs result of CTLZ(X) intrinsic is undefined
1696 // when X is 0. If we can not guarantee X != 0, we need to check this
1697 // when expand.
1698 bool ZeroCheck = false;
1699 // It is safe to assume Preheader exist as it was checked in
1700 // parent function RunOnLoop.
1701 BasicBlock *PH = CurLoop->getLoopPreheader();
1702
1703 // If we are using the count instruction outside the loop, make sure we
1704 // have a zero check as a precondition. Without the check the loop would run
1705 // one iteration for before any check of the input value. This means 0 and 1
1706 // would have identical behavior in the original loop and thus
1707 if (!IsCntPhiUsedOutsideLoop) {
1708 auto *PreCondBB = PH->getSinglePredecessor();
1709 if (!PreCondBB)
1710 return false;
1711 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1712 if (!PreCondBI)
1713 return false;
1714 if (matchCondition(PreCondBI, PH) != InitX)
1715 return false;
1716 ZeroCheck = true;
1717 }
1718
1719 // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
1720 // profitable if we delete the loop.
1721
1722 // the loop has only 6 instructions:
1723 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1724 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1725 // %shr = ashr %n.addr.0, 1
1726 // %tobool = icmp eq %shr, 0
1727 // %inc = add nsw %i.0, 1
1728 // br i1 %tobool
1729
1730 const Value *Args[] = {InitX,
1731 ConstantInt::getBool(InitX->getContext(), ZeroCheck)};
1732
1733 // @llvm.dbg doesn't count as they have no semantic effect.
1734 auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug();
1735 uint32_t HeaderSize =
1736 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());
1737
1738 IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args);
1739 InstructionCost Cost =
1740 TTI->getIntrinsicInstrCost(Attrs, TargetTransformInfo::TCK_SizeAndLatency);
1741 if (HeaderSize != IdiomCanonicalSize &&
1742 Cost > TargetTransformInfo::TCC_Basic)
1743 return false;
1744
1745 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
1746 DefX->getDebugLoc(), ZeroCheck,
1747 IsCntPhiUsedOutsideLoop);
1748 return true;
1749}
1750
1751/// Recognizes a population count idiom in a non-countable loop.
1752///
1753/// If detected, transforms the relevant code to issue the popcount intrinsic
1754/// function call, and returns true; otherwise, returns false.
1755bool LoopIdiomRecognize::recognizePopcount() {
1756 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1757 return false;
1758
1759 // Counting population are usually conducted by few arithmetic instructions.
1760 // Such instructions can be easily "absorbed" by vacant slots in a
1761 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1762 // in a compact loop.
1763
1764 // Give up if the loop has multiple blocks or multiple backedges.
1765 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1766 return false;
1767
1768 BasicBlock *LoopBody = *(CurLoop->block_begin());
1769 if (LoopBody->size() >= 20) {
1770 // The loop is too big, bail out.
1771 return false;
1772 }
1773
1774 // It should have a preheader containing nothing but an unconditional branch.
1775 BasicBlock *PH = CurLoop->getLoopPreheader();
1776 if (!PH || &PH->front() != PH->getTerminator())
1777 return false;
1778 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
1779 if (!EntryBI || EntryBI->isConditional())
1780 return false;
1781
1782 // It should have a precondition block where the generated popcount intrinsic
1783 // function can be inserted.
1784 auto *PreCondBB = PH->getSinglePredecessor();
1785 if (!PreCondBB)
1786 return false;
1787 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1788 if (!PreCondBI || PreCondBI->isUnconditional())
1789 return false;
1790
1791 Instruction *CntInst;
1792 PHINode *CntPhi;
1793 Value *Val;
1794 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1795 return false;
1796
1797 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1798 return true;
1799}
1800
1801static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1802 const DebugLoc &DL) {
1803 Value *Ops[] = {Val};
1804 Type *Tys[] = {Val->getType()};
1805
1806 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1807 Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1808 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1809 CI->setDebugLoc(DL);
1810
1811 return CI;
1812}
1813
1814static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1815 const DebugLoc &DL, bool ZeroCheck,
1816 Intrinsic::ID IID) {
1817 Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)};
1818 Type *Tys[] = {Val->getType()};
1819
1820 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1821 Function *Func = Intrinsic::getDeclaration(M, IID, Tys);
1822 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1823 CI->setDebugLoc(DL);
1824
1825 return CI;
1826}
1827
1828/// Transform the following loop (Using CTLZ, CTTZ is similar):
1829/// loop:
1830/// CntPhi = PHI [Cnt0, CntInst]
1831/// PhiX = PHI [InitX, DefX]
1832/// CntInst = CntPhi + 1
1833/// DefX = PhiX >> 1
1834/// LOOP_BODY
1835/// Br: loop if (DefX != 0)
1836/// Use(CntPhi) or Use(CntInst)
1837///
1838/// Into:
1839/// If CntPhi used outside the loop:
1840/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1841/// Count = CountPrev + 1
1842/// else
1843/// Count = BitWidth(InitX) - CTLZ(InitX)
1844/// loop:
1845/// CntPhi = PHI [Cnt0, CntInst]
1846/// PhiX = PHI [InitX, DefX]
1847/// PhiCount = PHI [Count, Dec]
1848/// CntInst = CntPhi + 1
1849/// DefX = PhiX >> 1
1850/// Dec = PhiCount - 1
1851/// LOOP_BODY
1852/// Br: loop if (Dec != 0)
1853/// Use(CountPrev + Cnt0) // Use(CntPhi)
1854/// or
1855/// Use(Count + Cnt0) // Use(CntInst)
1856///
1857/// If LOOP_BODY is empty the loop will be deleted.
1858/// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1859void LoopIdiomRecognize::transformLoopToCountable(
1860 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
1861 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
1862 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
1863 BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
1864
1865 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
1866 IRBuilder<> Builder(PreheaderBr);
1867 Builder.SetCurrentDebugLocation(DL);
1868
1869 // If there are no uses of CntPhi crate:
1870 // Count = BitWidth - CTLZ(InitX);
1871 // NewCount = Count;
1872 // If there are uses of CntPhi create:
1873 // NewCount = BitWidth - CTLZ(InitX >> 1);
1874 // Count = NewCount + 1;
1875 Value *InitXNext;
1876 if (IsCntPhiUsedOutsideLoop) {
1877 if (DefX->getOpcode() == Instruction::AShr)
1878 InitXNext = Builder.CreateAShr(InitX, 1);
1879 else if (DefX->getOpcode() == Instruction::LShr)
1880 InitXNext = Builder.CreateLShr(InitX, 1);
1881 else if (DefX->getOpcode() == Instruction::Shl) // cttz
1882 InitXNext = Builder.CreateShl(InitX, 1);
1883 else
1884 llvm_unreachable("Unexpected opcode!")::llvm::llvm_unreachable_internal("Unexpected opcode!", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 1884)
;
1885 } else
1886 InitXNext = InitX;
1887 Value *Count =
1888 createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
1889 Type *CountTy = Count->getType();
1890 Count = Builder.CreateSub(
1891 ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count);
1892 Value *NewCount = Count;
1893 if (IsCntPhiUsedOutsideLoop)
1894 Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1));
1895
1896 NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType());
1897
1898 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1899 if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) {
1900 // If the counter was being incremented in the loop, add NewCount to the
1901 // counter's initial value, but only if the initial value is not zero.
1902 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1903 if (!InitConst || !InitConst->isZero())
1904 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1905 } else {
1906 // If the count was being decremented in the loop, subtract NewCount from
1907 // the counter's initial value.
1908 NewCount = Builder.CreateSub(CntInitVal, NewCount);
1909 }
1910
1911 // Step 2: Insert new IV and loop condition:
1912 // loop:
1913 // ...
1914 // PhiCount = PHI [Count, Dec]
1915 // ...
1916 // Dec = PhiCount - 1
1917 // ...
1918 // Br: loop if (Dec != 0)
1919 BasicBlock *Body = *(CurLoop->block_begin());
1920 auto *LbBr = cast<BranchInst>(Body->getTerminator());
1921 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1922
1923 PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi", &Body->front());
1924
1925 Builder.SetInsertPoint(LbCond);
1926 Instruction *TcDec = cast<Instruction>(Builder.CreateSub(
1927 TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true));
1928
1929 TcPhi->addIncoming(Count, Preheader);
1930 TcPhi->addIncoming(TcDec, Body);
1931
1932 CmpInst::Predicate Pred =
1933 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
1934 LbCond->setPredicate(Pred);
1935 LbCond->setOperand(0, TcDec);
1936 LbCond->setOperand(1, ConstantInt::get(CountTy, 0));
1937
1938 // Step 3: All the references to the original counter outside
1939 // the loop are replaced with the NewCount
1940 if (IsCntPhiUsedOutsideLoop)
1941 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
1942 else
1943 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1944
1945 // step 4: Forget the "non-computable" trip-count SCEV associated with the
1946 // loop. The loop would otherwise not be deleted even if it becomes empty.
1947 SE->forgetLoop(CurLoop);
1948}
1949
1950void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1951 Instruction *CntInst,
1952 PHINode *CntPhi, Value *Var) {
1953 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1954 auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());
1955 const DebugLoc &DL = CntInst->getDebugLoc();
1956
1957 // Assuming before transformation, the loop is following:
1958 // if (x) // the precondition
1959 // do { cnt++; x &= x - 1; } while(x);
1960
1961 // Step 1: Insert the ctpop instruction at the end of the precondition block
1962 IRBuilder<> Builder(PreCondBr);
1963 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1964 {
1965 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1966 NewCount = PopCntZext =
1967 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1968
1969 if (NewCount != PopCnt)
1970 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1971
1972 // TripCnt is exactly the number of iterations the loop has
1973 TripCnt = NewCount;
1974
1975 // If the population counter's initial value is not zero, insert Add Inst.
1976 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1977 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1978 if (!InitConst || !InitConst->isZero()) {
1979 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1980 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1981 }
1982 }
1983
1984 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
1985 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
1986 // function would be partial dead code, and downstream passes will drag
1987 // it back from the precondition block to the preheader.
1988 {
1989 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1990
1991 Value *Opnd0 = PopCntZext;
1992 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1993 if (PreCond->getOperand(0) != Var)
1994 std::swap(Opnd0, Opnd1);
1995
1996 ICmpInst *NewPreCond = cast<ICmpInst>(
1997 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1998 PreCondBr->setCondition(NewPreCond);
1999
2000 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
2001 }
2002
2003 // Step 3: Note that the population count is exactly the trip count of the
2004 // loop in question, which enable us to convert the loop from noncountable
2005 // loop into a countable one. The benefit is twofold:
2006 //
2007 // - If the loop only counts population, the entire loop becomes dead after
2008 // the transformation. It is a lot easier to prove a countable loop dead
2009 // than to prove a noncountable one. (In some C dialects, an infinite loop
2010 // isn't dead even if it computes nothing useful. In general, DCE needs
2011 // to prove a noncountable loop finite before safely delete it.)
2012 //
2013 // - If the loop also performs something else, it remains alive.
2014 // Since it is transformed to countable form, it can be aggressively
2015 // optimized by some optimizations which are in general not applicable
2016 // to a noncountable loop.
2017 //
2018 // After this step, this loop (conceptually) would look like following:
2019 // newcnt = __builtin_ctpop(x);
2020 // t = newcnt;
2021 // if (x)
2022 // do { cnt++; x &= x-1; t--) } while (t > 0);
2023 BasicBlock *Body = *(CurLoop->block_begin());
2024 {
2025 auto *LbBr = cast<BranchInst>(Body->getTerminator());
2026 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
2027 Type *Ty = TripCnt->getType();
2028
2029 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
2030
2031 Builder.SetInsertPoint(LbCond);
2032 Instruction *TcDec = cast<Instruction>(
2033 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
2034 "tcdec", false, true));
2035
2036 TcPhi->addIncoming(TripCnt, PreHead);
2037 TcPhi->addIncoming(TcDec, Body);
2038
2039 CmpInst::Predicate Pred =
2040 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
2041 LbCond->setPredicate(Pred);
2042 LbCond->setOperand(0, TcDec);
2043 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
2044 }
2045
2046 // Step 4: All the references to the original population counter outside
2047 // the loop are replaced with the NewCount -- the value returned from
2048 // __builtin_ctpop().
2049 CntInst->replaceUsesOutsideBlock(NewCount, Body);
2050
2051 // step 5: Forget the "non-computable" trip-count SCEV associated with the
2052 // loop. The loop would otherwise not be deleted even if it becomes empty.
2053 SE->forgetLoop(CurLoop);
2054}
2055
2056/// Match loop-invariant value.
2057template <typename SubPattern_t> struct match_LoopInvariant {
2058 SubPattern_t SubPattern;
2059 const Loop *L;
2060
2061 match_LoopInvariant(const SubPattern_t &SP, const Loop *L)
2062 : SubPattern(SP), L(L) {}
2063
2064 template <typename ITy> bool match(ITy *V) {
2065 return L->isLoopInvariant(V) && SubPattern.match(V);
2066 }
2067};
2068
2069/// Matches if the value is loop-invariant.
2070template <typename Ty>
2071inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) {
2072 return match_LoopInvariant<Ty>(M, L);
2073}
2074
2075/// Return true if the idiom is detected in the loop.
2076///
2077/// The core idiom we are trying to detect is:
2078/// \code
2079/// entry:
2080/// <...>
2081/// %bitmask = shl i32 1, %bitpos
2082/// br label %loop
2083///
2084/// loop:
2085/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
2086/// %x.curr.bitmasked = and i32 %x.curr, %bitmask
2087/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
2088/// %x.next = shl i32 %x.curr, 1
2089/// <...>
2090/// br i1 %x.curr.isbitunset, label %loop, label %end
2091///
2092/// end:
2093/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2094/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
2095/// <...>
2096/// \endcode
2097static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX,
2098 Value *&BitMask, Value *&BitPos,
2099 Value *&CurrX, Instruction *&NextX) {
2100 LLVM_DEBUG(dbgs() << DEBUG_TYPEdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Performing shift-until-bittest idiom detection.\n"
; } } while (false)
2101 " Performing shift-until-bittest idiom detection.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Performing shift-until-bittest idiom detection.\n"
; } } while (false)
;
2102
2103 // Give up if the loop has multiple blocks or multiple backedges.
2104 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
2105 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad block/backedge count.\n"
; } } while (false)
;
2106 return false;
2107 }
2108
2109 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2110 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2111 assert(LoopPreheaderBB && "There is always a loop preheader.")(static_cast <bool> (LoopPreheaderBB && "There is always a loop preheader."
) ? void (0) : __assert_fail ("LoopPreheaderBB && \"There is always a loop preheader.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2111, __extension__ __PRETTY_FUNCTION__))
;
2112
2113 using namespace PatternMatch;
2114
2115 // Step 1: Check if the loop backedge is in desirable form.
2116
2117 ICmpInst::Predicate Pred;
2118 Value *CmpLHS, *CmpRHS;
2119 BasicBlock *TrueBB, *FalseBB;
2120 if (!match(LoopHeaderBB->getTerminator(),
2121 m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
2122 m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) {
2123 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad backedge structure.\n"
; } } while (false)
;
2124 return false;
2125 }
2126
2127 // Step 2: Check if the backedge's condition is in desirable form.
2128
2129 auto MatchVariableBitMask = [&]() {
2130 return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
2131 match(CmpLHS,
2132 m_c_And(m_Value(CurrX),
2133 m_CombineAnd(
2134 m_Value(BitMask),
2135 m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)),
2136 CurLoop))));
2137 };
2138 auto MatchConstantBitMask = [&]() {
2139 return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
2140 match(CmpLHS, m_And(m_Value(CurrX),
2141 m_CombineAnd(m_Value(BitMask), m_Power2()))) &&
2142 (BitPos = ConstantExpr::getExactLogBase2(cast<Constant>(BitMask)));
2143 };
2144 auto MatchDecomposableConstantBitMask = [&]() {
2145 APInt Mask;
2146 return llvm::decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, CurrX, Mask) &&
2147 ICmpInst::isEquality(Pred) && Mask.isPowerOf2() &&
2148 (BitMask = ConstantInt::get(CurrX->getType(), Mask)) &&
2149 (BitPos = ConstantInt::get(CurrX->getType(), Mask.logBase2()));
2150 };
2151
2152 if (!MatchVariableBitMask() && !MatchConstantBitMask() &&
2153 !MatchDecomposableConstantBitMask()) {
2154 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad backedge comparison.\n"
; } } while (false)
;
2155 return false;
2156 }
2157
2158 // Step 3: Check if the recurrence is in desirable form.
2159 auto *CurrXPN = dyn_cast<PHINode>(CurrX);
2160 if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {
2161 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Not an expected PHI node.\n"
; } } while (false)
;
2162 return false;
2163 }
2164
2165 BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);
2166 NextX =
2167 dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB));
2168
2169 assert(CurLoop->isLoopInvariant(BaseX) &&(static_cast <bool> (CurLoop->isLoopInvariant(BaseX)
&& "Expected BaseX to be avaliable in the preheader!"
) ? void (0) : __assert_fail ("CurLoop->isLoopInvariant(BaseX) && \"Expected BaseX to be avaliable in the preheader!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2170, __extension__ __PRETTY_FUNCTION__))
2170 "Expected BaseX to be avaliable in the preheader!")(static_cast <bool> (CurLoop->isLoopInvariant(BaseX)
&& "Expected BaseX to be avaliable in the preheader!"
) ? void (0) : __assert_fail ("CurLoop->isLoopInvariant(BaseX) && \"Expected BaseX to be avaliable in the preheader!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2170, __extension__ __PRETTY_FUNCTION__))
;
2171
2172 if (!NextX || !match(NextX, m_Shl(m_Specific(CurrX), m_One()))) {
2173 // FIXME: support right-shift?
2174 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad recurrence.\n"
; } } while (false)
;
2175 return false;
2176 }
2177
2178 // Step 4: Check if the backedge's destinations are in desirable form.
2179
2180 assert(ICmpInst::isEquality(Pred) &&(static_cast <bool> (ICmpInst::isEquality(Pred) &&
"Should only get equality predicates here.") ? void (0) : __assert_fail
("ICmpInst::isEquality(Pred) && \"Should only get equality predicates here.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2181, __extension__ __PRETTY_FUNCTION__))
2181 "Should only get equality predicates here.")(static_cast <bool> (ICmpInst::isEquality(Pred) &&
"Should only get equality predicates here.") ? void (0) : __assert_fail
("ICmpInst::isEquality(Pred) && \"Should only get equality predicates here.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2181, __extension__ __PRETTY_FUNCTION__))
;
2182
2183 // cmp-br is commutative, so canonicalize to a single variant.
2184 if (Pred != ICmpInst::Predicate::ICMP_EQ) {
2185 Pred = ICmpInst::getInversePredicate(Pred);
2186 std::swap(TrueBB, FalseBB);
2187 }
2188
2189 // We expect to exit loop when comparison yields false,
2190 // so when it yields true we should branch back to loop header.
2191 if (TrueBB != LoopHeaderBB) {
2192 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad backedge flow.\n"
; } } while (false)
;
2193 return false;
2194 }
2195
2196 // Okay, idiom checks out.
2197 return true;
2198}
2199
2200/// Look for the following loop:
2201/// \code
2202/// entry:
2203/// <...>
2204/// %bitmask = shl i32 1, %bitpos
2205/// br label %loop
2206///
2207/// loop:
2208/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
2209/// %x.curr.bitmasked = and i32 %x.curr, %bitmask
2210/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
2211/// %x.next = shl i32 %x.curr, 1
2212/// <...>
2213/// br i1 %x.curr.isbitunset, label %loop, label %end
2214///
2215/// end:
2216/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2217/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
2218/// <...>
2219/// \endcode
2220///
2221/// And transform it into:
2222/// \code
2223/// entry:
2224/// %bitmask = shl i32 1, %bitpos
2225/// %lowbitmask = add i32 %bitmask, -1
2226/// %mask = or i32 %lowbitmask, %bitmask
2227/// %x.masked = and i32 %x, %mask
2228/// %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked,
2229/// i1 true)
2230/// %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros
2231/// %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -1
2232/// %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos
2233/// %tripcount = add i32 %backedgetakencount, 1
2234/// %x.curr = shl i32 %x, %backedgetakencount
2235/// %x.next = shl i32 %x, %tripcount
2236/// br label %loop
2237///
2238/// loop:
2239/// %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ]
2240/// %loop.iv.next = add nuw i32 %loop.iv, 1
2241/// %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount
2242/// <...>
2243/// br i1 %loop.ivcheck, label %end, label %loop
2244///
2245/// end:
2246/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2247/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
2248/// <...>
2249/// \endcode
2250bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {
2251 bool MadeChange = false;
2252
2253 Value *X, *BitMask, *BitPos, *XCurr;
2254 Instruction *XNext;
2255 if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr,
2256 XNext)) {
2257 LLVM_DEBUG(dbgs() << DEBUG_TYPEdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " shift-until-bittest idiom detection failed.\n"
; } } while (false)
2258 " shift-until-bittest idiom detection failed.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " shift-until-bittest idiom detection failed.\n"
; } } while (false)
;
2259 return MadeChange;
2260 }
2261 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " shift-until-bittest idiom detected!\n"
; } } while (false)
;
2262
2263 // Ok, it is the idiom we were looking for, we *could* transform this loop,
2264 // but is it profitable to transform?
2265
2266 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2267 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2268 assert(LoopPreheaderBB && "There is always a loop preheader.")(static_cast <bool> (LoopPreheaderBB && "There is always a loop preheader."
) ? void (0) : __assert_fail ("LoopPreheaderBB && \"There is always a loop preheader.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2268, __extension__ __PRETTY_FUNCTION__))
;
2269
2270 BasicBlock *SuccessorBB = CurLoop->getExitBlock();
2271 assert(SuccessorBB && "There is only a single successor.")(static_cast <bool> (SuccessorBB && "There is only a single successor."
) ? void (0) : __assert_fail ("SuccessorBB && \"There is only a single successor.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2271, __extension__ __PRETTY_FUNCTION__))
;
2272
2273 IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
2274 Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc());
2275
2276 Intrinsic::ID IntrID = Intrinsic::ctlz;
2277 Type *Ty = X->getType();
2278 unsigned Bitwidth = Ty->getScalarSizeInBits();
2279
2280 TargetTransformInfo::TargetCostKind CostKind =
2281 TargetTransformInfo::TCK_SizeAndLatency;
2282
2283 // The rewrite is considered to be unprofitable iff and only iff the
2284 // intrinsic/shift we'll use are not cheap. Note that we are okay with *just*
2285 // making the loop countable, even if nothing else changes.
2286 IntrinsicCostAttributes Attrs(
2287 IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getTrue()});
2288 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
2289 if (Cost > TargetTransformInfo::TCC_Basic) {
2290 LLVM_DEBUG(dbgs() << DEBUG_TYPEdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Intrinsic is too costly, not beneficial\n"
; } } while (false)
2291 " Intrinsic is too costly, not beneficial\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Intrinsic is too costly, not beneficial\n"
; } } while (false)
;
2292 return MadeChange;
2293 }
2294 if (TTI->getArithmeticInstrCost(Instruction::Shl, Ty, CostKind) >
2295 TargetTransformInfo::TCC_Basic) {
2296 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Shift is too costly, not beneficial\n"
; } } while (false)
;
2297 return MadeChange;
2298 }
2299
2300 // Ok, transform appears worthwhile.
2301 MadeChange = true;
2302
2303 // Step 1: Compute the loop trip count.
2304
2305 Value *LowBitMask = Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty),
2306 BitPos->getName() + ".lowbitmask");
2307 Value *Mask =
2308 Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask");
2309 Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked");
2310 CallInst *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(
2311 IntrID, Ty, {XMasked, /*is_zero_undef=*/Builder.getTrue()},
2312 /*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros");
2313 Value *XMaskedNumActiveBits = Builder.CreateSub(
2314 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros,
2315 XMasked->getName() + ".numactivebits", /*HasNUW=*/true,
2316 /*HasNSW=*/Bitwidth != 2);
2317 Value *XMaskedLeadingOnePos =
2318 Builder.CreateAdd(XMaskedNumActiveBits, Constant::getAllOnesValue(Ty),
2319 XMasked->getName() + ".leadingonepos", /*HasNUW=*/false,
2320 /*HasNSW=*/Bitwidth > 2);
2321
2322 Value *LoopBackedgeTakenCount = Builder.CreateSub(
2323 BitPos, XMaskedLeadingOnePos, CurLoop->getName() + ".backedgetakencount",
2324 /*HasNUW=*/true, /*HasNSW=*/true);
2325 // We know loop's backedge-taken count, but what's loop's trip count?
2326 // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
2327 Value *LoopTripCount =
2328 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
2329 CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
2330 /*HasNSW=*/Bitwidth != 2);
2331
2332 // Step 2: Compute the recurrence's final value without a loop.
2333
2334 // NewX is always safe to compute, because `LoopBackedgeTakenCount`
2335 // will always be smaller than `bitwidth(X)`, i.e. we never get poison.
2336 Value *NewX = Builder.CreateShl(X, LoopBackedgeTakenCount);
2337 NewX->takeName(XCurr);
2338 if (auto *I = dyn_cast<Instruction>(NewX))
2339 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
2340
2341 Value *NewXNext;
2342 // Rewriting XNext is more complicated, however, because `X << LoopTripCount`
2343 // will be poison iff `LoopTripCount == bitwidth(X)` (which will happen
2344 // iff `BitPos` is `bitwidth(x) - 1` and `X` is `1`). So unless we know
2345 // that isn't the case, we'll need to emit an alternative, safe IR.
2346 if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() ||
2347 PatternMatch::match(
2348 BitPos, PatternMatch::m_SpecificInt_ICMP(
2349 ICmpInst::ICMP_NE, APInt(Ty->getScalarSizeInBits(),
2350 Ty->getScalarSizeInBits() - 1))))
2351 NewXNext = Builder.CreateShl(X, LoopTripCount);
2352 else {
2353 // Otherwise, just additionally shift by one. It's the smallest solution,
2354 // alternatively, we could check that NewX is INT_MIN (or BitPos is )
2355 // and select 0 instead.
2356 NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));
2357 }
2358
2359 NewXNext->takeName(XNext);
2360 if (auto *I = dyn_cast<Instruction>(NewXNext))
2361 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
2362
2363 // Step 3: Adjust the successor basic block to recieve the computed
2364 // recurrence's final value instead of the recurrence itself.
2365
2366 XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB);
2367 XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB);
2368
2369 // Step 4: Rewrite the loop into a countable form, with canonical IV.
2370
2371 // The new canonical induction variable.
2372 Builder.SetInsertPoint(&LoopHeaderBB->front());
2373 auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
2374
2375 // The induction itself.
2376 // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
2377 Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
2378 auto *IVNext =
2379 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
2380 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
2381
2382 // The loop trip count check.
2383 auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,
2384 CurLoop->getName() + ".ivcheck");
2385 Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);
2386 LoopHeaderBB->getTerminator()->eraseFromParent();
2387
2388 // Populate the IV PHI.
2389 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
2390 IV->addIncoming(IVNext, LoopHeaderBB);
2391
2392 // Step 5: Forget the "non-computable" trip-count SCEV associated with the
2393 // loop. The loop would otherwise not be deleted even if it becomes empty.
2394
2395 SE->forgetLoop(CurLoop);
2396
2397 // Other passes will take care of actually deleting the loop if possible.
2398
2399 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " shift-until-bittest idiom optimized!\n"
; } } while (false)
;
2400
2401 ++NumShiftUntilBitTest;
2402 return MadeChange;
2403}
2404
2405/// Return true if the idiom is detected in the loop.
2406///
2407/// The core idiom we are trying to detect is:
2408/// \code
2409/// entry:
2410/// <...>
2411/// %start = <...>
2412/// %extraoffset = <...>
2413/// <...>
2414/// br label %for.cond
2415///
2416/// loop:
2417/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
2418/// %nbits = add nsw i8 %iv, %extraoffset
2419/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
2420/// %val.shifted.iszero = icmp eq i8 %val.shifted, 0
2421/// %iv.next = add i8 %iv, 1
2422/// <...>
2423/// br i1 %val.shifted.iszero, label %end, label %loop
2424///
2425/// end:
2426/// %iv.res = phi i8 [ %iv, %loop ] <...>
2427/// %nbits.res = phi i8 [ %nbits, %loop ] <...>
2428/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
2429/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
2430/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
2431/// <...>
2432/// \endcode
2433static bool detectShiftUntilZeroIdiom(Loop *CurLoop, ScalarEvolution *SE,
2434 Instruction *&ValShiftedIsZero,
2435 Intrinsic::ID &IntrinID, Instruction *&IV,
2436 Value *&Start, Value *&Val,
2437 const SCEV *&ExtraOffsetExpr,
2438 bool &InvertedCond) {
2439 LLVM_DEBUG(dbgs() << DEBUG_TYPEdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Performing shift-until-zero idiom detection.\n"
; } } while (false)
2440 " Performing shift-until-zero idiom detection.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Performing shift-until-zero idiom detection.\n"
; } } while (false)
;
2441
2442 // Give up if the loop has multiple blocks or multiple backedges.
2443 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
2444 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad block/backedge count.\n"
; } } while (false)
;
2445 return false;
2446 }
2447
2448 Instruction *ValShifted, *NBits, *IVNext;
2449 Value *ExtraOffset;
2450
2451 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2452 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2453 assert(LoopPreheaderBB && "There is always a loop preheader.")(static_cast <bool> (LoopPreheaderBB && "There is always a loop preheader."
) ? void (0) : __assert_fail ("LoopPreheaderBB && \"There is always a loop preheader.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2453, __extension__ __PRETTY_FUNCTION__))
;
2454
2455 using namespace PatternMatch;
2456
2457 // Step 1: Check if the loop backedge, condition is in desirable form.
2458
2459 ICmpInst::Predicate Pred;
2460 BasicBlock *TrueBB, *FalseBB;
2461 if (!match(LoopHeaderBB->getTerminator(),
2462 m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB),
2463 m_BasicBlock(FalseBB))) ||
2464 !match(ValShiftedIsZero,
2465 m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) ||
2466 !ICmpInst::isEquality(Pred)) {
2467 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad backedge structure.\n"
; } } while (false)
;
2468 return false;
2469 }
2470
2471 // Step 2: Check if the comparison's operand is in desirable form.
2472 // FIXME: Val could be a one-input PHI node, which we should look past.
2473 if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop),
2474 m_Instruction(NBits)))) {
2475 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad comparisons value computation.\n"
; } } while (false)
;
2476 return false;
2477 }
2478 IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz
2479 : Intrinsic::ctlz;
2480
2481 // Step 3: Check if the shift amount is in desirable form.
2482
2483 if (match(NBits, m_c_Add(m_Instruction(IV),
2484 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
2485 (NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap()))
2486 ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset));
2487 else if (match(NBits,
2488 m_Sub(m_Instruction(IV),
2489 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
2490 NBits->hasNoSignedWrap())
2491 ExtraOffsetExpr = SE->getSCEV(ExtraOffset);
2492 else {
2493 IV = NBits;
2494 ExtraOffsetExpr = SE->getZero(NBits->getType());
2495 }
2496
2497 // Step 4: Check if the recurrence is in desirable form.
2498 auto *IVPN = dyn_cast<PHINode>(IV);
2499 if (!IVPN || IVPN->getParent() != LoopHeaderBB) {
2500 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Not an expected PHI node.\n"
; } } while (false)
;
2501 return false;
2502 }
2503
2504 Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);
2505 IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB));
2506
2507 if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) {
2508 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad recurrence.\n"
; } } while (false)
;
2509 return false;
2510 }
2511
2512 // Step 4: Check if the backedge's destinations are in desirable form.
2513
2514 assert(ICmpInst::isEquality(Pred) &&(static_cast <bool> (ICmpInst::isEquality(Pred) &&
"Should only get equality predicates here.") ? void (0) : __assert_fail
("ICmpInst::isEquality(Pred) && \"Should only get equality predicates here.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2515, __extension__ __PRETTY_FUNCTION__))
2515 "Should only get equality predicates here.")(static_cast <bool> (ICmpInst::isEquality(Pred) &&
"Should only get equality predicates here.") ? void (0) : __assert_fail
("ICmpInst::isEquality(Pred) && \"Should only get equality predicates here.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2515, __extension__ __PRETTY_FUNCTION__))
;
2516
2517 // cmp-br is commutative, so canonicalize to a single variant.
2518 InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ;
2519 if (InvertedCond) {
2520 Pred = ICmpInst::getInversePredicate(Pred);
Value stored to 'Pred' is never read
2521 std::swap(TrueBB, FalseBB);
2522 }
2523
2524 // We expect to exit loop when comparison yields true,
2525 // so when it yields false we should branch back to loop header.
2526 if (FalseBB != LoopHeaderBB) {
2527 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Bad backedge flow.\n"
; } } while (false)
;
2528 return false;
2529 }
2530
2531 // The new, countable, loop will certainly only run a known number of
2532 // iterations, It won't be infinite. But the old loop might be infinite
2533 // under certain conditions. For logical shifts, the value will become zero
2534 // after at most bitwidth(%Val) loop iterations. However, for arithmetic
2535 // right-shift, iff the sign bit was set, the value will never become zero,
2536 // and the loop may never finish.
2537 if (ValShifted->getOpcode() == Instruction::AShr &&
2538 !isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) {
2539 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Can not prove the loop is finite.\n"
; } } while (false)
;
2540 return false;
2541 }
2542
2543 // Okay, idiom checks out.
2544 return true;
2545}
2546
2547/// Look for the following loop:
2548/// \code
2549/// entry:
2550/// <...>
2551/// %start = <...>
2552/// %extraoffset = <...>
2553/// <...>
2554/// br label %for.cond
2555///
2556/// loop:
2557/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
2558/// %nbits = add nsw i8 %iv, %extraoffset
2559/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
2560/// %val.shifted.iszero = icmp eq i8 %val.shifted, 0
2561/// %iv.next = add i8 %iv, 1
2562/// <...>
2563/// br i1 %val.shifted.iszero, label %end, label %loop
2564///
2565/// end:
2566/// %iv.res = phi i8 [ %iv, %loop ] <...>
2567/// %nbits.res = phi i8 [ %nbits, %loop ] <...>
2568/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
2569/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
2570/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
2571/// <...>
2572/// \endcode
2573///
2574/// And transform it into:
2575/// \code
2576/// entry:
2577/// <...>
2578/// %start = <...>
2579/// %extraoffset = <...>
2580/// <...>
2581/// %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0)
2582/// %val.numactivebits = sub i8 8, %val.numleadingzeros
2583/// %extraoffset.neg = sub i8 0, %extraoffset
2584/// %tmp = add i8 %val.numactivebits, %extraoffset.neg
2585/// %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start)
2586/// %loop.tripcount = sub i8 %iv.final, %start
2587/// br label %loop
2588///
2589/// loop:
2590/// %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ]
2591/// %loop.iv.next = add i8 %loop.iv, 1
2592/// %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount
2593/// %iv = add i8 %loop.iv, %start
2594/// <...>
2595/// br i1 %loop.ivcheck, label %end, label %loop
2596///
2597/// end:
2598/// %iv.res = phi i8 [ %iv.final, %loop ] <...>
2599/// <...>
2600/// \endcode
2601bool LoopIdiomRecognize::recognizeShiftUntilZero() {
2602 bool MadeChange = false;
2603
2604 Instruction *ValShiftedIsZero;
2605 Intrinsic::ID IntrID;
2606 Instruction *IV;
2607 Value *Start, *Val;
2608 const SCEV *ExtraOffsetExpr;
2609 bool InvertedCond;
2610 if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV,
2611 Start, Val, ExtraOffsetExpr, InvertedCond)) {
2612 LLVM_DEBUG(dbgs() << DEBUG_TYPEdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " shift-until-zero idiom detection failed.\n"
; } } while (false)
2613 " shift-until-zero idiom detection failed.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " shift-until-zero idiom detection failed.\n"
; } } while (false)
;
2614 return MadeChange;
2615 }
2616 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " shift-until-zero idiom detected!\n"
; } } while (false)
;
2617
2618 // Ok, it is the idiom we were looking for, we *could* transform this loop,
2619 // but is it profitable to transform?
2620
2621 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2622 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2623 assert(LoopPreheaderBB && "There is always a loop preheader.")(static_cast <bool> (LoopPreheaderBB && "There is always a loop preheader."
) ? void (0) : __assert_fail ("LoopPreheaderBB && \"There is always a loop preheader.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2623, __extension__ __PRETTY_FUNCTION__))
;
2624
2625 BasicBlock *SuccessorBB = CurLoop->getExitBlock();
2626 assert(SuccessorBB && "There is only a single successor.")(static_cast <bool> (SuccessorBB && "There is only a single successor."
) ? void (0) : __assert_fail ("SuccessorBB && \"There is only a single successor.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp"
, 2626, __extension__ __PRETTY_FUNCTION__))
;
2627
2628 IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
2629 Builder.SetCurrentDebugLocation(IV->getDebugLoc());
2630
2631 Type *Ty = Val->getType();
2632 unsigned Bitwidth = Ty->getScalarSizeInBits();
2633
2634 TargetTransformInfo::TargetCostKind CostKind =
2635 TargetTransformInfo::TCK_SizeAndLatency;
2636
2637 // The rewrite is considered to be unprofitable iff and only iff the
2638 // intrinsic we'll use are not cheap. Note that we are okay with *just*
2639 // making the loop countable, even if nothing else changes.
2640 IntrinsicCostAttributes Attrs(
2641 IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getFalse()});
2642 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
2643 if (Cost > TargetTransformInfo::TCC_Basic) {
2644 LLVM_DEBUG(dbgs() << DEBUG_TYPEdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Intrinsic is too costly, not beneficial\n"
; } } while (false)
2645 " Intrinsic is too costly, not beneficial\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " Intrinsic is too costly, not beneficial\n"
; } } while (false)
;
2646 return MadeChange;
2647 }
2648
2649 // Ok, transform appears worthwhile.
2650 MadeChange = true;
2651
2652 bool OffsetIsZero = false;
2653 if (auto *ExtraOffsetExprC = dyn_cast<SCEVConstant>(ExtraOffsetExpr))
2654 OffsetIsZero = ExtraOffsetExprC->isZero();
2655
2656 // Step 1: Compute the loop's final IV value / trip count.
2657
2658 CallInst *ValNumLeadingZeros = Builder.CreateIntrinsic(
2659 IntrID, Ty, {Val, /*is_zero_undef=*/Builder.getFalse()},
2660 /*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros");
2661 Value *ValNumActiveBits = Builder.CreateSub(
2662 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros,
2663 Val->getName() + ".numactivebits", /*HasNUW=*/true,
2664 /*HasNSW=*/Bitwidth != 2);
2665
2666 SCEVExpander Expander(*SE, *DL, "loop-idiom");
2667 Expander.setInsertPoint(&*Builder.GetInsertPoint());
2668 Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);
2669
2670 Value *ValNumActiveBitsOffset = Builder.CreateAdd(
2671 ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset",
2672 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true);
2673 Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},
2674 {ValNumActiveBitsOffset, Start},
2675 /*FMFSource=*/nullptr, "iv.final");
2676
2677 auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub(
2678 IVFinal, Start, CurLoop->getName() + ".backedgetakencount",
2679 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true));
2680 // FIXME: or when the offset was `add nuw`
2681
2682 // We know loop's backedge-taken count, but what's loop's trip count?
2683 Value *LoopTripCount =
2684 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
2685 CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
2686 /*HasNSW=*/Bitwidth != 2);
2687
2688 // Step 2: Adjust the successor basic block to recieve the original
2689 // induction variable's final value instead of the orig. IV itself.
2690
2691 IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);
2692
2693 // Step 3: Rewrite the loop into a countable form, with canonical IV.
2694
2695 // The new canonical induction variable.
2696 Builder.SetInsertPoint(&LoopHeaderBB->front());
2697 auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
2698
2699 // The induction itself.
2700 Builder.SetInsertPoint(LoopHeaderBB->getFirstNonPHI());
2701 auto *CIVNext =
2702 Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next",
2703 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
2704
2705 // The loop trip count check.
2706 auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,
2707 CurLoop->getName() + ".ivcheck");
2708 auto *NewIVCheck = CIVCheck;
2709 if (InvertedCond) {
2710 NewIVCheck = Builder.CreateNot(CIVCheck);
2711 NewIVCheck->takeName(ValShiftedIsZero);
2712 }
2713
2714 // The original IV, but rebased to be an offset to the CIV.
2715 auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false,
2716 /*HasNSW=*/true); // FIXME: what about NUW?
2717 IVDePHId->takeName(IV);
2718
2719 // The loop terminator.
2720 Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
2721 Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);
2722 LoopHeaderBB->getTerminator()->eraseFromParent();
2723
2724 // Populate the IV PHI.
2725 CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
2726 CIV->addIncoming(CIVNext, LoopHeaderBB);
2727
2728 // Step 4: Forget the "non-computable" trip-count SCEV associated with the
2729 // loop. The loop would otherwise not be deleted even if it becomes empty.
2730
2731 SE->forgetLoop(CurLoop);
2732
2733 // Step 5: Try to cleanup the loop's body somewhat.
2734 IV->replaceAllUsesWith(IVDePHId);
2735 IV->eraseFromParent();
2736
2737 ValShiftedIsZero->replaceAllUsesWith(NewIVCheck);
2738 ValShiftedIsZero->eraseFromParent();
2739
2740 // Other passes will take care of actually deleting the loop if possible.
2741
2742 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-idiom")) { dbgs() << "loop-idiom" " shift-until-zero idiom optimized!\n"
; } } while (false)
;
2743
2744 ++NumShiftUntilZero;
2745 return MadeChange;
2746}