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