10b57cec5SDimitry Andric //===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass implements an idiom recognizer that transforms simple loops into a
100b57cec5SDimitry Andric // non-loop form.  In cases that this kicks in, it can be a significant
110b57cec5SDimitry Andric // performance win.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric // If compiling for code size we avoid idiom recognition if the resulting
140b57cec5SDimitry Andric // code could be larger than the code for the original loop. One way this could
150b57cec5SDimitry Andric // happen is if the loop is not removable after idiom recognition due to the
160b57cec5SDimitry Andric // presence of non-idiom instructions. The initial implementation of the
170b57cec5SDimitry Andric // heuristics applies to idioms in multi-block loops.
180b57cec5SDimitry Andric //
190b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
200b57cec5SDimitry Andric //
210b57cec5SDimitry Andric // TODO List:
220b57cec5SDimitry Andric //
230b57cec5SDimitry Andric // Future loop memory idioms to recognize:
24fe6060f1SDimitry Andric //   memcmp, strlen, etc.
250b57cec5SDimitry Andric // Future floating point idioms to recognize in -ffast-math mode:
260b57cec5SDimitry Andric //   fpowi
270b57cec5SDimitry Andric //
280b57cec5SDimitry Andric // This could recognize common matrix multiplies and dot product idioms and
290b57cec5SDimitry Andric // replace them with calls to BLAS (if linked in??).
300b57cec5SDimitry Andric //
310b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
340b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
350b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
360b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
370b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
380b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
390b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
400b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
410b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
420b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
430b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
44e8d8bef9SDimitry Andric #include "llvm/Analysis/CmpInstAnalysis.h"
450b57cec5SDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
460b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
470b57cec5SDimitry Andric #include "llvm/Analysis/LoopPass.h"
480b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
495ffd83dbSDimitry Andric #include "llvm/Analysis/MemorySSA.h"
505ffd83dbSDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
515ffd83dbSDimitry Andric #include "llvm/Analysis/MustExecute.h"
520b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
530b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
540b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
550b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
560b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
570b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
580b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
590b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
600b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
610b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
620b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
630b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
640b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
650b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
660b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
670b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
680b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
690b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
700b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
710b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
720b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
730b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
740b57cec5SDimitry Andric #include "llvm/IR/Module.h"
750b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
76e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h"
770b57cec5SDimitry Andric #include "llvm/IR/Type.h"
780b57cec5SDimitry Andric #include "llvm/IR/User.h"
790b57cec5SDimitry Andric #include "llvm/IR/Value.h"
800b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
810b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
820b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
830b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
84fe6060f1SDimitry Andric #include "llvm/Support/InstructionCost.h"
850b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
860b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BuildLibCalls.h"
870b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
880b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
895ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
900b57cec5SDimitry Andric #include <algorithm>
910b57cec5SDimitry Andric #include <cassert>
920b57cec5SDimitry Andric #include <cstdint>
930b57cec5SDimitry Andric #include <utility>
940b57cec5SDimitry Andric #include <vector>
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric using namespace llvm;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric #define DEBUG_TYPE "loop-idiom"
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
1010b57cec5SDimitry Andric STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
102fe6060f1SDimitry Andric STATISTIC(NumMemMove, "Number of memmove's formed from loop load+stores");
103e8d8bef9SDimitry Andric STATISTIC(
104e8d8bef9SDimitry Andric     NumShiftUntilBitTest,
105e8d8bef9SDimitry Andric     "Number of uncountable loops recognized as 'shift until bitttest' idiom");
106fe6060f1SDimitry Andric STATISTIC(NumShiftUntilZero,
107fe6060f1SDimitry Andric           "Number of uncountable loops recognized as 'shift until zero' idiom");
108e8d8bef9SDimitry Andric 
109e8d8bef9SDimitry Andric bool DisableLIRP::All;
110e8d8bef9SDimitry Andric static cl::opt<bool, true>
111e8d8bef9SDimitry Andric     DisableLIRPAll("disable-" DEBUG_TYPE "-all",
112e8d8bef9SDimitry Andric                    cl::desc("Options to disable Loop Idiom Recognize Pass."),
113e8d8bef9SDimitry Andric                    cl::location(DisableLIRP::All), cl::init(false),
114e8d8bef9SDimitry Andric                    cl::ReallyHidden);
115e8d8bef9SDimitry Andric 
116e8d8bef9SDimitry Andric bool DisableLIRP::Memset;
117e8d8bef9SDimitry Andric static cl::opt<bool, true>
118e8d8bef9SDimitry Andric     DisableLIRPMemset("disable-" DEBUG_TYPE "-memset",
119e8d8bef9SDimitry Andric                       cl::desc("Proceed with loop idiom recognize pass, but do "
120e8d8bef9SDimitry Andric                                "not convert loop(s) to memset."),
121e8d8bef9SDimitry Andric                       cl::location(DisableLIRP::Memset), cl::init(false),
122e8d8bef9SDimitry Andric                       cl::ReallyHidden);
123e8d8bef9SDimitry Andric 
124e8d8bef9SDimitry Andric bool DisableLIRP::Memcpy;
125e8d8bef9SDimitry Andric static cl::opt<bool, true>
126e8d8bef9SDimitry Andric     DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy",
127e8d8bef9SDimitry Andric                       cl::desc("Proceed with loop idiom recognize pass, but do "
128e8d8bef9SDimitry Andric                                "not convert loop(s) to memcpy."),
129e8d8bef9SDimitry Andric                       cl::location(DisableLIRP::Memcpy), cl::init(false),
130e8d8bef9SDimitry Andric                       cl::ReallyHidden);
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric static cl::opt<bool> UseLIRCodeSizeHeurs(
1330b57cec5SDimitry Andric     "use-lir-code-size-heurs",
1340b57cec5SDimitry Andric     cl::desc("Use loop idiom recognition code size heuristics when compiling"
1350b57cec5SDimitry Andric              "with -Os/-Oz"),
1360b57cec5SDimitry Andric     cl::init(true), cl::Hidden);
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric namespace {
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric class LoopIdiomRecognize {
1410b57cec5SDimitry Andric   Loop *CurLoop = nullptr;
1420b57cec5SDimitry Andric   AliasAnalysis *AA;
1430b57cec5SDimitry Andric   DominatorTree *DT;
1440b57cec5SDimitry Andric   LoopInfo *LI;
1450b57cec5SDimitry Andric   ScalarEvolution *SE;
1460b57cec5SDimitry Andric   TargetLibraryInfo *TLI;
1470b57cec5SDimitry Andric   const TargetTransformInfo *TTI;
1480b57cec5SDimitry Andric   const DataLayout *DL;
1490b57cec5SDimitry Andric   OptimizationRemarkEmitter &ORE;
1500b57cec5SDimitry Andric   bool ApplyCodeSizeHeuristics;
1515ffd83dbSDimitry Andric   std::unique_ptr<MemorySSAUpdater> MSSAU;
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric public:
LoopIdiomRecognize(AliasAnalysis * AA,DominatorTree * DT,LoopInfo * LI,ScalarEvolution * SE,TargetLibraryInfo * TLI,const TargetTransformInfo * TTI,MemorySSA * MSSA,const DataLayout * DL,OptimizationRemarkEmitter & ORE)1540b57cec5SDimitry Andric   explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
1550b57cec5SDimitry Andric                               LoopInfo *LI, ScalarEvolution *SE,
1560b57cec5SDimitry Andric                               TargetLibraryInfo *TLI,
1575ffd83dbSDimitry Andric                               const TargetTransformInfo *TTI, MemorySSA *MSSA,
158480093f4SDimitry Andric                               const DataLayout *DL,
1590b57cec5SDimitry Andric                               OptimizationRemarkEmitter &ORE)
1605ffd83dbSDimitry Andric       : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) {
1615ffd83dbSDimitry Andric     if (MSSA)
1625ffd83dbSDimitry Andric       MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
1635ffd83dbSDimitry Andric   }
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   bool runOnLoop(Loop *L);
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric private:
1680b57cec5SDimitry Andric   using StoreList = SmallVector<StoreInst *, 8>;
1690b57cec5SDimitry Andric   using StoreListMap = MapVector<Value *, StoreList>;
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   StoreListMap StoreRefsForMemset;
1720b57cec5SDimitry Andric   StoreListMap StoreRefsForMemsetPattern;
1730b57cec5SDimitry Andric   StoreList StoreRefsForMemcpy;
1740b57cec5SDimitry Andric   bool HasMemset;
1750b57cec5SDimitry Andric   bool HasMemsetPattern;
1760b57cec5SDimitry Andric   bool HasMemcpy;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   /// Return code for isLegalStore()
1790b57cec5SDimitry Andric   enum LegalStoreKind {
1800b57cec5SDimitry Andric     None = 0,
1810b57cec5SDimitry Andric     Memset,
1820b57cec5SDimitry Andric     MemsetPattern,
1830b57cec5SDimitry Andric     Memcpy,
1840b57cec5SDimitry Andric     UnorderedAtomicMemcpy,
1850b57cec5SDimitry Andric     DontUse // Dummy retval never to be used. Allows catching errors in retval
1860b57cec5SDimitry Andric             // handling.
1870b57cec5SDimitry Andric   };
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   /// \name Countable Loop Idiom Handling
1900b57cec5SDimitry Andric   /// @{
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   bool runOnCountableLoop();
1930b57cec5SDimitry Andric   bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
1940b57cec5SDimitry Andric                       SmallVectorImpl<BasicBlock *> &ExitBlocks);
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   void collectStores(BasicBlock *BB);
1970b57cec5SDimitry Andric   LegalStoreKind isLegalStore(StoreInst *SI);
1980b57cec5SDimitry Andric   enum class ForMemset { No, Yes };
1990b57cec5SDimitry Andric   bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
2000b57cec5SDimitry Andric                          ForMemset For);
201fe6060f1SDimitry Andric 
202fe6060f1SDimitry Andric   template <typename MemInst>
203fe6060f1SDimitry Andric   bool processLoopMemIntrinsic(
204fe6060f1SDimitry Andric       BasicBlock *BB,
205fe6060f1SDimitry Andric       bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
206fe6060f1SDimitry Andric       const SCEV *BECount);
207fe6060f1SDimitry Andric   bool processLoopMemCpy(MemCpyInst *MCI, const SCEV *BECount);
2080b57cec5SDimitry Andric   bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
2090b57cec5SDimitry Andric 
210349cc55cSDimitry Andric   bool processLoopStridedStore(Value *DestPtr, const SCEV *StoreSizeSCEV,
211480093f4SDimitry Andric                                MaybeAlign StoreAlignment, Value *StoredVal,
2120b57cec5SDimitry Andric                                Instruction *TheStore,
2130b57cec5SDimitry Andric                                SmallPtrSetImpl<Instruction *> &Stores,
2140b57cec5SDimitry Andric                                const SCEVAddRecExpr *Ev, const SCEV *BECount,
215349cc55cSDimitry Andric                                bool IsNegStride, bool IsLoopMemset = false);
2160b57cec5SDimitry Andric   bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
217fe6060f1SDimitry Andric   bool processLoopStoreOfLoopLoad(Value *DestPtr, Value *SourcePtr,
218349cc55cSDimitry Andric                                   const SCEV *StoreSize, MaybeAlign StoreAlign,
219fe6060f1SDimitry Andric                                   MaybeAlign LoadAlign, Instruction *TheStore,
220fe6060f1SDimitry Andric                                   Instruction *TheLoad,
221fe6060f1SDimitry Andric                                   const SCEVAddRecExpr *StoreEv,
222fe6060f1SDimitry Andric                                   const SCEVAddRecExpr *LoadEv,
223fe6060f1SDimitry Andric                                   const SCEV *BECount);
2240b57cec5SDimitry Andric   bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
2250b57cec5SDimitry Andric                                  bool IsLoopMemset = false);
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   /// @}
2280b57cec5SDimitry Andric   /// \name Noncountable Loop Idiom Handling
2290b57cec5SDimitry Andric   /// @{
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric   bool runOnNoncountableLoop();
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   bool recognizePopcount();
2340b57cec5SDimitry Andric   void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
2350b57cec5SDimitry Andric                                PHINode *CntPhi, Value *Var);
2360b57cec5SDimitry Andric   bool recognizeAndInsertFFS();  /// Find First Set: ctlz or cttz
2370b57cec5SDimitry Andric   void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB,
2380b57cec5SDimitry Andric                                 Instruction *CntInst, PHINode *CntPhi,
2390b57cec5SDimitry Andric                                 Value *Var, Instruction *DefX,
2400b57cec5SDimitry Andric                                 const DebugLoc &DL, bool ZeroCheck,
2410b57cec5SDimitry Andric                                 bool IsCntPhiUsedOutsideLoop);
2420b57cec5SDimitry Andric 
243e8d8bef9SDimitry Andric   bool recognizeShiftUntilBitTest();
244fe6060f1SDimitry Andric   bool recognizeShiftUntilZero();
245e8d8bef9SDimitry Andric 
2460b57cec5SDimitry Andric   /// @}
2470b57cec5SDimitry Andric };
2480b57cec5SDimitry Andric } // end anonymous namespace
2490b57cec5SDimitry Andric 
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater &)2500b57cec5SDimitry Andric PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
2510b57cec5SDimitry Andric                                               LoopStandardAnalysisResults &AR,
252480093f4SDimitry Andric                                               LPMUpdater &) {
253e8d8bef9SDimitry Andric   if (DisableLIRP::All)
254e8d8bef9SDimitry Andric     return PreservedAnalyses::all();
255e8d8bef9SDimitry Andric 
2560b57cec5SDimitry Andric   const auto *DL = &L.getHeader()->getModule()->getDataLayout();
2570b57cec5SDimitry Andric 
2585ffd83dbSDimitry Andric   // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
2595ffd83dbSDimitry Andric   // pass.  Function analyses need to be preserved across loop transformations
2605ffd83dbSDimitry Andric   // but ORE cannot be preserved (see comment before the pass definition).
2615ffd83dbSDimitry Andric   OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
2620b57cec5SDimitry Andric 
2635ffd83dbSDimitry Andric   LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI,
2645ffd83dbSDimitry Andric                          AR.MSSA, DL, ORE);
2650b57cec5SDimitry Andric   if (!LIR.runOnLoop(&L))
2660b57cec5SDimitry Andric     return PreservedAnalyses::all();
2670b57cec5SDimitry Andric 
2685ffd83dbSDimitry Andric   auto PA = getLoopPassPreservedAnalyses();
2695ffd83dbSDimitry Andric   if (AR.MSSA)
2705ffd83dbSDimitry Andric     PA.preserve<MemorySSAAnalysis>();
2715ffd83dbSDimitry Andric   return PA;
2720b57cec5SDimitry Andric }
2730b57cec5SDimitry Andric 
deleteDeadInstruction(Instruction * I)2740b57cec5SDimitry Andric static void deleteDeadInstruction(Instruction *I) {
27581ad6265SDimitry Andric   I->replaceAllUsesWith(PoisonValue::get(I->getType()));
2760b57cec5SDimitry Andric   I->eraseFromParent();
2770b57cec5SDimitry Andric }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2800b57cec5SDimitry Andric //
2810b57cec5SDimitry Andric //          Implementation of LoopIdiomRecognize
2820b57cec5SDimitry Andric //
2830b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2840b57cec5SDimitry Andric 
runOnLoop(Loop * L)2850b57cec5SDimitry Andric bool LoopIdiomRecognize::runOnLoop(Loop *L) {
2860b57cec5SDimitry Andric   CurLoop = L;
2870b57cec5SDimitry Andric   // If the loop could not be converted to canonical form, it must have an
2880b57cec5SDimitry Andric   // indirectbr in it, just give up.
2890b57cec5SDimitry Andric   if (!L->getLoopPreheader())
2900b57cec5SDimitry Andric     return false;
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   // Disable loop idiom recognition if the function's name is a common idiom.
2930b57cec5SDimitry Andric   StringRef Name = L->getHeader()->getParent()->getName();
294480093f4SDimitry Andric   if (Name == "memset" || Name == "memcpy")
2950b57cec5SDimitry Andric     return false;
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric   // Determine if code size heuristics need to be applied.
2980b57cec5SDimitry Andric   ApplyCodeSizeHeuristics =
2990b57cec5SDimitry Andric       L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   HasMemset = TLI->has(LibFunc_memset);
3020b57cec5SDimitry Andric   HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
3030b57cec5SDimitry Andric   HasMemcpy = TLI->has(LibFunc_memcpy);
3040b57cec5SDimitry Andric 
305480093f4SDimitry Andric   if (HasMemset || HasMemsetPattern || HasMemcpy)
3060b57cec5SDimitry Andric     if (SE->hasLoopInvariantBackedgeTakenCount(L))
3070b57cec5SDimitry Andric       return runOnCountableLoop();
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric   return runOnNoncountableLoop();
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric 
runOnCountableLoop()3120b57cec5SDimitry Andric bool LoopIdiomRecognize::runOnCountableLoop() {
3130b57cec5SDimitry Andric   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
3140b57cec5SDimitry Andric   assert(!isa<SCEVCouldNotCompute>(BECount) &&
3150b57cec5SDimitry Andric          "runOnCountableLoop() called on a loop without a predictable"
3160b57cec5SDimitry Andric          "backedge-taken count");
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   // If this loop executes exactly one time, then it should be peeled, not
3190b57cec5SDimitry Andric   // optimized by this pass.
3200b57cec5SDimitry Andric   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
3210b57cec5SDimitry Andric     if (BECst->getAPInt() == 0)
3220b57cec5SDimitry Andric       return false;
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> ExitBlocks;
3250b57cec5SDimitry Andric   CurLoop->getUniqueExitBlocks(ExitBlocks);
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
3280b57cec5SDimitry Andric                     << CurLoop->getHeader()->getParent()->getName()
3290b57cec5SDimitry Andric                     << "] Countable Loop %" << CurLoop->getHeader()->getName()
3300b57cec5SDimitry Andric                     << "\n");
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   // The following transforms hoist stores/memsets into the loop pre-header.
3335ffd83dbSDimitry Andric   // Give up if the loop has instructions that may throw.
3340b57cec5SDimitry Andric   SimpleLoopSafetyInfo SafetyInfo;
3350b57cec5SDimitry Andric   SafetyInfo.computeLoopSafetyInfo(CurLoop);
3360b57cec5SDimitry Andric   if (SafetyInfo.anyBlockMayThrow())
3375ffd83dbSDimitry Andric     return false;
3385ffd83dbSDimitry Andric 
3395ffd83dbSDimitry Andric   bool MadeChange = false;
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric   // Scan all the blocks in the loop that are not in subloops.
3420b57cec5SDimitry Andric   for (auto *BB : CurLoop->getBlocks()) {
3430b57cec5SDimitry Andric     // Ignore blocks in subloops.
3440b57cec5SDimitry Andric     if (LI->getLoopFor(BB) != CurLoop)
3450b57cec5SDimitry Andric       continue;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric     MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
3480b57cec5SDimitry Andric   }
3490b57cec5SDimitry Andric   return MadeChange;
3500b57cec5SDimitry Andric }
3510b57cec5SDimitry Andric 
getStoreStride(const SCEVAddRecExpr * StoreEv)3520b57cec5SDimitry Andric static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
3530b57cec5SDimitry Andric   const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
3540b57cec5SDimitry Andric   return ConstStride->getAPInt();
3550b57cec5SDimitry Andric }
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric /// getMemSetPatternValue - If a strided store of the specified value is safe to
3580b57cec5SDimitry Andric /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
3590b57cec5SDimitry Andric /// be passed in.  Otherwise, return null.
3600b57cec5SDimitry Andric ///
3610b57cec5SDimitry Andric /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
3620b57cec5SDimitry Andric /// just replicate their input array and then pass on to memset_pattern16.
getMemSetPatternValue(Value * V,const DataLayout * DL)3630b57cec5SDimitry Andric static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
3640b57cec5SDimitry Andric   // FIXME: This could check for UndefValue because it can be merged into any
3650b57cec5SDimitry Andric   // other valid pattern.
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   // If the value isn't a constant, we can't promote it to being in a constant
3680b57cec5SDimitry Andric   // array.  We could theoretically do a store to an alloca or something, but
3690b57cec5SDimitry Andric   // that doesn't seem worthwhile.
3700b57cec5SDimitry Andric   Constant *C = dyn_cast<Constant>(V);
371bdd1243dSDimitry Andric   if (!C || isa<ConstantExpr>(C))
3720b57cec5SDimitry Andric     return nullptr;
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   // Only handle simple values that are a power of two bytes in size.
3750b57cec5SDimitry Andric   uint64_t Size = DL->getTypeSizeInBits(V->getType());
3760b57cec5SDimitry Andric   if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
3770b57cec5SDimitry Andric     return nullptr;
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   // Don't care enough about darwin/ppc to implement this.
3800b57cec5SDimitry Andric   if (DL->isBigEndian())
3810b57cec5SDimitry Andric     return nullptr;
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   // Convert to size in bytes.
3840b57cec5SDimitry Andric   Size /= 8;
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
3870b57cec5SDimitry Andric   // if the top and bottom are the same (e.g. for vectors and large integers).
3880b57cec5SDimitry Andric   if (Size > 16)
3890b57cec5SDimitry Andric     return nullptr;
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric   // If the constant is exactly 16 bytes, just use it.
3920b57cec5SDimitry Andric   if (Size == 16)
3930b57cec5SDimitry Andric     return C;
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   // Otherwise, we'll use an array of the constants.
3960b57cec5SDimitry Andric   unsigned ArraySize = 16 / Size;
3970b57cec5SDimitry Andric   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
3980b57cec5SDimitry Andric   return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
3990b57cec5SDimitry Andric }
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric LoopIdiomRecognize::LegalStoreKind
isLegalStore(StoreInst * SI)4020b57cec5SDimitry Andric LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
4030b57cec5SDimitry Andric   // Don't touch volatile stores.
4040b57cec5SDimitry Andric   if (SI->isVolatile())
4050b57cec5SDimitry Andric     return LegalStoreKind::None;
4060b57cec5SDimitry Andric   // We only want simple or unordered-atomic stores.
4070b57cec5SDimitry Andric   if (!SI->isUnordered())
4080b57cec5SDimitry Andric     return LegalStoreKind::None;
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   // Avoid merging nontemporal stores.
4110b57cec5SDimitry Andric   if (SI->getMetadata(LLVMContext::MD_nontemporal))
4120b57cec5SDimitry Andric     return LegalStoreKind::None;
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric   Value *StoredVal = SI->getValueOperand();
4150b57cec5SDimitry Andric   Value *StorePtr = SI->getPointerOperand();
4160b57cec5SDimitry Andric 
417e8d8bef9SDimitry Andric   // Don't convert stores of non-integral pointer types to memsets (which stores
418e8d8bef9SDimitry Andric   // integers).
419e8d8bef9SDimitry Andric   if (DL->isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
420e8d8bef9SDimitry Andric     return LegalStoreKind::None;
421e8d8bef9SDimitry Andric 
4220b57cec5SDimitry Andric   // Reject stores that are so large that they overflow an unsigned.
423e8d8bef9SDimitry Andric   // When storing out scalable vectors we bail out for now, since the code
424e8d8bef9SDimitry Andric   // below currently only works for constant strides.
425e8d8bef9SDimitry Andric   TypeSize SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
426bdd1243dSDimitry Andric   if (SizeInBits.isScalable() || (SizeInBits.getFixedValue() & 7) ||
427bdd1243dSDimitry Andric       (SizeInBits.getFixedValue() >> 32) != 0)
4280b57cec5SDimitry Andric     return LegalStoreKind::None;
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   // See if the pointer expression is an AddRec like {base,+,1} on the current
4310b57cec5SDimitry Andric   // loop, which indicates a strided store.  If we have something else, it's a
4320b57cec5SDimitry Andric   // random store we can't handle.
4330b57cec5SDimitry Andric   const SCEVAddRecExpr *StoreEv =
4340b57cec5SDimitry Andric       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
4350b57cec5SDimitry Andric   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
4360b57cec5SDimitry Andric     return LegalStoreKind::None;
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   // Check to see if we have a constant stride.
4390b57cec5SDimitry Andric   if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
4400b57cec5SDimitry Andric     return LegalStoreKind::None;
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric   // See if the store can be turned into a memset.
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   // If the stored value is a byte-wise value (like i32 -1), then it may be
4450b57cec5SDimitry Andric   // turned into a memset of i8 -1, assuming that all the consecutive bytes
4460b57cec5SDimitry Andric   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
4470b57cec5SDimitry Andric   // but it can be turned into memset_pattern if the target supports it.
4480b57cec5SDimitry Andric   Value *SplatValue = isBytewiseValue(StoredVal, *DL);
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   // Note: memset and memset_pattern on unordered-atomic is yet not supported
4510b57cec5SDimitry Andric   bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   // If we're allowed to form a memset, and the stored value would be
4540b57cec5SDimitry Andric   // acceptable for memset, use it.
455e8d8bef9SDimitry Andric   if (!UnorderedAtomic && HasMemset && SplatValue && !DisableLIRP::Memset &&
4560b57cec5SDimitry Andric       // Verify that the stored value is loop invariant.  If not, we can't
4570b57cec5SDimitry Andric       // promote the memset.
4580b57cec5SDimitry Andric       CurLoop->isLoopInvariant(SplatValue)) {
4590b57cec5SDimitry Andric     // It looks like we can use SplatValue.
4600b57cec5SDimitry Andric     return LegalStoreKind::Memset;
461fe6060f1SDimitry Andric   }
462fe6060f1SDimitry Andric   if (!UnorderedAtomic && HasMemsetPattern && !DisableLIRP::Memset &&
4630b57cec5SDimitry Andric       // Don't create memset_pattern16s with address spaces.
4640b57cec5SDimitry Andric       StorePtr->getType()->getPointerAddressSpace() == 0 &&
465fe6060f1SDimitry Andric       getMemSetPatternValue(StoredVal, DL)) {
4660b57cec5SDimitry Andric     // It looks like we can use PatternValue!
4670b57cec5SDimitry Andric     return LegalStoreKind::MemsetPattern;
4680b57cec5SDimitry Andric   }
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   // Otherwise, see if the store can be turned into a memcpy.
471e8d8bef9SDimitry Andric   if (HasMemcpy && !DisableLIRP::Memcpy) {
4720b57cec5SDimitry Andric     // Check to see if the stride matches the size of the store.  If so, then we
4730b57cec5SDimitry Andric     // know that every byte is touched in the loop.
4740b57cec5SDimitry Andric     APInt Stride = getStoreStride(StoreEv);
4750b57cec5SDimitry Andric     unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
4760b57cec5SDimitry Andric     if (StoreSize != Stride && StoreSize != -Stride)
4770b57cec5SDimitry Andric       return LegalStoreKind::None;
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric     // The store must be feeding a non-volatile load.
4800b57cec5SDimitry Andric     LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric     // Only allow non-volatile loads
4830b57cec5SDimitry Andric     if (!LI || LI->isVolatile())
4840b57cec5SDimitry Andric       return LegalStoreKind::None;
4850b57cec5SDimitry Andric     // Only allow simple or unordered-atomic loads
4860b57cec5SDimitry Andric     if (!LI->isUnordered())
4870b57cec5SDimitry Andric       return LegalStoreKind::None;
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric     // See if the pointer expression is an AddRec like {base,+,1} on the current
4900b57cec5SDimitry Andric     // loop, which indicates a strided load.  If we have something else, it's a
4910b57cec5SDimitry Andric     // random load we can't handle.
4920b57cec5SDimitry Andric     const SCEVAddRecExpr *LoadEv =
4930b57cec5SDimitry Andric         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
4940b57cec5SDimitry Andric     if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
4950b57cec5SDimitry Andric       return LegalStoreKind::None;
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric     // The store and load must share the same stride.
4980b57cec5SDimitry Andric     if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
4990b57cec5SDimitry Andric       return LegalStoreKind::None;
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric     // Success.  This store can be converted into a memcpy.
5020b57cec5SDimitry Andric     UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
5030b57cec5SDimitry Andric     return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
5040b57cec5SDimitry Andric                            : LegalStoreKind::Memcpy;
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric   // This store can't be transformed into a memset/memcpy.
5070b57cec5SDimitry Andric   return LegalStoreKind::None;
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric 
collectStores(BasicBlock * BB)5100b57cec5SDimitry Andric void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
5110b57cec5SDimitry Andric   StoreRefsForMemset.clear();
5120b57cec5SDimitry Andric   StoreRefsForMemsetPattern.clear();
5130b57cec5SDimitry Andric   StoreRefsForMemcpy.clear();
5140b57cec5SDimitry Andric   for (Instruction &I : *BB) {
5150b57cec5SDimitry Andric     StoreInst *SI = dyn_cast<StoreInst>(&I);
5160b57cec5SDimitry Andric     if (!SI)
5170b57cec5SDimitry Andric       continue;
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric     // Make sure this is a strided store with a constant stride.
5200b57cec5SDimitry Andric     switch (isLegalStore(SI)) {
5210b57cec5SDimitry Andric     case LegalStoreKind::None:
5220b57cec5SDimitry Andric       // Nothing to do
5230b57cec5SDimitry Andric       break;
5240b57cec5SDimitry Andric     case LegalStoreKind::Memset: {
5250b57cec5SDimitry Andric       // Find the base pointer.
526e8d8bef9SDimitry Andric       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
5270b57cec5SDimitry Andric       StoreRefsForMemset[Ptr].push_back(SI);
5280b57cec5SDimitry Andric     } break;
5290b57cec5SDimitry Andric     case LegalStoreKind::MemsetPattern: {
5300b57cec5SDimitry Andric       // Find the base pointer.
531e8d8bef9SDimitry Andric       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
5320b57cec5SDimitry Andric       StoreRefsForMemsetPattern[Ptr].push_back(SI);
5330b57cec5SDimitry Andric     } break;
5340b57cec5SDimitry Andric     case LegalStoreKind::Memcpy:
5350b57cec5SDimitry Andric     case LegalStoreKind::UnorderedAtomicMemcpy:
5360b57cec5SDimitry Andric       StoreRefsForMemcpy.push_back(SI);
5370b57cec5SDimitry Andric       break;
5380b57cec5SDimitry Andric     default:
5390b57cec5SDimitry Andric       assert(false && "unhandled return value");
5400b57cec5SDimitry Andric       break;
5410b57cec5SDimitry Andric     }
5420b57cec5SDimitry Andric   }
5430b57cec5SDimitry Andric }
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric /// runOnLoopBlock - Process the specified block, which lives in a counted loop
5460b57cec5SDimitry Andric /// with the specified backedge count.  This block is known to be in the current
5470b57cec5SDimitry Andric /// loop and not in any subloops.
runOnLoopBlock(BasicBlock * BB,const SCEV * BECount,SmallVectorImpl<BasicBlock * > & ExitBlocks)5480b57cec5SDimitry Andric bool LoopIdiomRecognize::runOnLoopBlock(
5490b57cec5SDimitry Andric     BasicBlock *BB, const SCEV *BECount,
5500b57cec5SDimitry Andric     SmallVectorImpl<BasicBlock *> &ExitBlocks) {
5510b57cec5SDimitry Andric   // We can only promote stores in this block if they are unconditionally
5520b57cec5SDimitry Andric   // executed in the loop.  For a block to be unconditionally executed, it has
5530b57cec5SDimitry Andric   // to dominate all the exit blocks of the loop.  Verify this now.
554349cc55cSDimitry Andric   for (BasicBlock *ExitBlock : ExitBlocks)
555349cc55cSDimitry Andric     if (!DT->dominates(BB, ExitBlock))
5560b57cec5SDimitry Andric       return false;
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   bool MadeChange = false;
5590b57cec5SDimitry Andric   // Look for store instructions, which may be optimized to memset/memcpy.
5600b57cec5SDimitry Andric   collectStores(BB);
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   // Look for a single store or sets of stores with a common base, which can be
5630b57cec5SDimitry Andric   // optimized into a memset (memset_pattern).  The latter most commonly happens
5640b57cec5SDimitry Andric   // with structs and handunrolled loops.
5650b57cec5SDimitry Andric   for (auto &SL : StoreRefsForMemset)
5660b57cec5SDimitry Andric     MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   for (auto &SL : StoreRefsForMemsetPattern)
5690b57cec5SDimitry Andric     MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   // Optimize the store into a memcpy, if it feeds an similarly strided load.
5720b57cec5SDimitry Andric   for (auto &SI : StoreRefsForMemcpy)
5730b57cec5SDimitry Andric     MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
5740b57cec5SDimitry Andric 
575fe6060f1SDimitry Andric   MadeChange |= processLoopMemIntrinsic<MemCpyInst>(
576fe6060f1SDimitry Andric       BB, &LoopIdiomRecognize::processLoopMemCpy, BECount);
577fe6060f1SDimitry Andric   MadeChange |= processLoopMemIntrinsic<MemSetInst>(
578fe6060f1SDimitry Andric       BB, &LoopIdiomRecognize::processLoopMemSet, BECount);
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   return MadeChange;
5810b57cec5SDimitry Andric }
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric /// See if this store(s) can be promoted to a memset.
processLoopStores(SmallVectorImpl<StoreInst * > & SL,const SCEV * BECount,ForMemset For)5840b57cec5SDimitry Andric bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
5850b57cec5SDimitry Andric                                            const SCEV *BECount, ForMemset For) {
5860b57cec5SDimitry Andric   // Try to find consecutive stores that can be transformed into memsets.
5870b57cec5SDimitry Andric   SetVector<StoreInst *> Heads, Tails;
5880b57cec5SDimitry Andric   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric   // Do a quadratic search on all of the given stores and find
5910b57cec5SDimitry Andric   // all of the pairs of stores that follow each other.
5920b57cec5SDimitry Andric   SmallVector<unsigned, 16> IndexQueue;
5930b57cec5SDimitry Andric   for (unsigned i = 0, e = SL.size(); i < e; ++i) {
5940b57cec5SDimitry Andric     assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric     Value *FirstStoredVal = SL[i]->getValueOperand();
5970b57cec5SDimitry Andric     Value *FirstStorePtr = SL[i]->getPointerOperand();
5980b57cec5SDimitry Andric     const SCEVAddRecExpr *FirstStoreEv =
5990b57cec5SDimitry Andric         cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
6000b57cec5SDimitry Andric     APInt FirstStride = getStoreStride(FirstStoreEv);
6010b57cec5SDimitry Andric     unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric     // See if we can optimize just this store in isolation.
6040b57cec5SDimitry Andric     if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
6050b57cec5SDimitry Andric       Heads.insert(SL[i]);
6060b57cec5SDimitry Andric       continue;
6070b57cec5SDimitry Andric     }
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric     Value *FirstSplatValue = nullptr;
6100b57cec5SDimitry Andric     Constant *FirstPatternValue = nullptr;
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric     if (For == ForMemset::Yes)
6130b57cec5SDimitry Andric       FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL);
6140b57cec5SDimitry Andric     else
6150b57cec5SDimitry Andric       FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric     assert((FirstSplatValue || FirstPatternValue) &&
6180b57cec5SDimitry Andric            "Expected either splat value or pattern value.");
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric     IndexQueue.clear();
6210b57cec5SDimitry Andric     // If a store has multiple consecutive store candidates, search Stores
6220b57cec5SDimitry Andric     // array according to the sequence: from i+1 to e, then from i-1 to 0.
6230b57cec5SDimitry Andric     // This is because usually pairing with immediate succeeding or preceding
6240b57cec5SDimitry Andric     // candidate create the best chance to find memset opportunity.
6250b57cec5SDimitry Andric     unsigned j = 0;
6260b57cec5SDimitry Andric     for (j = i + 1; j < e; ++j)
6270b57cec5SDimitry Andric       IndexQueue.push_back(j);
6280b57cec5SDimitry Andric     for (j = i; j > 0; --j)
6290b57cec5SDimitry Andric       IndexQueue.push_back(j - 1);
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric     for (auto &k : IndexQueue) {
6320b57cec5SDimitry Andric       assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
6330b57cec5SDimitry Andric       Value *SecondStorePtr = SL[k]->getPointerOperand();
6340b57cec5SDimitry Andric       const SCEVAddRecExpr *SecondStoreEv =
6350b57cec5SDimitry Andric           cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
6360b57cec5SDimitry Andric       APInt SecondStride = getStoreStride(SecondStoreEv);
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric       if (FirstStride != SecondStride)
6390b57cec5SDimitry Andric         continue;
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric       Value *SecondStoredVal = SL[k]->getValueOperand();
6420b57cec5SDimitry Andric       Value *SecondSplatValue = nullptr;
6430b57cec5SDimitry Andric       Constant *SecondPatternValue = nullptr;
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric       if (For == ForMemset::Yes)
6460b57cec5SDimitry Andric         SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL);
6470b57cec5SDimitry Andric       else
6480b57cec5SDimitry Andric         SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric       assert((SecondSplatValue || SecondPatternValue) &&
6510b57cec5SDimitry Andric              "Expected either splat value or pattern value.");
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric       if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
6540b57cec5SDimitry Andric         if (For == ForMemset::Yes) {
6550b57cec5SDimitry Andric           if (isa<UndefValue>(FirstSplatValue))
6560b57cec5SDimitry Andric             FirstSplatValue = SecondSplatValue;
6570b57cec5SDimitry Andric           if (FirstSplatValue != SecondSplatValue)
6580b57cec5SDimitry Andric             continue;
6590b57cec5SDimitry Andric         } else {
6600b57cec5SDimitry Andric           if (isa<UndefValue>(FirstPatternValue))
6610b57cec5SDimitry Andric             FirstPatternValue = SecondPatternValue;
6620b57cec5SDimitry Andric           if (FirstPatternValue != SecondPatternValue)
6630b57cec5SDimitry Andric             continue;
6640b57cec5SDimitry Andric         }
6650b57cec5SDimitry Andric         Tails.insert(SL[k]);
6660b57cec5SDimitry Andric         Heads.insert(SL[i]);
6670b57cec5SDimitry Andric         ConsecutiveChain[SL[i]] = SL[k];
6680b57cec5SDimitry Andric         break;
6690b57cec5SDimitry Andric       }
6700b57cec5SDimitry Andric     }
6710b57cec5SDimitry Andric   }
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric   // We may run into multiple chains that merge into a single chain. We mark the
6740b57cec5SDimitry Andric   // stores that we transformed so that we don't visit the same store twice.
6750b57cec5SDimitry Andric   SmallPtrSet<Value *, 16> TransformedStores;
6760b57cec5SDimitry Andric   bool Changed = false;
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric   // For stores that start but don't end a link in the chain:
679349cc55cSDimitry Andric   for (StoreInst *I : Heads) {
680349cc55cSDimitry Andric     if (Tails.count(I))
6810b57cec5SDimitry Andric       continue;
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric     // We found a store instr that starts a chain. Now follow the chain and try
6840b57cec5SDimitry Andric     // to transform it.
6850b57cec5SDimitry Andric     SmallPtrSet<Instruction *, 8> AdjacentStores;
6860b57cec5SDimitry Andric     StoreInst *HeadStore = I;
6870b57cec5SDimitry Andric     unsigned StoreSize = 0;
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric     // Collect the chain into a list.
6900b57cec5SDimitry Andric     while (Tails.count(I) || Heads.count(I)) {
6910b57cec5SDimitry Andric       if (TransformedStores.count(I))
6920b57cec5SDimitry Andric         break;
6930b57cec5SDimitry Andric       AdjacentStores.insert(I);
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric       StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
6960b57cec5SDimitry Andric       // Move to the next value in the chain.
6970b57cec5SDimitry Andric       I = ConsecutiveChain[I];
6980b57cec5SDimitry Andric     }
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric     Value *StoredVal = HeadStore->getValueOperand();
7010b57cec5SDimitry Andric     Value *StorePtr = HeadStore->getPointerOperand();
7020b57cec5SDimitry Andric     const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
7030b57cec5SDimitry Andric     APInt Stride = getStoreStride(StoreEv);
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric     // Check to see if the stride matches the size of the stores.  If so, then
7060b57cec5SDimitry Andric     // we know that every byte is touched in the loop.
7070b57cec5SDimitry Andric     if (StoreSize != Stride && StoreSize != -Stride)
7080b57cec5SDimitry Andric       continue;
7090b57cec5SDimitry Andric 
710349cc55cSDimitry Andric     bool IsNegStride = StoreSize == -Stride;
7110b57cec5SDimitry Andric 
712349cc55cSDimitry Andric     Type *IntIdxTy = DL->getIndexType(StorePtr->getType());
713349cc55cSDimitry Andric     const SCEV *StoreSizeSCEV = SE->getConstant(IntIdxTy, StoreSize);
714349cc55cSDimitry Andric     if (processLoopStridedStore(StorePtr, StoreSizeSCEV,
7150eae32dcSDimitry Andric                                 MaybeAlign(HeadStore->getAlign()), StoredVal,
7160eae32dcSDimitry Andric                                 HeadStore, AdjacentStores, StoreEv, BECount,
7170eae32dcSDimitry Andric                                 IsNegStride)) {
7180b57cec5SDimitry Andric       TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
7190b57cec5SDimitry Andric       Changed = true;
7200b57cec5SDimitry Andric     }
7210b57cec5SDimitry Andric   }
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   return Changed;
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric 
726fe6060f1SDimitry Andric /// processLoopMemIntrinsic - Template function for calling different processor
72781ad6265SDimitry Andric /// functions based on mem intrinsic type.
728fe6060f1SDimitry Andric template <typename MemInst>
processLoopMemIntrinsic(BasicBlock * BB,bool (LoopIdiomRecognize::* Processor)(MemInst *,const SCEV *),const SCEV * BECount)729fe6060f1SDimitry Andric bool LoopIdiomRecognize::processLoopMemIntrinsic(
730fe6060f1SDimitry Andric     BasicBlock *BB,
731fe6060f1SDimitry Andric     bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
732fe6060f1SDimitry Andric     const SCEV *BECount) {
733fe6060f1SDimitry Andric   bool MadeChange = false;
734fe6060f1SDimitry Andric   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
735fe6060f1SDimitry Andric     Instruction *Inst = &*I++;
736fe6060f1SDimitry Andric     // Look for memory instructions, which may be optimized to a larger one.
737fe6060f1SDimitry Andric     if (MemInst *MI = dyn_cast<MemInst>(Inst)) {
738fe6060f1SDimitry Andric       WeakTrackingVH InstPtr(&*I);
739fe6060f1SDimitry Andric       if (!(this->*Processor)(MI, BECount))
740fe6060f1SDimitry Andric         continue;
741fe6060f1SDimitry Andric       MadeChange = true;
742fe6060f1SDimitry Andric 
743fe6060f1SDimitry Andric       // If processing the instruction invalidated our iterator, start over from
744fe6060f1SDimitry Andric       // the top of the block.
745fe6060f1SDimitry Andric       if (!InstPtr)
746fe6060f1SDimitry Andric         I = BB->begin();
747fe6060f1SDimitry Andric     }
748fe6060f1SDimitry Andric   }
749fe6060f1SDimitry Andric   return MadeChange;
750fe6060f1SDimitry Andric }
751fe6060f1SDimitry Andric 
752fe6060f1SDimitry Andric /// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy
processLoopMemCpy(MemCpyInst * MCI,const SCEV * BECount)753fe6060f1SDimitry Andric bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI,
754fe6060f1SDimitry Andric                                            const SCEV *BECount) {
755fe6060f1SDimitry Andric   // We can only handle non-volatile memcpys with a constant size.
756fe6060f1SDimitry Andric   if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength()))
757fe6060f1SDimitry Andric     return false;
758fe6060f1SDimitry Andric 
759fe6060f1SDimitry Andric   // If we're not allowed to hack on memcpy, we fail.
760fe6060f1SDimitry Andric   if ((!HasMemcpy && !isa<MemCpyInlineInst>(MCI)) || DisableLIRP::Memcpy)
761fe6060f1SDimitry Andric     return false;
762fe6060f1SDimitry Andric 
763fe6060f1SDimitry Andric   Value *Dest = MCI->getDest();
764fe6060f1SDimitry Andric   Value *Source = MCI->getSource();
765fe6060f1SDimitry Andric   if (!Dest || !Source)
766fe6060f1SDimitry Andric     return false;
767fe6060f1SDimitry Andric 
768fe6060f1SDimitry Andric   // See if the load and store pointer expressions are AddRec like {base,+,1} on
769fe6060f1SDimitry Andric   // the current loop, which indicates a strided load and store.  If we have
770fe6060f1SDimitry Andric   // something else, it's a random load or store we can't handle.
771fe6060f1SDimitry Andric   const SCEVAddRecExpr *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Dest));
772fe6060f1SDimitry Andric   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
773fe6060f1SDimitry Andric     return false;
774fe6060f1SDimitry Andric   const SCEVAddRecExpr *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Source));
775fe6060f1SDimitry Andric   if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
776fe6060f1SDimitry Andric     return false;
777fe6060f1SDimitry Andric 
778fe6060f1SDimitry Andric   // Reject memcpys that are so large that they overflow an unsigned.
779fe6060f1SDimitry Andric   uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue();
780fe6060f1SDimitry Andric   if ((SizeInBytes >> 32) != 0)
781fe6060f1SDimitry Andric     return false;
782fe6060f1SDimitry Andric 
783fe6060f1SDimitry Andric   // Check if the stride matches the size of the memcpy. If so, then we know
784fe6060f1SDimitry Andric   // that every byte is touched in the loop.
785349cc55cSDimitry Andric   const SCEVConstant *ConstStoreStride =
786fe6060f1SDimitry Andric       dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
787349cc55cSDimitry Andric   const SCEVConstant *ConstLoadStride =
788fe6060f1SDimitry Andric       dyn_cast<SCEVConstant>(LoadEv->getOperand(1));
789349cc55cSDimitry Andric   if (!ConstStoreStride || !ConstLoadStride)
790fe6060f1SDimitry Andric     return false;
791fe6060f1SDimitry Andric 
792349cc55cSDimitry Andric   APInt StoreStrideValue = ConstStoreStride->getAPInt();
793349cc55cSDimitry Andric   APInt LoadStrideValue = ConstLoadStride->getAPInt();
794fe6060f1SDimitry Andric   // Huge stride value - give up
795fe6060f1SDimitry Andric   if (StoreStrideValue.getBitWidth() > 64 || LoadStrideValue.getBitWidth() > 64)
796fe6060f1SDimitry Andric     return false;
797fe6060f1SDimitry Andric 
798fe6060f1SDimitry Andric   if (SizeInBytes != StoreStrideValue && SizeInBytes != -StoreStrideValue) {
799fe6060f1SDimitry Andric     ORE.emit([&]() {
800fe6060f1SDimitry Andric       return OptimizationRemarkMissed(DEBUG_TYPE, "SizeStrideUnequal", MCI)
801fe6060f1SDimitry Andric              << ore::NV("Inst", "memcpy") << " in "
802fe6060f1SDimitry Andric              << ore::NV("Function", MCI->getFunction())
803349cc55cSDimitry Andric              << " function will not be hoisted: "
804fe6060f1SDimitry Andric              << ore::NV("Reason", "memcpy size is not equal to stride");
805fe6060f1SDimitry Andric     });
806fe6060f1SDimitry Andric     return false;
807fe6060f1SDimitry Andric   }
808fe6060f1SDimitry Andric 
809fe6060f1SDimitry Andric   int64_t StoreStrideInt = StoreStrideValue.getSExtValue();
810fe6060f1SDimitry Andric   int64_t LoadStrideInt = LoadStrideValue.getSExtValue();
811fe6060f1SDimitry Andric   // Check if the load stride matches the store stride.
812fe6060f1SDimitry Andric   if (StoreStrideInt != LoadStrideInt)
813fe6060f1SDimitry Andric     return false;
814fe6060f1SDimitry Andric 
815349cc55cSDimitry Andric   return processLoopStoreOfLoopLoad(
816349cc55cSDimitry Andric       Dest, Source, SE->getConstant(Dest->getType(), SizeInBytes),
817349cc55cSDimitry Andric       MCI->getDestAlign(), MCI->getSourceAlign(), MCI, MCI, StoreEv, LoadEv,
818349cc55cSDimitry Andric       BECount);
819fe6060f1SDimitry Andric }
820fe6060f1SDimitry Andric 
8210b57cec5SDimitry Andric /// processLoopMemSet - See if this memset can be promoted to a large memset.
processLoopMemSet(MemSetInst * MSI,const SCEV * BECount)8220b57cec5SDimitry Andric bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
8230b57cec5SDimitry Andric                                            const SCEV *BECount) {
824349cc55cSDimitry Andric   // We can only handle non-volatile memsets.
825349cc55cSDimitry Andric   if (MSI->isVolatile())
8260b57cec5SDimitry Andric     return false;
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   // If we're not allowed to hack on memset, we fail.
829fe6060f1SDimitry Andric   if (!HasMemset || DisableLIRP::Memset)
8300b57cec5SDimitry Andric     return false;
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   Value *Pointer = MSI->getDest();
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   // See if the pointer expression is an AddRec like {base,+,1} on the current
8350b57cec5SDimitry Andric   // loop, which indicates a strided store.  If we have something else, it's a
8360b57cec5SDimitry Andric   // random store we can't handle.
8370b57cec5SDimitry Andric   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
838349cc55cSDimitry Andric   if (!Ev || Ev->getLoop() != CurLoop)
839349cc55cSDimitry Andric     return false;
840349cc55cSDimitry Andric   if (!Ev->isAffine()) {
841349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "  Pointer is not affine, abort\n");
842349cc55cSDimitry Andric     return false;
843349cc55cSDimitry Andric   }
844349cc55cSDimitry Andric 
845349cc55cSDimitry Andric   const SCEV *PointerStrideSCEV = Ev->getOperand(1);
846349cc55cSDimitry Andric   const SCEV *MemsetSizeSCEV = SE->getSCEV(MSI->getLength());
847349cc55cSDimitry Andric   if (!PointerStrideSCEV || !MemsetSizeSCEV)
8480b57cec5SDimitry Andric     return false;
8490b57cec5SDimitry Andric 
850349cc55cSDimitry Andric   bool IsNegStride = false;
851349cc55cSDimitry Andric   const bool IsConstantSize = isa<ConstantInt>(MSI->getLength());
852349cc55cSDimitry Andric 
853349cc55cSDimitry Andric   if (IsConstantSize) {
854349cc55cSDimitry Andric     // Memset size is constant.
855349cc55cSDimitry Andric     // Check if the pointer stride matches the memset size. If so, then
856349cc55cSDimitry Andric     // we know that every byte is touched in the loop.
857349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "  memset size is constant\n");
8580b57cec5SDimitry Andric     uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
8590b57cec5SDimitry Andric     const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
8600b57cec5SDimitry Andric     if (!ConstStride)
8610b57cec5SDimitry Andric       return false;
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric     APInt Stride = ConstStride->getAPInt();
8640b57cec5SDimitry Andric     if (SizeInBytes != Stride && SizeInBytes != -Stride)
8650b57cec5SDimitry Andric       return false;
8660b57cec5SDimitry Andric 
867349cc55cSDimitry Andric     IsNegStride = SizeInBytes == -Stride;
868349cc55cSDimitry Andric   } else {
869349cc55cSDimitry Andric     // Memset size is non-constant.
870349cc55cSDimitry Andric     // Check if the pointer stride matches the memset size.
871349cc55cSDimitry Andric     // To be conservative, the pass would not promote pointers that aren't in
872349cc55cSDimitry Andric     // address space zero. Also, the pass only handles memset length and stride
873349cc55cSDimitry Andric     // that are invariant for the top level loop.
874349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "  memset size is non-constant\n");
875349cc55cSDimitry Andric     if (Pointer->getType()->getPointerAddressSpace() != 0) {
876349cc55cSDimitry Andric       LLVM_DEBUG(dbgs() << "  pointer is not in address space zero, "
877349cc55cSDimitry Andric                         << "abort\n");
878349cc55cSDimitry Andric       return false;
879349cc55cSDimitry Andric     }
880349cc55cSDimitry Andric     if (!SE->isLoopInvariant(MemsetSizeSCEV, CurLoop)) {
881349cc55cSDimitry Andric       LLVM_DEBUG(dbgs() << "  memset size is not a loop-invariant, "
882349cc55cSDimitry Andric                         << "abort\n");
883349cc55cSDimitry Andric       return false;
884349cc55cSDimitry Andric     }
885349cc55cSDimitry Andric 
886349cc55cSDimitry Andric     // Compare positive direction PointerStrideSCEV with MemsetSizeSCEV
887349cc55cSDimitry Andric     IsNegStride = PointerStrideSCEV->isNonConstantNegative();
888349cc55cSDimitry Andric     const SCEV *PositiveStrideSCEV =
889349cc55cSDimitry Andric         IsNegStride ? SE->getNegativeSCEV(PointerStrideSCEV)
890349cc55cSDimitry Andric                     : PointerStrideSCEV;
891349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "  MemsetSizeSCEV: " << *MemsetSizeSCEV << "\n"
892349cc55cSDimitry Andric                       << "  PositiveStrideSCEV: " << *PositiveStrideSCEV
893349cc55cSDimitry Andric                       << "\n");
894349cc55cSDimitry Andric 
895349cc55cSDimitry Andric     if (PositiveStrideSCEV != MemsetSizeSCEV) {
8960eae32dcSDimitry Andric       // If an expression is covered by the loop guard, compare again and
8970eae32dcSDimitry Andric       // proceed with optimization if equal.
8980eae32dcSDimitry Andric       const SCEV *FoldedPositiveStride =
8990eae32dcSDimitry Andric           SE->applyLoopGuards(PositiveStrideSCEV, CurLoop);
9000eae32dcSDimitry Andric       const SCEV *FoldedMemsetSize =
9010eae32dcSDimitry Andric           SE->applyLoopGuards(MemsetSizeSCEV, CurLoop);
9020eae32dcSDimitry Andric 
9030eae32dcSDimitry Andric       LLVM_DEBUG(dbgs() << "  Try to fold SCEV based on loop guard\n"
9040eae32dcSDimitry Andric                         << "    FoldedMemsetSize: " << *FoldedMemsetSize << "\n"
9050eae32dcSDimitry Andric                         << "    FoldedPositiveStride: " << *FoldedPositiveStride
9060eae32dcSDimitry Andric                         << "\n");
9070eae32dcSDimitry Andric 
9080eae32dcSDimitry Andric       if (FoldedPositiveStride != FoldedMemsetSize) {
909349cc55cSDimitry Andric         LLVM_DEBUG(dbgs() << "  SCEV don't match, abort\n");
910349cc55cSDimitry Andric         return false;
911349cc55cSDimitry Andric       }
912349cc55cSDimitry Andric     }
9130eae32dcSDimitry Andric   }
914349cc55cSDimitry Andric 
9150b57cec5SDimitry Andric   // Verify that the memset value is loop invariant.  If not, we can't promote
9160b57cec5SDimitry Andric   // the memset.
9170b57cec5SDimitry Andric   Value *SplatValue = MSI->getValue();
9180b57cec5SDimitry Andric   if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
9190b57cec5SDimitry Andric     return false;
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 1> MSIs;
9220b57cec5SDimitry Andric   MSIs.insert(MSI);
923349cc55cSDimitry Andric   return processLoopStridedStore(Pointer, SE->getSCEV(MSI->getLength()),
92481ad6265SDimitry Andric                                  MSI->getDestAlign(), SplatValue, MSI, MSIs, Ev,
92581ad6265SDimitry Andric                                  BECount, IsNegStride, /*IsLoopMemset=*/true);
9260b57cec5SDimitry Andric }
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric /// mayLoopAccessLocation - Return true if the specified loop might access the
9290b57cec5SDimitry Andric /// specified pointer location, which is a loop-strided access.  The 'Access'
9300b57cec5SDimitry Andric /// argument specifies what the verboten forms of access are (read or write).
9310b57cec5SDimitry Andric static bool
mayLoopAccessLocation(Value * Ptr,ModRefInfo Access,Loop * L,const SCEV * BECount,const SCEV * StoreSizeSCEV,AliasAnalysis & AA,SmallPtrSetImpl<Instruction * > & IgnoredInsts)9320b57cec5SDimitry Andric mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
933349cc55cSDimitry Andric                       const SCEV *BECount, const SCEV *StoreSizeSCEV,
9340b57cec5SDimitry Andric                       AliasAnalysis &AA,
935349cc55cSDimitry Andric                       SmallPtrSetImpl<Instruction *> &IgnoredInsts) {
9360b57cec5SDimitry Andric   // Get the location that may be stored across the loop.  Since the access is
9370b57cec5SDimitry Andric   // strided positively through memory, we say that the modified location starts
9380b57cec5SDimitry Andric   // at the pointer and has infinite size.
939e8d8bef9SDimitry Andric   LocationSize AccessSize = LocationSize::afterPointer();
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   // If the loop iterates a fixed number of times, we can refine the access size
9420b57cec5SDimitry Andric   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
943349cc55cSDimitry Andric   const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount);
944349cc55cSDimitry Andric   const SCEVConstant *ConstSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
9455f757f3fSDimitry Andric   if (BECst && ConstSize) {
9465f757f3fSDimitry Andric     std::optional<uint64_t> BEInt = BECst->getAPInt().tryZExtValue();
9475f757f3fSDimitry Andric     std::optional<uint64_t> SizeInt = ConstSize->getAPInt().tryZExtValue();
9485f757f3fSDimitry Andric     // FIXME: Should this check for overflow?
9495f757f3fSDimitry Andric     if (BEInt && SizeInt)
9505f757f3fSDimitry Andric       AccessSize = LocationSize::precise((*BEInt + 1) * *SizeInt);
9515f757f3fSDimitry Andric   }
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric   // TODO: For this to be really effective, we have to dive into the pointer
9540b57cec5SDimitry Andric   // operand in the store.  Store to &A[i] of 100 will always return may alias
9550b57cec5SDimitry Andric   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
9560b57cec5SDimitry Andric   // which will then no-alias a store to &A[100].
9570b57cec5SDimitry Andric   MemoryLocation StoreLoc(Ptr, AccessSize);
9580b57cec5SDimitry Andric 
959349cc55cSDimitry Andric   for (BasicBlock *B : L->blocks())
960349cc55cSDimitry Andric     for (Instruction &I : *B)
961349cc55cSDimitry Andric       if (!IgnoredInsts.contains(&I) &&
962bdd1243dSDimitry Andric           isModOrRefSet(AA.getModRefInfo(&I, StoreLoc) & Access))
9630b57cec5SDimitry Andric         return true;
9640b57cec5SDimitry Andric   return false;
9650b57cec5SDimitry Andric }
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric // If we have a negative stride, Start refers to the end of the memory location
9680b57cec5SDimitry Andric // we're trying to memset.  Therefore, we need to recompute the base pointer,
9690b57cec5SDimitry Andric // which is just Start - BECount*Size.
getStartForNegStride(const SCEV * Start,const SCEV * BECount,Type * IntPtr,const SCEV * StoreSizeSCEV,ScalarEvolution * SE)9700b57cec5SDimitry Andric static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
971349cc55cSDimitry Andric                                         Type *IntPtr, const SCEV *StoreSizeSCEV,
9720b57cec5SDimitry Andric                                         ScalarEvolution *SE) {
9730b57cec5SDimitry Andric   const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
974349cc55cSDimitry Andric   if (!StoreSizeSCEV->isOne()) {
975349cc55cSDimitry Andric     // index = back edge count * store size
976349cc55cSDimitry Andric     Index = SE->getMulExpr(Index,
977349cc55cSDimitry Andric                            SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
9780b57cec5SDimitry Andric                            SCEV::FlagNUW);
979349cc55cSDimitry Andric   }
980349cc55cSDimitry Andric   // base pointer = start - index * store size
9810b57cec5SDimitry Andric   return SE->getMinusSCEV(Start, Index);
9820b57cec5SDimitry Andric }
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric /// Compute the number of bytes as a SCEV from the backedge taken count.
9850b57cec5SDimitry Andric ///
9860b57cec5SDimitry Andric /// This also maps the SCEV into the provided type and tries to handle the
9870b57cec5SDimitry Andric /// computation in a way that will fold cleanly.
getNumBytes(const SCEV * BECount,Type * IntPtr,const SCEV * StoreSizeSCEV,Loop * CurLoop,const DataLayout * DL,ScalarEvolution * SE)9880b57cec5SDimitry Andric static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
989349cc55cSDimitry Andric                                const SCEV *StoreSizeSCEV, Loop *CurLoop,
9900b57cec5SDimitry Andric                                const DataLayout *DL, ScalarEvolution *SE) {
99106c3fb27SDimitry Andric   const SCEV *TripCountSCEV =
99206c3fb27SDimitry Andric       SE->getTripCountFromExitCount(BECount, IntPtr, CurLoop);
993349cc55cSDimitry Andric   return SE->getMulExpr(TripCountSCEV,
994349cc55cSDimitry Andric                         SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
9950b57cec5SDimitry Andric                         SCEV::FlagNUW);
9960b57cec5SDimitry Andric }
9970b57cec5SDimitry Andric 
9980b57cec5SDimitry Andric /// processLoopStridedStore - We see a strided store of some value.  If we can
9990b57cec5SDimitry Andric /// 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)10000b57cec5SDimitry Andric bool LoopIdiomRecognize::processLoopStridedStore(
1001349cc55cSDimitry Andric     Value *DestPtr, const SCEV *StoreSizeSCEV, MaybeAlign StoreAlignment,
10020b57cec5SDimitry Andric     Value *StoredVal, Instruction *TheStore,
10030b57cec5SDimitry Andric     SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
1004349cc55cSDimitry Andric     const SCEV *BECount, bool IsNegStride, bool IsLoopMemset) {
100581ad6265SDimitry Andric   Module *M = TheStore->getModule();
10060b57cec5SDimitry Andric   Value *SplatValue = isBytewiseValue(StoredVal, *DL);
10070b57cec5SDimitry Andric   Constant *PatternValue = nullptr;
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   if (!SplatValue)
10100b57cec5SDimitry Andric     PatternValue = getMemSetPatternValue(StoredVal, DL);
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric   assert((SplatValue || PatternValue) &&
10130b57cec5SDimitry Andric          "Expected either splat value or pattern value.");
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   // The trip count of the loop and the base pointer of the addrec SCEV is
10160b57cec5SDimitry Andric   // guaranteed to be loop invariant, which means that it should dominate the
10170b57cec5SDimitry Andric   // header.  This allows us to insert code for it in the preheader.
10180b57cec5SDimitry Andric   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
10190b57cec5SDimitry Andric   BasicBlock *Preheader = CurLoop->getLoopPreheader();
10200b57cec5SDimitry Andric   IRBuilder<> Builder(Preheader->getTerminator());
10210b57cec5SDimitry Andric   SCEVExpander Expander(*SE, *DL, "loop-idiom");
102204eeddc0SDimitry Andric   SCEVExpanderCleaner ExpCleaner(Expander);
10230b57cec5SDimitry Andric 
10245f757f3fSDimitry Andric   Type *DestInt8PtrTy = Builder.getPtrTy(DestAS);
1025480093f4SDimitry Andric   Type *IntIdxTy = DL->getIndexType(DestPtr->getType());
10260b57cec5SDimitry Andric 
1027e8d8bef9SDimitry Andric   bool Changed = false;
10280b57cec5SDimitry Andric   const SCEV *Start = Ev->getStart();
10290b57cec5SDimitry Andric   // Handle negative strided loops.
1030349cc55cSDimitry Andric   if (IsNegStride)
1031349cc55cSDimitry Andric     Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSizeSCEV, SE);
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric   // TODO: ideally we should still be able to generate memset if SCEV expander
10340b57cec5SDimitry Andric   // is taught to generate the dependencies at the latest point.
1035fcaf7f86SDimitry Andric   if (!Expander.isSafeToExpand(Start))
1036e8d8bef9SDimitry Andric     return Changed;
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
10390b57cec5SDimitry Andric   // this into a memset in the loop preheader now if we want.  However, this
10400b57cec5SDimitry Andric   // would be unsafe to do if there is anything else in the loop that may read
10410b57cec5SDimitry Andric   // or write to the aliased location.  Check for any overlap by generating the
10420b57cec5SDimitry Andric   // base pointer and checking the region.
10430b57cec5SDimitry Andric   Value *BasePtr =
10440b57cec5SDimitry Andric       Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
1045e8d8bef9SDimitry Andric 
1046e8d8bef9SDimitry Andric   // From here on out, conservatively report to the pass manager that we've
1047e8d8bef9SDimitry Andric   // changed the IR, even if we later clean up these added instructions. There
1048e8d8bef9SDimitry Andric   // may be structural differences e.g. in the order of use lists not accounted
1049e8d8bef9SDimitry Andric   // for in just a textual dump of the IR. This is written as a variable, even
1050e8d8bef9SDimitry Andric   // though statically all the places this dominates could be replaced with
1051e8d8bef9SDimitry Andric   // 'true', with the hope that anyone trying to be clever / "more precise" with
1052e8d8bef9SDimitry Andric   // the return value will read this comment, and leave them alone.
1053e8d8bef9SDimitry Andric   Changed = true;
1054e8d8bef9SDimitry Andric 
10550b57cec5SDimitry Andric   if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1056349cc55cSDimitry Andric                             StoreSizeSCEV, *AA, Stores))
1057e8d8bef9SDimitry Andric     return Changed;
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric   if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
1060e8d8bef9SDimitry Andric     return Changed;
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric   // Okay, everything looks good, insert the memset.
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   const SCEV *NumBytesS =
1065349cc55cSDimitry Andric       getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric   // TODO: ideally we should still be able to generate memset if SCEV expander
10680b57cec5SDimitry Andric   // is taught to generate the dependencies at the latest point.
1069fcaf7f86SDimitry Andric   if (!Expander.isSafeToExpand(NumBytesS))
1070e8d8bef9SDimitry Andric     return Changed;
10710b57cec5SDimitry Andric 
10720b57cec5SDimitry Andric   Value *NumBytes =
1073480093f4SDimitry Andric       Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
10740b57cec5SDimitry Andric 
107506c3fb27SDimitry Andric   if (!SplatValue && !isLibFuncEmittable(M, TLI, LibFunc_memset_pattern16))
107606c3fb27SDimitry Andric     return Changed;
107706c3fb27SDimitry Andric 
10781fd87a68SDimitry Andric   AAMDNodes AATags = TheStore->getAAMetadata();
107956f451bbSDimitry Andric   for (Instruction *Store : Stores)
108056f451bbSDimitry Andric     AATags = AATags.merge(Store->getAAMetadata());
10811fd87a68SDimitry Andric   if (auto CI = dyn_cast<ConstantInt>(NumBytes))
10821fd87a68SDimitry Andric     AATags = AATags.extendTo(CI->getZExtValue());
10831fd87a68SDimitry Andric   else
10841fd87a68SDimitry Andric     AATags = AATags.extendTo(-1);
10851fd87a68SDimitry Andric 
108606c3fb27SDimitry Andric   CallInst *NewCall;
108706c3fb27SDimitry Andric   if (SplatValue) {
10881fd87a68SDimitry Andric     NewCall = Builder.CreateMemSet(
10891fd87a68SDimitry Andric         BasePtr, SplatValue, NumBytes, MaybeAlign(StoreAlignment),
10901fd87a68SDimitry Andric         /*isVolatile=*/false, AATags.TBAA, AATags.Scope, AATags.NoAlias);
109106c3fb27SDimitry Andric   } else {
109206c3fb27SDimitry Andric     assert (isLibFuncEmittable(M, TLI, LibFunc_memset_pattern16));
10930b57cec5SDimitry Andric     // Everything is emitted in default address space
10940b57cec5SDimitry Andric     Type *Int8PtrTy = DestInt8PtrTy;
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric     StringRef FuncName = "memset_pattern16";
109781ad6265SDimitry Andric     FunctionCallee MSP = getOrInsertLibFunc(M, *TLI, LibFunc_memset_pattern16,
109881ad6265SDimitry Andric                             Builder.getVoidTy(), Int8PtrTy, Int8PtrTy, IntIdxTy);
109981ad6265SDimitry Andric     inferNonMandatoryLibFuncAttrs(M, FuncName, *TLI);
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
11020b57cec5SDimitry Andric     // an constant array of 16-bytes.  Plop the value into a mergable global.
11030b57cec5SDimitry Andric     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
11040b57cec5SDimitry Andric                                             GlobalValue::PrivateLinkage,
11050b57cec5SDimitry Andric                                             PatternValue, ".memset_pattern");
11060b57cec5SDimitry Andric     GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
11078bcb0991SDimitry Andric     GV->setAlignment(Align(16));
11085f757f3fSDimitry Andric     Value *PatternPtr = GV;
11090b57cec5SDimitry Andric     NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
111006c3fb27SDimitry Andric 
111106c3fb27SDimitry Andric     // Set the TBAA info if present.
111206c3fb27SDimitry Andric     if (AATags.TBAA)
111306c3fb27SDimitry Andric       NewCall->setMetadata(LLVMContext::MD_tbaa, AATags.TBAA);
111406c3fb27SDimitry Andric 
111506c3fb27SDimitry Andric     if (AATags.Scope)
111606c3fb27SDimitry Andric       NewCall->setMetadata(LLVMContext::MD_alias_scope, AATags.Scope);
111706c3fb27SDimitry Andric 
111806c3fb27SDimitry Andric     if (AATags.NoAlias)
111906c3fb27SDimitry Andric       NewCall->setMetadata(LLVMContext::MD_noalias, AATags.NoAlias);
112006c3fb27SDimitry Andric   }
112181ad6265SDimitry Andric 
11225ffd83dbSDimitry Andric   NewCall->setDebugLoc(TheStore->getDebugLoc());
11235ffd83dbSDimitry Andric 
11245ffd83dbSDimitry Andric   if (MSSAU) {
11255ffd83dbSDimitry Andric     MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
11265ffd83dbSDimitry Andric         NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
11275ffd83dbSDimitry Andric     MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
11285ffd83dbSDimitry Andric   }
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
11310b57cec5SDimitry Andric                     << "    from store to: " << *Ev << " at: " << *TheStore
11320b57cec5SDimitry Andric                     << "\n");
11330b57cec5SDimitry Andric 
11340b57cec5SDimitry Andric   ORE.emit([&]() {
1135349cc55cSDimitry Andric     OptimizationRemark R(DEBUG_TYPE, "ProcessLoopStridedStore",
1136349cc55cSDimitry Andric                          NewCall->getDebugLoc(), Preheader);
1137349cc55cSDimitry Andric     R << "Transformed loop-strided store in "
1138fe6060f1SDimitry Andric       << ore::NV("Function", TheStore->getFunction())
1139fe6060f1SDimitry Andric       << " function into a call to "
11400b57cec5SDimitry Andric       << ore::NV("NewFunction", NewCall->getCalledFunction())
1141fe6060f1SDimitry Andric       << "() intrinsic";
1142349cc55cSDimitry Andric     if (!Stores.empty())
1143349cc55cSDimitry Andric       R << ore::setExtraArgs();
1144349cc55cSDimitry Andric     for (auto *I : Stores) {
1145349cc55cSDimitry Andric       R << ore::NV("FromBlock", I->getParent()->getName())
1146349cc55cSDimitry Andric         << ore::NV("ToBlock", Preheader->getName());
1147349cc55cSDimitry Andric     }
1148349cc55cSDimitry Andric     return R;
11490b57cec5SDimitry Andric   });
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric   // Okay, the memset has been formed.  Zap the original store and anything that
11520b57cec5SDimitry Andric   // feeds into it.
11535ffd83dbSDimitry Andric   for (auto *I : Stores) {
11545ffd83dbSDimitry Andric     if (MSSAU)
11555ffd83dbSDimitry Andric       MSSAU->removeMemoryAccess(I, true);
11560b57cec5SDimitry Andric     deleteDeadInstruction(I);
11575ffd83dbSDimitry Andric   }
11585ffd83dbSDimitry Andric   if (MSSAU && VerifyMemorySSA)
11595ffd83dbSDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
11600b57cec5SDimitry Andric   ++NumMemSet;
1161e8d8bef9SDimitry Andric   ExpCleaner.markResultUsed();
11620b57cec5SDimitry Andric   return true;
11630b57cec5SDimitry Andric }
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric /// If the stored value is a strided load in the same loop with the same stride
11660b57cec5SDimitry Andric /// this may be transformable into a memcpy.  This kicks in for stuff like
11670b57cec5SDimitry Andric /// for (i) A[i] = B[i];
processLoopStoreOfLoopLoad(StoreInst * SI,const SCEV * BECount)11680b57cec5SDimitry Andric bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
11690b57cec5SDimitry Andric                                                     const SCEV *BECount) {
11700b57cec5SDimitry Andric   assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
11710b57cec5SDimitry Andric 
11720b57cec5SDimitry Andric   Value *StorePtr = SI->getPointerOperand();
11730b57cec5SDimitry Andric   const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
11740b57cec5SDimitry Andric   unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
11750b57cec5SDimitry Andric 
11760b57cec5SDimitry Andric   // The store must be feeding a non-volatile load.
11770b57cec5SDimitry Andric   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
11780b57cec5SDimitry Andric   assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric   // See if the pointer expression is an AddRec like {base,+,1} on the current
11810b57cec5SDimitry Andric   // loop, which indicates a strided load.  If we have something else, it's a
11820b57cec5SDimitry Andric   // random load we can't handle.
1183fe6060f1SDimitry Andric   Value *LoadPtr = LI->getPointerOperand();
1184fe6060f1SDimitry Andric   const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1185349cc55cSDimitry Andric 
1186349cc55cSDimitry Andric   const SCEV *StoreSizeSCEV = SE->getConstant(StorePtr->getType(), StoreSize);
1187349cc55cSDimitry Andric   return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSizeSCEV,
1188fe6060f1SDimitry Andric                                     SI->getAlign(), LI->getAlign(), SI, LI,
1189fe6060f1SDimitry Andric                                     StoreEv, LoadEv, BECount);
1190fe6060f1SDimitry Andric }
1191fe6060f1SDimitry Andric 
1192bdd1243dSDimitry Andric namespace {
1193349cc55cSDimitry Andric class MemmoveVerifier {
1194349cc55cSDimitry Andric public:
MemmoveVerifier(const Value & LoadBasePtr,const Value & StoreBasePtr,const DataLayout & DL)1195349cc55cSDimitry Andric   explicit MemmoveVerifier(const Value &LoadBasePtr, const Value &StoreBasePtr,
1196349cc55cSDimitry Andric                            const DataLayout &DL)
119781ad6265SDimitry Andric       : DL(DL), BP1(llvm::GetPointerBaseWithConstantOffset(
1198349cc55cSDimitry Andric                     LoadBasePtr.stripPointerCasts(), LoadOff, DL)),
1199349cc55cSDimitry Andric         BP2(llvm::GetPointerBaseWithConstantOffset(
1200349cc55cSDimitry Andric             StoreBasePtr.stripPointerCasts(), StoreOff, DL)),
1201349cc55cSDimitry Andric         IsSameObject(BP1 == BP2) {}
1202349cc55cSDimitry Andric 
loadAndStoreMayFormMemmove(unsigned StoreSize,bool IsNegStride,const Instruction & TheLoad,bool IsMemCpy) const1203349cc55cSDimitry Andric   bool loadAndStoreMayFormMemmove(unsigned StoreSize, bool IsNegStride,
1204349cc55cSDimitry Andric                                   const Instruction &TheLoad,
1205349cc55cSDimitry Andric                                   bool IsMemCpy) const {
1206349cc55cSDimitry Andric     if (IsMemCpy) {
1207349cc55cSDimitry Andric       // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr
1208349cc55cSDimitry Andric       // for negative stride.
1209349cc55cSDimitry Andric       if ((!IsNegStride && LoadOff <= StoreOff) ||
1210349cc55cSDimitry Andric           (IsNegStride && LoadOff >= StoreOff))
1211349cc55cSDimitry Andric         return false;
1212349cc55cSDimitry Andric     } else {
1213349cc55cSDimitry Andric       // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr
1214349cc55cSDimitry Andric       // for negative stride. LoadBasePtr shouldn't overlap with StoreBasePtr.
1215349cc55cSDimitry Andric       int64_t LoadSize =
1216bdd1243dSDimitry Andric           DL.getTypeSizeInBits(TheLoad.getType()).getFixedValue() / 8;
1217349cc55cSDimitry Andric       if (BP1 != BP2 || LoadSize != int64_t(StoreSize))
1218349cc55cSDimitry Andric         return false;
1219349cc55cSDimitry Andric       if ((!IsNegStride && LoadOff < StoreOff + int64_t(StoreSize)) ||
1220349cc55cSDimitry Andric           (IsNegStride && LoadOff + LoadSize > StoreOff))
1221349cc55cSDimitry Andric         return false;
1222349cc55cSDimitry Andric     }
1223349cc55cSDimitry Andric     return true;
1224349cc55cSDimitry Andric   }
1225349cc55cSDimitry Andric 
1226349cc55cSDimitry Andric private:
1227349cc55cSDimitry Andric   const DataLayout &DL;
122881ad6265SDimitry Andric   int64_t LoadOff = 0;
122981ad6265SDimitry Andric   int64_t StoreOff = 0;
1230349cc55cSDimitry Andric   const Value *BP1;
1231349cc55cSDimitry Andric   const Value *BP2;
1232349cc55cSDimitry Andric 
1233349cc55cSDimitry Andric public:
1234349cc55cSDimitry Andric   const bool IsSameObject;
1235349cc55cSDimitry Andric };
1236bdd1243dSDimitry Andric } // namespace
1237349cc55cSDimitry Andric 
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)1238fe6060f1SDimitry Andric bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
1239349cc55cSDimitry Andric     Value *DestPtr, Value *SourcePtr, const SCEV *StoreSizeSCEV,
1240349cc55cSDimitry Andric     MaybeAlign StoreAlign, MaybeAlign LoadAlign, Instruction *TheStore,
1241349cc55cSDimitry Andric     Instruction *TheLoad, const SCEVAddRecExpr *StoreEv,
1242349cc55cSDimitry Andric     const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
1243fe6060f1SDimitry Andric 
1244fe6060f1SDimitry Andric   // FIXME: until llvm.memcpy.inline supports dynamic sizes, we need to
1245fe6060f1SDimitry Andric   // conservatively bail here, since otherwise we may have to transform
1246fe6060f1SDimitry Andric   // llvm.memcpy.inline into llvm.memcpy which is illegal.
1247fe6060f1SDimitry Andric   if (isa<MemCpyInlineInst>(TheStore))
1248fe6060f1SDimitry Andric     return false;
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric   // The trip count of the loop and the base pointer of the addrec SCEV is
12510b57cec5SDimitry Andric   // guaranteed to be loop invariant, which means that it should dominate the
12520b57cec5SDimitry Andric   // header.  This allows us to insert code for it in the preheader.
12530b57cec5SDimitry Andric   BasicBlock *Preheader = CurLoop->getLoopPreheader();
12540b57cec5SDimitry Andric   IRBuilder<> Builder(Preheader->getTerminator());
12550b57cec5SDimitry Andric   SCEVExpander Expander(*SE, *DL, "loop-idiom");
12560b57cec5SDimitry Andric 
125704eeddc0SDimitry Andric   SCEVExpanderCleaner ExpCleaner(Expander);
12585ffd83dbSDimitry Andric 
1259e8d8bef9SDimitry Andric   bool Changed = false;
12600b57cec5SDimitry Andric   const SCEV *StrStart = StoreEv->getStart();
1261fe6060f1SDimitry Andric   unsigned StrAS = DestPtr->getType()->getPointerAddressSpace();
1262480093f4SDimitry Andric   Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS));
12630b57cec5SDimitry Andric 
1264fe6060f1SDimitry Andric   APInt Stride = getStoreStride(StoreEv);
1265349cc55cSDimitry Andric   const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1266349cc55cSDimitry Andric 
1267349cc55cSDimitry Andric   // TODO: Deal with non-constant size; Currently expect constant store size
1268349cc55cSDimitry Andric   assert(ConstStoreSize && "store size is expected to be a constant");
1269349cc55cSDimitry Andric 
1270349cc55cSDimitry Andric   int64_t StoreSize = ConstStoreSize->getValue()->getZExtValue();
1271349cc55cSDimitry Andric   bool IsNegStride = StoreSize == -Stride;
1272fe6060f1SDimitry Andric 
12730b57cec5SDimitry Andric   // Handle negative strided loops.
1274349cc55cSDimitry Andric   if (IsNegStride)
1275349cc55cSDimitry Andric     StrStart =
1276349cc55cSDimitry Andric         getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
12790b57cec5SDimitry Andric   // this into a memcpy in the loop preheader now if we want.  However, this
12800b57cec5SDimitry Andric   // would be unsafe to do if there is anything else in the loop that may read
12810b57cec5SDimitry Andric   // or write the memory region we're storing to.  This includes the load that
12820b57cec5SDimitry Andric   // feeds the stores.  Check for an alias by generating the base address and
12830b57cec5SDimitry Andric   // checking everything.
12840b57cec5SDimitry Andric   Value *StoreBasePtr = Expander.expandCodeFor(
12855f757f3fSDimitry Andric       StrStart, Builder.getPtrTy(StrAS), Preheader->getTerminator());
1286e8d8bef9SDimitry Andric 
1287e8d8bef9SDimitry Andric   // From here on out, conservatively report to the pass manager that we've
1288e8d8bef9SDimitry Andric   // changed the IR, even if we later clean up these added instructions. There
1289e8d8bef9SDimitry Andric   // may be structural differences e.g. in the order of use lists not accounted
1290e8d8bef9SDimitry Andric   // for in just a textual dump of the IR. This is written as a variable, even
1291e8d8bef9SDimitry Andric   // though statically all the places this dominates could be replaced with
1292e8d8bef9SDimitry Andric   // 'true', with the hope that anyone trying to be clever / "more precise" with
1293e8d8bef9SDimitry Andric   // the return value will read this comment, and leave them alone.
1294e8d8bef9SDimitry Andric   Changed = true;
12950b57cec5SDimitry Andric 
1296349cc55cSDimitry Andric   SmallPtrSet<Instruction *, 2> IgnoredInsts;
1297349cc55cSDimitry Andric   IgnoredInsts.insert(TheStore);
1298fe6060f1SDimitry Andric 
1299fe6060f1SDimitry Andric   bool IsMemCpy = isa<MemCpyInst>(TheStore);
1300fe6060f1SDimitry Andric   const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store";
1301fe6060f1SDimitry Andric 
1302349cc55cSDimitry Andric   bool LoopAccessStore =
1303fe6060f1SDimitry Andric       mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1304349cc55cSDimitry Andric                             StoreSizeSCEV, *AA, IgnoredInsts);
1305349cc55cSDimitry Andric   if (LoopAccessStore) {
130669ade1e0SDimitry Andric     // For memmove case it's not enough to guarantee that loop doesn't access
130769ade1e0SDimitry Andric     // TheStore and TheLoad. Additionally we need to make sure that TheStore is
130869ade1e0SDimitry Andric     // the only user of TheLoad.
130969ade1e0SDimitry Andric     if (!TheLoad->hasOneUse())
131069ade1e0SDimitry Andric       return Changed;
1311349cc55cSDimitry Andric     IgnoredInsts.insert(TheLoad);
1312fe6060f1SDimitry Andric     if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
1313349cc55cSDimitry Andric                               BECount, StoreSizeSCEV, *AA, IgnoredInsts)) {
1314fe6060f1SDimitry Andric       ORE.emit([&]() {
1315fe6060f1SDimitry Andric         return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessStore",
1316fe6060f1SDimitry Andric                                         TheStore)
1317fe6060f1SDimitry Andric                << ore::NV("Inst", InstRemark) << " in "
1318fe6060f1SDimitry Andric                << ore::NV("Function", TheStore->getFunction())
1319fe6060f1SDimitry Andric                << " function will not be hoisted: "
1320fe6060f1SDimitry Andric                << ore::NV("Reason", "The loop may access store location");
1321fe6060f1SDimitry Andric       });
1322e8d8bef9SDimitry Andric       return Changed;
1323fe6060f1SDimitry Andric     }
1324349cc55cSDimitry Andric     IgnoredInsts.erase(TheLoad);
1325fe6060f1SDimitry Andric   }
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric   const SCEV *LdStart = LoadEv->getStart();
1328fe6060f1SDimitry Andric   unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace();
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric   // Handle negative strided loops.
1331349cc55cSDimitry Andric   if (IsNegStride)
1332349cc55cSDimitry Andric     LdStart =
1333349cc55cSDimitry Andric         getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric   // For a memcpy, we have to make sure that the input array is not being
13360b57cec5SDimitry Andric   // mutated by the loop.
13375f757f3fSDimitry Andric   Value *LoadBasePtr = Expander.expandCodeFor(LdStart, Builder.getPtrTy(LdAS),
13385f757f3fSDimitry Andric                                               Preheader->getTerminator());
13390b57cec5SDimitry Andric 
1340fe6060f1SDimitry Andric   // If the store is a memcpy instruction, we must check if it will write to
1341fe6060f1SDimitry Andric   // the load memory locations. So remove it from the ignored stores.
1342349cc55cSDimitry Andric   MemmoveVerifier Verifier(*LoadBasePtr, *StoreBasePtr, *DL);
134356f451bbSDimitry Andric   if (IsMemCpy && !Verifier.IsSameObject)
134456f451bbSDimitry Andric     IgnoredInsts.erase(TheStore);
13450b57cec5SDimitry Andric   if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1346349cc55cSDimitry Andric                             StoreSizeSCEV, *AA, IgnoredInsts)) {
1347fe6060f1SDimitry Andric     ORE.emit([&]() {
134856f451bbSDimitry Andric       return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessLoad", TheLoad)
1349fe6060f1SDimitry Andric              << ore::NV("Inst", InstRemark) << " in "
1350fe6060f1SDimitry Andric              << ore::NV("Function", TheStore->getFunction())
1351fe6060f1SDimitry Andric              << " function will not be hoisted: "
1352fe6060f1SDimitry Andric              << ore::NV("Reason", "The loop may access load location");
1353fe6060f1SDimitry Andric     });
1354e8d8bef9SDimitry Andric     return Changed;
1355fe6060f1SDimitry Andric   }
13560b57cec5SDimitry Andric 
1357349cc55cSDimitry Andric   bool UseMemMove = IsMemCpy ? Verifier.IsSameObject : LoopAccessStore;
1358349cc55cSDimitry Andric   if (UseMemMove)
1359349cc55cSDimitry Andric     if (!Verifier.loadAndStoreMayFormMemmove(StoreSize, IsNegStride, *TheLoad,
1360349cc55cSDimitry Andric                                              IsMemCpy))
1361349cc55cSDimitry Andric       return Changed;
1362349cc55cSDimitry Andric 
13630b57cec5SDimitry Andric   if (avoidLIRForMultiBlockLoop())
1364e8d8bef9SDimitry Andric     return Changed;
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric   // Okay, everything is safe, we can transform this!
13670b57cec5SDimitry Andric 
13680b57cec5SDimitry Andric   const SCEV *NumBytesS =
1369349cc55cSDimitry Andric       getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric   Value *NumBytes =
1372480093f4SDimitry Andric       Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
13730b57cec5SDimitry Andric 
13741fd87a68SDimitry Andric   AAMDNodes AATags = TheLoad->getAAMetadata();
13751fd87a68SDimitry Andric   AAMDNodes StoreAATags = TheStore->getAAMetadata();
13761fd87a68SDimitry Andric   AATags = AATags.merge(StoreAATags);
13771fd87a68SDimitry Andric   if (auto CI = dyn_cast<ConstantInt>(NumBytes))
13781fd87a68SDimitry Andric     AATags = AATags.extendTo(CI->getZExtValue());
13791fd87a68SDimitry Andric   else
13801fd87a68SDimitry Andric     AATags = AATags.extendTo(-1);
13811fd87a68SDimitry Andric 
13820b57cec5SDimitry Andric   CallInst *NewCall = nullptr;
13830b57cec5SDimitry Andric   // Check whether to generate an unordered atomic memcpy:
13840b57cec5SDimitry Andric   //  If the load or store are atomic, then they must necessarily be unordered
13850b57cec5SDimitry Andric   //  by previous checks.
1386fe6060f1SDimitry Andric   if (!TheStore->isAtomic() && !TheLoad->isAtomic()) {
1387fe6060f1SDimitry Andric     if (UseMemMove)
13881fd87a68SDimitry Andric       NewCall = Builder.CreateMemMove(
13891fd87a68SDimitry Andric           StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign, NumBytes,
13901fd87a68SDimitry Andric           /*isVolatile=*/false, AATags.TBAA, AATags.Scope, AATags.NoAlias);
1391fe6060f1SDimitry Andric     else
13921fd87a68SDimitry Andric       NewCall =
13931fd87a68SDimitry Andric           Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign,
13941fd87a68SDimitry Andric                                NumBytes, /*isVolatile=*/false, AATags.TBAA,
13951fd87a68SDimitry Andric                                AATags.TBAAStruct, AATags.Scope, AATags.NoAlias);
1396fe6060f1SDimitry Andric   } else {
1397fe6060f1SDimitry Andric     // For now don't support unordered atomic memmove.
1398fe6060f1SDimitry Andric     if (UseMemMove)
1399fe6060f1SDimitry Andric       return Changed;
14000b57cec5SDimitry Andric     // We cannot allow unaligned ops for unordered load/store, so reject
14010b57cec5SDimitry Andric     // anything where the alignment isn't at least the element size.
140281ad6265SDimitry Andric     assert((StoreAlign && LoadAlign) &&
1403fe6060f1SDimitry Andric            "Expect unordered load/store to have align.");
1404bdd1243dSDimitry Andric     if (*StoreAlign < StoreSize || *LoadAlign < StoreSize)
1405e8d8bef9SDimitry Andric       return Changed;
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric     // If the element.atomic memcpy is not lowered into explicit
14080b57cec5SDimitry Andric     // loads/stores later, then it will be lowered into an element-size
14090b57cec5SDimitry Andric     // specific lib call. If the lib call doesn't exist for our store size, then
14100b57cec5SDimitry Andric     // we shouldn't generate the memcpy.
14110b57cec5SDimitry Andric     if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1412e8d8bef9SDimitry Andric       return Changed;
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric     // Create the call.
14150b57cec5SDimitry Andric     // Note that unordered atomic loads/stores are *required* by the spec to
14160b57cec5SDimitry Andric     // have an alignment but non-atomic loads/stores may not.
14170b57cec5SDimitry Andric     NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1418bdd1243dSDimitry Andric         StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, StoreSize,
1419bdd1243dSDimitry Andric         AATags.TBAA, AATags.TBAAStruct, AATags.Scope, AATags.NoAlias);
14200b57cec5SDimitry Andric   }
1421fe6060f1SDimitry Andric   NewCall->setDebugLoc(TheStore->getDebugLoc());
14220b57cec5SDimitry Andric 
14235ffd83dbSDimitry Andric   if (MSSAU) {
14245ffd83dbSDimitry Andric     MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
14255ffd83dbSDimitry Andric         NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
14265ffd83dbSDimitry Andric     MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
14275ffd83dbSDimitry Andric   }
14285ffd83dbSDimitry Andric 
1429fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "  Formed new call: " << *NewCall << "\n"
1430fe6060f1SDimitry Andric                     << "    from load ptr=" << *LoadEv << " at: " << *TheLoad
1431fe6060f1SDimitry Andric                     << "\n"
1432fe6060f1SDimitry Andric                     << "    from store ptr=" << *StoreEv << " at: " << *TheStore
14330b57cec5SDimitry Andric                     << "\n");
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric   ORE.emit([&]() {
14360b57cec5SDimitry Andric     return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad",
14370b57cec5SDimitry Andric                               NewCall->getDebugLoc(), Preheader)
14380b57cec5SDimitry Andric            << "Formed a call to "
14390b57cec5SDimitry Andric            << ore::NV("NewFunction", NewCall->getCalledFunction())
1440fe6060f1SDimitry Andric            << "() intrinsic from " << ore::NV("Inst", InstRemark)
1441fe6060f1SDimitry Andric            << " instruction in " << ore::NV("Function", TheStore->getFunction())
1442349cc55cSDimitry Andric            << " function"
1443349cc55cSDimitry Andric            << ore::setExtraArgs()
1444349cc55cSDimitry Andric            << ore::NV("FromBlock", TheStore->getParent()->getName())
1445349cc55cSDimitry Andric            << ore::NV("ToBlock", Preheader->getName());
14460b57cec5SDimitry Andric   });
14470b57cec5SDimitry Andric 
1448349cc55cSDimitry Andric   // Okay, a new call to memcpy/memmove has been formed.  Zap the original store
1449349cc55cSDimitry Andric   // and anything that feeds into it.
14505ffd83dbSDimitry Andric   if (MSSAU)
1451fe6060f1SDimitry Andric     MSSAU->removeMemoryAccess(TheStore, true);
1452fe6060f1SDimitry Andric   deleteDeadInstruction(TheStore);
14535ffd83dbSDimitry Andric   if (MSSAU && VerifyMemorySSA)
14545ffd83dbSDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
1455fe6060f1SDimitry Andric   if (UseMemMove)
1456fe6060f1SDimitry Andric     ++NumMemMove;
1457fe6060f1SDimitry Andric   else
14580b57cec5SDimitry Andric     ++NumMemCpy;
1459e8d8bef9SDimitry Andric   ExpCleaner.markResultUsed();
14600b57cec5SDimitry Andric   return true;
14610b57cec5SDimitry Andric }
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric // When compiling for codesize we avoid idiom recognition for a multi-block loop
14640b57cec5SDimitry Andric // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
14650b57cec5SDimitry Andric //
avoidLIRForMultiBlockLoop(bool IsMemset,bool IsLoopMemset)14660b57cec5SDimitry Andric bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
14670b57cec5SDimitry Andric                                                    bool IsLoopMemset) {
14680b57cec5SDimitry Andric   if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1469e8d8bef9SDimitry Andric     if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) {
14700b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  " << CurLoop->getHeader()->getParent()->getName()
14710b57cec5SDimitry Andric                         << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
14720b57cec5SDimitry Andric                         << " avoided: multi-block top-level loop\n");
14730b57cec5SDimitry Andric       return true;
14740b57cec5SDimitry Andric     }
14750b57cec5SDimitry Andric   }
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   return false;
14780b57cec5SDimitry Andric }
14790b57cec5SDimitry Andric 
runOnNoncountableLoop()14800b57cec5SDimitry Andric bool LoopIdiomRecognize::runOnNoncountableLoop() {
14810b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
14820b57cec5SDimitry Andric                     << CurLoop->getHeader()->getParent()->getName()
14830b57cec5SDimitry Andric                     << "] Noncountable Loop %"
14840b57cec5SDimitry Andric                     << CurLoop->getHeader()->getName() << "\n");
14850b57cec5SDimitry Andric 
1486e8d8bef9SDimitry Andric   return recognizePopcount() || recognizeAndInsertFFS() ||
1487fe6060f1SDimitry Andric          recognizeShiftUntilBitTest() || recognizeShiftUntilZero();
14880b57cec5SDimitry Andric }
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric /// Check if the given conditional branch is based on the comparison between
14910b57cec5SDimitry Andric /// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
14920b57cec5SDimitry Andric /// true), the control yields to the loop entry. If the branch matches the
14930b57cec5SDimitry Andric /// behavior, the variable involved in the comparison is returned. This function
14940b57cec5SDimitry Andric /// will be called to see if the precondition and postcondition of the loop are
14950b57cec5SDimitry Andric /// in desirable form.
matchCondition(BranchInst * BI,BasicBlock * LoopEntry,bool JmpOnZero=false)14960b57cec5SDimitry Andric static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry,
14970b57cec5SDimitry Andric                              bool JmpOnZero = false) {
14980b57cec5SDimitry Andric   if (!BI || !BI->isConditional())
14990b57cec5SDimitry Andric     return nullptr;
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric   ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
15020b57cec5SDimitry Andric   if (!Cond)
15030b57cec5SDimitry Andric     return nullptr;
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
15060b57cec5SDimitry Andric   if (!CmpZero || !CmpZero->isZero())
15070b57cec5SDimitry Andric     return nullptr;
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric   BasicBlock *TrueSucc = BI->getSuccessor(0);
15100b57cec5SDimitry Andric   BasicBlock *FalseSucc = BI->getSuccessor(1);
15110b57cec5SDimitry Andric   if (JmpOnZero)
15120b57cec5SDimitry Andric     std::swap(TrueSucc, FalseSucc);
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric   ICmpInst::Predicate Pred = Cond->getPredicate();
15150b57cec5SDimitry Andric   if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
15160b57cec5SDimitry Andric       (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
15170b57cec5SDimitry Andric     return Cond->getOperand(0);
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric   return nullptr;
15200b57cec5SDimitry Andric }
15210b57cec5SDimitry Andric 
15220b57cec5SDimitry Andric // Check if the recurrence variable `VarX` is in the right form to create
15230b57cec5SDimitry Andric // the idiom. Returns the value coerced to a PHINode if so.
getRecurrenceVar(Value * VarX,Instruction * DefX,BasicBlock * LoopEntry)15240b57cec5SDimitry Andric static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
15250b57cec5SDimitry Andric                                  BasicBlock *LoopEntry) {
15260b57cec5SDimitry Andric   auto *PhiX = dyn_cast<PHINode>(VarX);
15270b57cec5SDimitry Andric   if (PhiX && PhiX->getParent() == LoopEntry &&
15280b57cec5SDimitry Andric       (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
15290b57cec5SDimitry Andric     return PhiX;
15300b57cec5SDimitry Andric   return nullptr;
15310b57cec5SDimitry Andric }
15320b57cec5SDimitry Andric 
15330b57cec5SDimitry Andric /// Return true iff the idiom is detected in the loop.
15340b57cec5SDimitry Andric ///
15350b57cec5SDimitry Andric /// Additionally:
15360b57cec5SDimitry Andric /// 1) \p CntInst is set to the instruction counting the population bit.
15370b57cec5SDimitry Andric /// 2) \p CntPhi is set to the corresponding phi node.
15380b57cec5SDimitry Andric /// 3) \p Var is set to the value whose population bits are being counted.
15390b57cec5SDimitry Andric ///
15400b57cec5SDimitry Andric /// The core idiom we are trying to detect is:
15410b57cec5SDimitry Andric /// \code
15420b57cec5SDimitry Andric ///    if (x0 != 0)
15430b57cec5SDimitry Andric ///      goto loop-exit // the precondition of the loop
15440b57cec5SDimitry Andric ///    cnt0 = init-val;
15450b57cec5SDimitry Andric ///    do {
15460b57cec5SDimitry Andric ///       x1 = phi (x0, x2);
15470b57cec5SDimitry Andric ///       cnt1 = phi(cnt0, cnt2);
15480b57cec5SDimitry Andric ///
15490b57cec5SDimitry Andric ///       cnt2 = cnt1 + 1;
15500b57cec5SDimitry Andric ///        ...
15510b57cec5SDimitry Andric ///       x2 = x1 & (x1 - 1);
15520b57cec5SDimitry Andric ///        ...
15530b57cec5SDimitry Andric ///    } while(x != 0);
15540b57cec5SDimitry Andric ///
15550b57cec5SDimitry Andric /// loop-exit:
15560b57cec5SDimitry Andric /// \endcode
detectPopcountIdiom(Loop * CurLoop,BasicBlock * PreCondBB,Instruction * & CntInst,PHINode * & CntPhi,Value * & Var)15570b57cec5SDimitry Andric static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
15580b57cec5SDimitry Andric                                 Instruction *&CntInst, PHINode *&CntPhi,
15590b57cec5SDimitry Andric                                 Value *&Var) {
15600b57cec5SDimitry Andric   // step 1: Check to see if the look-back branch match this pattern:
15610b57cec5SDimitry Andric   //    "if (a!=0) goto loop-entry".
15620b57cec5SDimitry Andric   BasicBlock *LoopEntry;
15630b57cec5SDimitry Andric   Instruction *DefX2, *CountInst;
15640b57cec5SDimitry Andric   Value *VarX1, *VarX0;
15650b57cec5SDimitry Andric   PHINode *PhiX, *CountPhi;
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric   DefX2 = CountInst = nullptr;
15680b57cec5SDimitry Andric   VarX1 = VarX0 = nullptr;
15690b57cec5SDimitry Andric   PhiX = CountPhi = nullptr;
15700b57cec5SDimitry Andric   LoopEntry = *(CurLoop->block_begin());
15710b57cec5SDimitry Andric 
15720b57cec5SDimitry Andric   // step 1: Check if the loop-back branch is in desirable form.
15730b57cec5SDimitry Andric   {
15740b57cec5SDimitry Andric     if (Value *T = matchCondition(
15750b57cec5SDimitry Andric             dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
15760b57cec5SDimitry Andric       DefX2 = dyn_cast<Instruction>(T);
15770b57cec5SDimitry Andric     else
15780b57cec5SDimitry Andric       return false;
15790b57cec5SDimitry Andric   }
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
15820b57cec5SDimitry Andric   {
15830b57cec5SDimitry Andric     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
15840b57cec5SDimitry Andric       return false;
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric     BinaryOperator *SubOneOp;
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
15890b57cec5SDimitry Andric       VarX1 = DefX2->getOperand(1);
15900b57cec5SDimitry Andric     else {
15910b57cec5SDimitry Andric       VarX1 = DefX2->getOperand(0);
15920b57cec5SDimitry Andric       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
15930b57cec5SDimitry Andric     }
15940b57cec5SDimitry Andric     if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
15950b57cec5SDimitry Andric       return false;
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric     ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
15980b57cec5SDimitry Andric     if (!Dec ||
15990b57cec5SDimitry Andric         !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
16000b57cec5SDimitry Andric           (SubOneOp->getOpcode() == Instruction::Add &&
16010b57cec5SDimitry Andric            Dec->isMinusOne()))) {
16020b57cec5SDimitry Andric       return false;
16030b57cec5SDimitry Andric     }
16040b57cec5SDimitry Andric   }
16050b57cec5SDimitry Andric 
16060b57cec5SDimitry Andric   // step 3: Check the recurrence of variable X
16070b57cec5SDimitry Andric   PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
16080b57cec5SDimitry Andric   if (!PhiX)
16090b57cec5SDimitry Andric     return false;
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
16120b57cec5SDimitry Andric   {
16130b57cec5SDimitry Andric     CountInst = nullptr;
1614349cc55cSDimitry Andric     for (Instruction &Inst : llvm::make_range(
1615349cc55cSDimitry Andric              LoopEntry->getFirstNonPHI()->getIterator(), LoopEntry->end())) {
1616349cc55cSDimitry Andric       if (Inst.getOpcode() != Instruction::Add)
16170b57cec5SDimitry Andric         continue;
16180b57cec5SDimitry Andric 
1619349cc55cSDimitry Andric       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst.getOperand(1));
16200b57cec5SDimitry Andric       if (!Inc || !Inc->isOne())
16210b57cec5SDimitry Andric         continue;
16220b57cec5SDimitry Andric 
1623349cc55cSDimitry Andric       PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
16240b57cec5SDimitry Andric       if (!Phi)
16250b57cec5SDimitry Andric         continue;
16260b57cec5SDimitry Andric 
16270b57cec5SDimitry Andric       // Check if the result of the instruction is live of the loop.
16280b57cec5SDimitry Andric       bool LiveOutLoop = false;
1629349cc55cSDimitry Andric       for (User *U : Inst.users()) {
16300b57cec5SDimitry Andric         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
16310b57cec5SDimitry Andric           LiveOutLoop = true;
16320b57cec5SDimitry Andric           break;
16330b57cec5SDimitry Andric         }
16340b57cec5SDimitry Andric       }
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric       if (LiveOutLoop) {
1637349cc55cSDimitry Andric         CountInst = &Inst;
16380b57cec5SDimitry Andric         CountPhi = Phi;
16390b57cec5SDimitry Andric         break;
16400b57cec5SDimitry Andric       }
16410b57cec5SDimitry Andric     }
16420b57cec5SDimitry Andric 
16430b57cec5SDimitry Andric     if (!CountInst)
16440b57cec5SDimitry Andric       return false;
16450b57cec5SDimitry Andric   }
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric   // step 5: check if the precondition is in this form:
16480b57cec5SDimitry Andric   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
16490b57cec5SDimitry Andric   {
16500b57cec5SDimitry Andric     auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
16510b57cec5SDimitry Andric     Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
16520b57cec5SDimitry Andric     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
16530b57cec5SDimitry Andric       return false;
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric     CntInst = CountInst;
16560b57cec5SDimitry Andric     CntPhi = CountPhi;
16570b57cec5SDimitry Andric     Var = T;
16580b57cec5SDimitry Andric   }
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric   return true;
16610b57cec5SDimitry Andric }
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric /// Return true if the idiom is detected in the loop.
16640b57cec5SDimitry Andric ///
16650b57cec5SDimitry Andric /// Additionally:
16660b57cec5SDimitry Andric /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
16670b57cec5SDimitry Andric ///       or nullptr if there is no such.
16680b57cec5SDimitry Andric /// 2) \p CntPhi is set to the corresponding phi node
16690b57cec5SDimitry Andric ///       or nullptr if there is no such.
16700b57cec5SDimitry Andric /// 3) \p Var is set to the value whose CTLZ could be used.
16710b57cec5SDimitry Andric /// 4) \p DefX is set to the instruction calculating Loop exit condition.
16720b57cec5SDimitry Andric ///
16730b57cec5SDimitry Andric /// The core idiom we are trying to detect is:
16740b57cec5SDimitry Andric /// \code
16750b57cec5SDimitry Andric ///    if (x0 == 0)
16760b57cec5SDimitry Andric ///      goto loop-exit // the precondition of the loop
16770b57cec5SDimitry Andric ///    cnt0 = init-val;
16780b57cec5SDimitry Andric ///    do {
16790b57cec5SDimitry Andric ///       x = phi (x0, x.next);   //PhiX
16800b57cec5SDimitry Andric ///       cnt = phi(cnt0, cnt.next);
16810b57cec5SDimitry Andric ///
16820b57cec5SDimitry Andric ///       cnt.next = cnt + 1;
16830b57cec5SDimitry Andric ///        ...
16840b57cec5SDimitry Andric ///       x.next = x >> 1;   // DefX
16850b57cec5SDimitry Andric ///        ...
16860b57cec5SDimitry Andric ///    } while(x.next != 0);
16870b57cec5SDimitry Andric ///
16880b57cec5SDimitry Andric /// loop-exit:
16890b57cec5SDimitry Andric /// \endcode
detectShiftUntilZeroIdiom(Loop * CurLoop,const DataLayout & DL,Intrinsic::ID & IntrinID,Value * & InitX,Instruction * & CntInst,PHINode * & CntPhi,Instruction * & DefX)16900b57cec5SDimitry Andric static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
16910b57cec5SDimitry Andric                                       Intrinsic::ID &IntrinID, Value *&InitX,
16920b57cec5SDimitry Andric                                       Instruction *&CntInst, PHINode *&CntPhi,
16930b57cec5SDimitry Andric                                       Instruction *&DefX) {
16940b57cec5SDimitry Andric   BasicBlock *LoopEntry;
16950b57cec5SDimitry Andric   Value *VarX = nullptr;
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric   DefX = nullptr;
16980b57cec5SDimitry Andric   CntInst = nullptr;
16990b57cec5SDimitry Andric   CntPhi = nullptr;
17000b57cec5SDimitry Andric   LoopEntry = *(CurLoop->block_begin());
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric   // step 1: Check if the loop-back branch is in desirable form.
17030b57cec5SDimitry Andric   if (Value *T = matchCondition(
17040b57cec5SDimitry Andric           dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
17050b57cec5SDimitry Andric     DefX = dyn_cast<Instruction>(T);
17060b57cec5SDimitry Andric   else
17070b57cec5SDimitry Andric     return false;
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
17100b57cec5SDimitry Andric   if (!DefX || !DefX->isShift())
17110b57cec5SDimitry Andric     return false;
17120b57cec5SDimitry Andric   IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
17130b57cec5SDimitry Andric                                                      Intrinsic::ctlz;
17140b57cec5SDimitry Andric   ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));
17150b57cec5SDimitry Andric   if (!Shft || !Shft->isOne())
17160b57cec5SDimitry Andric     return false;
17170b57cec5SDimitry Andric   VarX = DefX->getOperand(0);
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric   // step 3: Check the recurrence of variable X
17200b57cec5SDimitry Andric   PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
17210b57cec5SDimitry Andric   if (!PhiX)
17220b57cec5SDimitry Andric     return false;
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric   InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric   // Make sure the initial value can't be negative otherwise the ashr in the
17270b57cec5SDimitry Andric   // loop might never reach zero which would make the loop infinite.
17280b57cec5SDimitry Andric   if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
17290b57cec5SDimitry Andric     return false;
17300b57cec5SDimitry Andric 
17310b57cec5SDimitry Andric   // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1732e8d8bef9SDimitry Andric   //         or cnt.next = cnt + -1.
17330b57cec5SDimitry Andric   // TODO: We can skip the step. If loop trip count is known (CTLZ),
17340b57cec5SDimitry Andric   //       then all uses of "cnt.next" could be optimized to the trip count
17350b57cec5SDimitry Andric   //       plus "cnt0". Currently it is not optimized.
17360b57cec5SDimitry Andric   //       This step could be used to detect POPCNT instruction:
17370b57cec5SDimitry Andric   //       cnt.next = cnt + (x.next & 1)
1738349cc55cSDimitry Andric   for (Instruction &Inst : llvm::make_range(
1739349cc55cSDimitry Andric            LoopEntry->getFirstNonPHI()->getIterator(), LoopEntry->end())) {
1740349cc55cSDimitry Andric     if (Inst.getOpcode() != Instruction::Add)
17410b57cec5SDimitry Andric       continue;
17420b57cec5SDimitry Andric 
1743349cc55cSDimitry Andric     ConstantInt *Inc = dyn_cast<ConstantInt>(Inst.getOperand(1));
1744e8d8bef9SDimitry Andric     if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
17450b57cec5SDimitry Andric       continue;
17460b57cec5SDimitry Andric 
1747349cc55cSDimitry Andric     PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
17480b57cec5SDimitry Andric     if (!Phi)
17490b57cec5SDimitry Andric       continue;
17500b57cec5SDimitry Andric 
1751349cc55cSDimitry Andric     CntInst = &Inst;
17520b57cec5SDimitry Andric     CntPhi = Phi;
17530b57cec5SDimitry Andric     break;
17540b57cec5SDimitry Andric   }
17550b57cec5SDimitry Andric   if (!CntInst)
17560b57cec5SDimitry Andric     return false;
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric   return true;
17590b57cec5SDimitry Andric }
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric /// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
17620b57cec5SDimitry Andric /// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
17630b57cec5SDimitry Andric /// trip count returns true; otherwise, returns false.
recognizeAndInsertFFS()17640b57cec5SDimitry Andric bool LoopIdiomRecognize::recognizeAndInsertFFS() {
17650b57cec5SDimitry Andric   // Give up if the loop has multiple blocks or multiple backedges.
17660b57cec5SDimitry Andric   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
17670b57cec5SDimitry Andric     return false;
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric   Intrinsic::ID IntrinID;
17700b57cec5SDimitry Andric   Value *InitX;
17710b57cec5SDimitry Andric   Instruction *DefX = nullptr;
17720b57cec5SDimitry Andric   PHINode *CntPhi = nullptr;
17730b57cec5SDimitry Andric   Instruction *CntInst = nullptr;
17740b57cec5SDimitry Andric   // Help decide if transformation is profitable. For ShiftUntilZero idiom,
17750b57cec5SDimitry Andric   // this is always 6.
17760b57cec5SDimitry Andric   size_t IdiomCanonicalSize = 6;
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric   if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX,
17790b57cec5SDimitry Andric                                  CntInst, CntPhi, DefX))
17800b57cec5SDimitry Andric     return false;
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   bool IsCntPhiUsedOutsideLoop = false;
17830b57cec5SDimitry Andric   for (User *U : CntPhi->users())
17840b57cec5SDimitry Andric     if (!CurLoop->contains(cast<Instruction>(U))) {
17850b57cec5SDimitry Andric       IsCntPhiUsedOutsideLoop = true;
17860b57cec5SDimitry Andric       break;
17870b57cec5SDimitry Andric     }
17880b57cec5SDimitry Andric   bool IsCntInstUsedOutsideLoop = false;
17890b57cec5SDimitry Andric   for (User *U : CntInst->users())
17900b57cec5SDimitry Andric     if (!CurLoop->contains(cast<Instruction>(U))) {
17910b57cec5SDimitry Andric       IsCntInstUsedOutsideLoop = true;
17920b57cec5SDimitry Andric       break;
17930b57cec5SDimitry Andric     }
17940b57cec5SDimitry Andric   // If both CntInst and CntPhi are used outside the loop the profitability
17950b57cec5SDimitry Andric   // is questionable.
17960b57cec5SDimitry Andric   if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
17970b57cec5SDimitry Andric     return false;
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric   // For some CPUs result of CTLZ(X) intrinsic is undefined
18000b57cec5SDimitry Andric   // when X is 0. If we can not guarantee X != 0, we need to check this
18010b57cec5SDimitry Andric   // when expand.
18020b57cec5SDimitry Andric   bool ZeroCheck = false;
18030b57cec5SDimitry Andric   // It is safe to assume Preheader exist as it was checked in
18040b57cec5SDimitry Andric   // parent function RunOnLoop.
18050b57cec5SDimitry Andric   BasicBlock *PH = CurLoop->getLoopPreheader();
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric   // If we are using the count instruction outside the loop, make sure we
18080b57cec5SDimitry Andric   // have a zero check as a precondition. Without the check the loop would run
18090b57cec5SDimitry Andric   // one iteration for before any check of the input value. This means 0 and 1
18100b57cec5SDimitry Andric   // would have identical behavior in the original loop and thus
18110b57cec5SDimitry Andric   if (!IsCntPhiUsedOutsideLoop) {
18120b57cec5SDimitry Andric     auto *PreCondBB = PH->getSinglePredecessor();
18130b57cec5SDimitry Andric     if (!PreCondBB)
18140b57cec5SDimitry Andric       return false;
18150b57cec5SDimitry Andric     auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
18160b57cec5SDimitry Andric     if (!PreCondBI)
18170b57cec5SDimitry Andric       return false;
18180b57cec5SDimitry Andric     if (matchCondition(PreCondBI, PH) != InitX)
18190b57cec5SDimitry Andric       return false;
18200b57cec5SDimitry Andric     ZeroCheck = true;
18210b57cec5SDimitry Andric   }
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric   // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
18240b57cec5SDimitry Andric   // profitable if we delete the loop.
18250b57cec5SDimitry Andric 
18260b57cec5SDimitry Andric   // the loop has only 6 instructions:
18270b57cec5SDimitry Andric   //  %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
18280b57cec5SDimitry Andric   //  %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
18290b57cec5SDimitry Andric   //  %shr = ashr %n.addr.0, 1
18300b57cec5SDimitry Andric   //  %tobool = icmp eq %shr, 0
18310b57cec5SDimitry Andric   //  %inc = add nsw %i.0, 1
18320b57cec5SDimitry Andric   //  br i1 %tobool
18330b57cec5SDimitry Andric 
1834fe6060f1SDimitry Andric   const Value *Args[] = {InitX,
1835fe6060f1SDimitry Andric                          ConstantInt::getBool(InitX->getContext(), ZeroCheck)};
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric   // @llvm.dbg doesn't count as they have no semantic effect.
18380b57cec5SDimitry Andric   auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug();
18390b57cec5SDimitry Andric   uint32_t HeaderSize =
18400b57cec5SDimitry Andric       std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());
18410b57cec5SDimitry Andric 
18425ffd83dbSDimitry Andric   IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args);
1843fe6060f1SDimitry Andric   InstructionCost Cost =
18445ffd83dbSDimitry Andric     TTI->getIntrinsicInstrCost(Attrs, TargetTransformInfo::TCK_SizeAndLatency);
18450b57cec5SDimitry Andric   if (HeaderSize != IdiomCanonicalSize &&
18465ffd83dbSDimitry Andric       Cost > TargetTransformInfo::TCC_Basic)
18470b57cec5SDimitry Andric     return false;
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric   transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
18500b57cec5SDimitry Andric                            DefX->getDebugLoc(), ZeroCheck,
18510b57cec5SDimitry Andric                            IsCntPhiUsedOutsideLoop);
18520b57cec5SDimitry Andric   return true;
18530b57cec5SDimitry Andric }
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric /// Recognizes a population count idiom in a non-countable loop.
18560b57cec5SDimitry Andric ///
18570b57cec5SDimitry Andric /// If detected, transforms the relevant code to issue the popcount intrinsic
18580b57cec5SDimitry Andric /// function call, and returns true; otherwise, returns false.
recognizePopcount()18590b57cec5SDimitry Andric bool LoopIdiomRecognize::recognizePopcount() {
18600b57cec5SDimitry Andric   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
18610b57cec5SDimitry Andric     return false;
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric   // Counting population are usually conducted by few arithmetic instructions.
18640b57cec5SDimitry Andric   // Such instructions can be easily "absorbed" by vacant slots in a
18650b57cec5SDimitry Andric   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
18660b57cec5SDimitry Andric   // in a compact loop.
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric   // Give up if the loop has multiple blocks or multiple backedges.
18690b57cec5SDimitry Andric   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
18700b57cec5SDimitry Andric     return false;
18710b57cec5SDimitry Andric 
18720b57cec5SDimitry Andric   BasicBlock *LoopBody = *(CurLoop->block_begin());
18730b57cec5SDimitry Andric   if (LoopBody->size() >= 20) {
18740b57cec5SDimitry Andric     // The loop is too big, bail out.
18750b57cec5SDimitry Andric     return false;
18760b57cec5SDimitry Andric   }
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric   // It should have a preheader containing nothing but an unconditional branch.
18790b57cec5SDimitry Andric   BasicBlock *PH = CurLoop->getLoopPreheader();
18800b57cec5SDimitry Andric   if (!PH || &PH->front() != PH->getTerminator())
18810b57cec5SDimitry Andric     return false;
18820b57cec5SDimitry Andric   auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
18830b57cec5SDimitry Andric   if (!EntryBI || EntryBI->isConditional())
18840b57cec5SDimitry Andric     return false;
18850b57cec5SDimitry Andric 
18860b57cec5SDimitry Andric   // It should have a precondition block where the generated popcount intrinsic
18870b57cec5SDimitry Andric   // function can be inserted.
18880b57cec5SDimitry Andric   auto *PreCondBB = PH->getSinglePredecessor();
18890b57cec5SDimitry Andric   if (!PreCondBB)
18900b57cec5SDimitry Andric     return false;
18910b57cec5SDimitry Andric   auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
18920b57cec5SDimitry Andric   if (!PreCondBI || PreCondBI->isUnconditional())
18930b57cec5SDimitry Andric     return false;
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric   Instruction *CntInst;
18960b57cec5SDimitry Andric   PHINode *CntPhi;
18970b57cec5SDimitry Andric   Value *Val;
18980b57cec5SDimitry Andric   if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
18990b57cec5SDimitry Andric     return false;
19000b57cec5SDimitry Andric 
19010b57cec5SDimitry Andric   transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
19020b57cec5SDimitry Andric   return true;
19030b57cec5SDimitry Andric }
19040b57cec5SDimitry Andric 
createPopcntIntrinsic(IRBuilder<> & IRBuilder,Value * Val,const DebugLoc & DL)19050b57cec5SDimitry Andric static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
19060b57cec5SDimitry Andric                                        const DebugLoc &DL) {
19070b57cec5SDimitry Andric   Value *Ops[] = {Val};
19080b57cec5SDimitry Andric   Type *Tys[] = {Val->getType()};
19090b57cec5SDimitry Andric 
19100b57cec5SDimitry Andric   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
19110b57cec5SDimitry Andric   Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
19120b57cec5SDimitry Andric   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
19130b57cec5SDimitry Andric   CI->setDebugLoc(DL);
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric   return CI;
19160b57cec5SDimitry Andric }
19170b57cec5SDimitry Andric 
createFFSIntrinsic(IRBuilder<> & IRBuilder,Value * Val,const DebugLoc & DL,bool ZeroCheck,Intrinsic::ID IID)19180b57cec5SDimitry Andric static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
19190b57cec5SDimitry Andric                                     const DebugLoc &DL, bool ZeroCheck,
19200b57cec5SDimitry Andric                                     Intrinsic::ID IID) {
1921fe6060f1SDimitry Andric   Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)};
19220b57cec5SDimitry Andric   Type *Tys[] = {Val->getType()};
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
19250b57cec5SDimitry Andric   Function *Func = Intrinsic::getDeclaration(M, IID, Tys);
19260b57cec5SDimitry Andric   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
19270b57cec5SDimitry Andric   CI->setDebugLoc(DL);
19280b57cec5SDimitry Andric 
19290b57cec5SDimitry Andric   return CI;
19300b57cec5SDimitry Andric }
19310b57cec5SDimitry Andric 
19320b57cec5SDimitry Andric /// Transform the following loop (Using CTLZ, CTTZ is similar):
19330b57cec5SDimitry Andric /// loop:
19340b57cec5SDimitry Andric ///   CntPhi = PHI [Cnt0, CntInst]
19350b57cec5SDimitry Andric ///   PhiX = PHI [InitX, DefX]
19360b57cec5SDimitry Andric ///   CntInst = CntPhi + 1
19370b57cec5SDimitry Andric ///   DefX = PhiX >> 1
19380b57cec5SDimitry Andric ///   LOOP_BODY
19390b57cec5SDimitry Andric ///   Br: loop if (DefX != 0)
19400b57cec5SDimitry Andric /// Use(CntPhi) or Use(CntInst)
19410b57cec5SDimitry Andric ///
19420b57cec5SDimitry Andric /// Into:
19430b57cec5SDimitry Andric /// If CntPhi used outside the loop:
19440b57cec5SDimitry Andric ///   CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
19450b57cec5SDimitry Andric ///   Count = CountPrev + 1
19460b57cec5SDimitry Andric /// else
19470b57cec5SDimitry Andric ///   Count = BitWidth(InitX) - CTLZ(InitX)
19480b57cec5SDimitry Andric /// loop:
19490b57cec5SDimitry Andric ///   CntPhi = PHI [Cnt0, CntInst]
19500b57cec5SDimitry Andric ///   PhiX = PHI [InitX, DefX]
19510b57cec5SDimitry Andric ///   PhiCount = PHI [Count, Dec]
19520b57cec5SDimitry Andric ///   CntInst = CntPhi + 1
19530b57cec5SDimitry Andric ///   DefX = PhiX >> 1
19540b57cec5SDimitry Andric ///   Dec = PhiCount - 1
19550b57cec5SDimitry Andric ///   LOOP_BODY
19560b57cec5SDimitry Andric ///   Br: loop if (Dec != 0)
19570b57cec5SDimitry Andric /// Use(CountPrev + Cnt0) // Use(CntPhi)
19580b57cec5SDimitry Andric /// or
19590b57cec5SDimitry Andric /// Use(Count + Cnt0) // Use(CntInst)
19600b57cec5SDimitry Andric ///
19610b57cec5SDimitry Andric /// If LOOP_BODY is empty the loop will be deleted.
19620b57cec5SDimitry Andric /// 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)19630b57cec5SDimitry Andric void LoopIdiomRecognize::transformLoopToCountable(
19640b57cec5SDimitry Andric     Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
19650b57cec5SDimitry Andric     PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
19660b57cec5SDimitry Andric     bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
19670b57cec5SDimitry Andric   BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
19680b57cec5SDimitry Andric 
19690b57cec5SDimitry Andric   // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
19700b57cec5SDimitry Andric   IRBuilder<> Builder(PreheaderBr);
19710b57cec5SDimitry Andric   Builder.SetCurrentDebugLocation(DL);
19720b57cec5SDimitry Andric 
1973fe6060f1SDimitry Andric   // If there are no uses of CntPhi crate:
19740b57cec5SDimitry Andric   //   Count = BitWidth - CTLZ(InitX);
1975e8d8bef9SDimitry Andric   //   NewCount = Count;
19760b57cec5SDimitry Andric   // If there are uses of CntPhi create:
1977e8d8bef9SDimitry Andric   //   NewCount = BitWidth - CTLZ(InitX >> 1);
1978e8d8bef9SDimitry Andric   //   Count = NewCount + 1;
1979e8d8bef9SDimitry Andric   Value *InitXNext;
19800b57cec5SDimitry Andric   if (IsCntPhiUsedOutsideLoop) {
19810b57cec5SDimitry Andric     if (DefX->getOpcode() == Instruction::AShr)
1982fe6060f1SDimitry Andric       InitXNext = Builder.CreateAShr(InitX, 1);
19830b57cec5SDimitry Andric     else if (DefX->getOpcode() == Instruction::LShr)
1984fe6060f1SDimitry Andric       InitXNext = Builder.CreateLShr(InitX, 1);
19850b57cec5SDimitry Andric     else if (DefX->getOpcode() == Instruction::Shl) // cttz
1986fe6060f1SDimitry Andric       InitXNext = Builder.CreateShl(InitX, 1);
19870b57cec5SDimitry Andric     else
19880b57cec5SDimitry Andric       llvm_unreachable("Unexpected opcode!");
19890b57cec5SDimitry Andric   } else
19900b57cec5SDimitry Andric     InitXNext = InitX;
1991fe6060f1SDimitry Andric   Value *Count =
1992fe6060f1SDimitry Andric       createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
1993fe6060f1SDimitry Andric   Type *CountTy = Count->getType();
1994fe6060f1SDimitry Andric   Count = Builder.CreateSub(
1995fe6060f1SDimitry Andric       ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count);
1996e8d8bef9SDimitry Andric   Value *NewCount = Count;
1997fe6060f1SDimitry Andric   if (IsCntPhiUsedOutsideLoop)
1998fe6060f1SDimitry Andric     Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1));
19990b57cec5SDimitry Andric 
2000fe6060f1SDimitry Andric   NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType());
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric   Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
2003e8d8bef9SDimitry Andric   if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) {
2004e8d8bef9SDimitry Andric     // If the counter was being incremented in the loop, add NewCount to the
2005e8d8bef9SDimitry Andric     // counter's initial value, but only if the initial value is not zero.
20060b57cec5SDimitry Andric     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
20070b57cec5SDimitry Andric     if (!InitConst || !InitConst->isZero())
20080b57cec5SDimitry Andric       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
2009e8d8bef9SDimitry Andric   } else {
2010e8d8bef9SDimitry Andric     // If the count was being decremented in the loop, subtract NewCount from
2011e8d8bef9SDimitry Andric     // the counter's initial value.
2012e8d8bef9SDimitry Andric     NewCount = Builder.CreateSub(CntInitVal, NewCount);
2013e8d8bef9SDimitry Andric   }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric   // Step 2: Insert new IV and loop condition:
20160b57cec5SDimitry Andric   // loop:
20170b57cec5SDimitry Andric   //   ...
20180b57cec5SDimitry Andric   //   PhiCount = PHI [Count, Dec]
20190b57cec5SDimitry Andric   //   ...
20200b57cec5SDimitry Andric   //   Dec = PhiCount - 1
20210b57cec5SDimitry Andric   //   ...
20220b57cec5SDimitry Andric   //   Br: loop if (Dec != 0)
20230b57cec5SDimitry Andric   BasicBlock *Body = *(CurLoop->block_begin());
20240b57cec5SDimitry Andric   auto *LbBr = cast<BranchInst>(Body->getTerminator());
20250b57cec5SDimitry Andric   ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
20260b57cec5SDimitry Andric 
20275f757f3fSDimitry Andric   PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi");
20285f757f3fSDimitry Andric   TcPhi->insertBefore(Body->begin());
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric   Builder.SetInsertPoint(LbCond);
2031fe6060f1SDimitry Andric   Instruction *TcDec = cast<Instruction>(Builder.CreateSub(
2032fe6060f1SDimitry Andric       TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true));
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric   TcPhi->addIncoming(Count, Preheader);
20350b57cec5SDimitry Andric   TcPhi->addIncoming(TcDec, Body);
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric   CmpInst::Predicate Pred =
20380b57cec5SDimitry Andric       (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
20390b57cec5SDimitry Andric   LbCond->setPredicate(Pred);
20400b57cec5SDimitry Andric   LbCond->setOperand(0, TcDec);
2041fe6060f1SDimitry Andric   LbCond->setOperand(1, ConstantInt::get(CountTy, 0));
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric   // Step 3: All the references to the original counter outside
20440b57cec5SDimitry Andric   //  the loop are replaced with the NewCount
20450b57cec5SDimitry Andric   if (IsCntPhiUsedOutsideLoop)
20460b57cec5SDimitry Andric     CntPhi->replaceUsesOutsideBlock(NewCount, Body);
20470b57cec5SDimitry Andric   else
20480b57cec5SDimitry Andric     CntInst->replaceUsesOutsideBlock(NewCount, Body);
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric   // step 4: Forget the "non-computable" trip-count SCEV associated with the
20510b57cec5SDimitry Andric   //   loop. The loop would otherwise not be deleted even if it becomes empty.
20520b57cec5SDimitry Andric   SE->forgetLoop(CurLoop);
20530b57cec5SDimitry Andric }
20540b57cec5SDimitry Andric 
transformLoopToPopcount(BasicBlock * PreCondBB,Instruction * CntInst,PHINode * CntPhi,Value * Var)20550b57cec5SDimitry Andric void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
20560b57cec5SDimitry Andric                                                  Instruction *CntInst,
20570b57cec5SDimitry Andric                                                  PHINode *CntPhi, Value *Var) {
20580b57cec5SDimitry Andric   BasicBlock *PreHead = CurLoop->getLoopPreheader();
20590b57cec5SDimitry Andric   auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());
20600b57cec5SDimitry Andric   const DebugLoc &DL = CntInst->getDebugLoc();
20610b57cec5SDimitry Andric 
20620b57cec5SDimitry Andric   // Assuming before transformation, the loop is following:
20630b57cec5SDimitry Andric   //  if (x) // the precondition
20640b57cec5SDimitry Andric   //     do { cnt++; x &= x - 1; } while(x);
20650b57cec5SDimitry Andric 
20660b57cec5SDimitry Andric   // Step 1: Insert the ctpop instruction at the end of the precondition block
20670b57cec5SDimitry Andric   IRBuilder<> Builder(PreCondBr);
20680b57cec5SDimitry Andric   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
20690b57cec5SDimitry Andric   {
20700b57cec5SDimitry Andric     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
20710b57cec5SDimitry Andric     NewCount = PopCntZext =
20720b57cec5SDimitry Andric         Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric     if (NewCount != PopCnt)
20750b57cec5SDimitry Andric       (cast<Instruction>(NewCount))->setDebugLoc(DL);
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric     // TripCnt is exactly the number of iterations the loop has
20780b57cec5SDimitry Andric     TripCnt = NewCount;
20790b57cec5SDimitry Andric 
20800b57cec5SDimitry Andric     // If the population counter's initial value is not zero, insert Add Inst.
20810b57cec5SDimitry Andric     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
20820b57cec5SDimitry Andric     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
20830b57cec5SDimitry Andric     if (!InitConst || !InitConst->isZero()) {
20840b57cec5SDimitry Andric       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
20850b57cec5SDimitry Andric       (cast<Instruction>(NewCount))->setDebugLoc(DL);
20860b57cec5SDimitry Andric     }
20870b57cec5SDimitry Andric   }
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
20900b57cec5SDimitry Andric   //   "if (NewCount == 0) loop-exit". Without this change, the intrinsic
20910b57cec5SDimitry Andric   //   function would be partial dead code, and downstream passes will drag
20920b57cec5SDimitry Andric   //   it back from the precondition block to the preheader.
20930b57cec5SDimitry Andric   {
20940b57cec5SDimitry Andric     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric     Value *Opnd0 = PopCntZext;
20970b57cec5SDimitry Andric     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
20980b57cec5SDimitry Andric     if (PreCond->getOperand(0) != Var)
20990b57cec5SDimitry Andric       std::swap(Opnd0, Opnd1);
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric     ICmpInst *NewPreCond = cast<ICmpInst>(
21020b57cec5SDimitry Andric         Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
21030b57cec5SDimitry Andric     PreCondBr->setCondition(NewPreCond);
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
21060b57cec5SDimitry Andric   }
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric   // Step 3: Note that the population count is exactly the trip count of the
21090b57cec5SDimitry Andric   // loop in question, which enable us to convert the loop from noncountable
21100b57cec5SDimitry Andric   // loop into a countable one. The benefit is twofold:
21110b57cec5SDimitry Andric   //
21120b57cec5SDimitry Andric   //  - If the loop only counts population, the entire loop becomes dead after
21130b57cec5SDimitry Andric   //    the transformation. It is a lot easier to prove a countable loop dead
21140b57cec5SDimitry Andric   //    than to prove a noncountable one. (In some C dialects, an infinite loop
21150b57cec5SDimitry Andric   //    isn't dead even if it computes nothing useful. In general, DCE needs
21160b57cec5SDimitry Andric   //    to prove a noncountable loop finite before safely delete it.)
21170b57cec5SDimitry Andric   //
21180b57cec5SDimitry Andric   //  - If the loop also performs something else, it remains alive.
21190b57cec5SDimitry Andric   //    Since it is transformed to countable form, it can be aggressively
21200b57cec5SDimitry Andric   //    optimized by some optimizations which are in general not applicable
21210b57cec5SDimitry Andric   //    to a noncountable loop.
21220b57cec5SDimitry Andric   //
21230b57cec5SDimitry Andric   // After this step, this loop (conceptually) would look like following:
21240b57cec5SDimitry Andric   //   newcnt = __builtin_ctpop(x);
21250b57cec5SDimitry Andric   //   t = newcnt;
21260b57cec5SDimitry Andric   //   if (x)
21270b57cec5SDimitry Andric   //     do { cnt++; x &= x-1; t--) } while (t > 0);
21280b57cec5SDimitry Andric   BasicBlock *Body = *(CurLoop->block_begin());
21290b57cec5SDimitry Andric   {
21300b57cec5SDimitry Andric     auto *LbBr = cast<BranchInst>(Body->getTerminator());
21310b57cec5SDimitry Andric     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
21320b57cec5SDimitry Andric     Type *Ty = TripCnt->getType();
21330b57cec5SDimitry Andric 
21345f757f3fSDimitry Andric     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi");
21355f757f3fSDimitry Andric     TcPhi->insertBefore(Body->begin());
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric     Builder.SetInsertPoint(LbCond);
21380b57cec5SDimitry Andric     Instruction *TcDec = cast<Instruction>(
21390b57cec5SDimitry Andric         Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
21400b57cec5SDimitry Andric                           "tcdec", false, true));
21410b57cec5SDimitry Andric 
21420b57cec5SDimitry Andric     TcPhi->addIncoming(TripCnt, PreHead);
21430b57cec5SDimitry Andric     TcPhi->addIncoming(TcDec, Body);
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric     CmpInst::Predicate Pred =
21460b57cec5SDimitry Andric         (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
21470b57cec5SDimitry Andric     LbCond->setPredicate(Pred);
21480b57cec5SDimitry Andric     LbCond->setOperand(0, TcDec);
21490b57cec5SDimitry Andric     LbCond->setOperand(1, ConstantInt::get(Ty, 0));
21500b57cec5SDimitry Andric   }
21510b57cec5SDimitry Andric 
21520b57cec5SDimitry Andric   // Step 4: All the references to the original population counter outside
21530b57cec5SDimitry Andric   //  the loop are replaced with the NewCount -- the value returned from
21540b57cec5SDimitry Andric   //  __builtin_ctpop().
21550b57cec5SDimitry Andric   CntInst->replaceUsesOutsideBlock(NewCount, Body);
21560b57cec5SDimitry Andric 
21570b57cec5SDimitry Andric   // step 5: Forget the "non-computable" trip-count SCEV associated with the
21580b57cec5SDimitry Andric   //   loop. The loop would otherwise not be deleted even if it becomes empty.
21590b57cec5SDimitry Andric   SE->forgetLoop(CurLoop);
21600b57cec5SDimitry Andric }
2161e8d8bef9SDimitry Andric 
2162e8d8bef9SDimitry Andric /// Match loop-invariant value.
2163e8d8bef9SDimitry Andric template <typename SubPattern_t> struct match_LoopInvariant {
2164e8d8bef9SDimitry Andric   SubPattern_t SubPattern;
2165e8d8bef9SDimitry Andric   const Loop *L;
2166e8d8bef9SDimitry Andric 
match_LoopInvariantmatch_LoopInvariant2167e8d8bef9SDimitry Andric   match_LoopInvariant(const SubPattern_t &SP, const Loop *L)
2168e8d8bef9SDimitry Andric       : SubPattern(SP), L(L) {}
2169e8d8bef9SDimitry Andric 
matchmatch_LoopInvariant2170e8d8bef9SDimitry Andric   template <typename ITy> bool match(ITy *V) {
2171e8d8bef9SDimitry Andric     return L->isLoopInvariant(V) && SubPattern.match(V);
2172e8d8bef9SDimitry Andric   }
2173e8d8bef9SDimitry Andric };
2174e8d8bef9SDimitry Andric 
2175e8d8bef9SDimitry Andric /// Matches if the value is loop-invariant.
2176e8d8bef9SDimitry Andric template <typename Ty>
m_LoopInvariant(const Ty & M,const Loop * L)2177e8d8bef9SDimitry Andric inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) {
2178e8d8bef9SDimitry Andric   return match_LoopInvariant<Ty>(M, L);
2179e8d8bef9SDimitry Andric }
2180e8d8bef9SDimitry Andric 
2181e8d8bef9SDimitry Andric /// Return true if the idiom is detected in the loop.
2182e8d8bef9SDimitry Andric ///
2183e8d8bef9SDimitry Andric /// The core idiom we are trying to detect is:
2184e8d8bef9SDimitry Andric /// \code
2185e8d8bef9SDimitry Andric ///   entry:
2186e8d8bef9SDimitry Andric ///     <...>
2187e8d8bef9SDimitry Andric ///     %bitmask = shl i32 1, %bitpos
2188e8d8bef9SDimitry Andric ///     br label %loop
2189e8d8bef9SDimitry Andric ///
2190e8d8bef9SDimitry Andric ///   loop:
2191e8d8bef9SDimitry Andric ///     %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
2192e8d8bef9SDimitry Andric ///     %x.curr.bitmasked = and i32 %x.curr, %bitmask
2193e8d8bef9SDimitry Andric ///     %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
2194e8d8bef9SDimitry Andric ///     %x.next = shl i32 %x.curr, 1
2195e8d8bef9SDimitry Andric ///     <...>
2196e8d8bef9SDimitry Andric ///     br i1 %x.curr.isbitunset, label %loop, label %end
2197e8d8bef9SDimitry Andric ///
2198e8d8bef9SDimitry Andric ///   end:
2199e8d8bef9SDimitry Andric ///     %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2200e8d8bef9SDimitry Andric ///     %x.next.res = phi i32 [ %x.next, %loop ] <...>
2201e8d8bef9SDimitry Andric ///     <...>
2202e8d8bef9SDimitry Andric /// \endcode
detectShiftUntilBitTestIdiom(Loop * CurLoop,Value * & BaseX,Value * & BitMask,Value * & BitPos,Value * & CurrX,Instruction * & NextX)2203e8d8bef9SDimitry Andric static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX,
2204e8d8bef9SDimitry Andric                                          Value *&BitMask, Value *&BitPos,
2205e8d8bef9SDimitry Andric                                          Value *&CurrX, Instruction *&NextX) {
2206e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << DEBUG_TYPE
2207e8d8bef9SDimitry Andric              " Performing shift-until-bittest idiom detection.\n");
2208e8d8bef9SDimitry Andric 
2209e8d8bef9SDimitry Andric   // Give up if the loop has multiple blocks or multiple backedges.
2210e8d8bef9SDimitry Andric   if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
2211e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
2212e8d8bef9SDimitry Andric     return false;
2213e8d8bef9SDimitry Andric   }
2214e8d8bef9SDimitry Andric 
2215e8d8bef9SDimitry Andric   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2216e8d8bef9SDimitry Andric   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2217e8d8bef9SDimitry Andric   assert(LoopPreheaderBB && "There is always a loop preheader.");
2218e8d8bef9SDimitry Andric 
2219e8d8bef9SDimitry Andric   using namespace PatternMatch;
2220e8d8bef9SDimitry Andric 
2221e8d8bef9SDimitry Andric   // Step 1: Check if the loop backedge is in desirable form.
2222e8d8bef9SDimitry Andric 
2223e8d8bef9SDimitry Andric   ICmpInst::Predicate Pred;
2224e8d8bef9SDimitry Andric   Value *CmpLHS, *CmpRHS;
2225e8d8bef9SDimitry Andric   BasicBlock *TrueBB, *FalseBB;
2226e8d8bef9SDimitry Andric   if (!match(LoopHeaderBB->getTerminator(),
2227e8d8bef9SDimitry Andric              m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
2228e8d8bef9SDimitry Andric                   m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) {
2229e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
2230e8d8bef9SDimitry Andric     return false;
2231e8d8bef9SDimitry Andric   }
2232e8d8bef9SDimitry Andric 
2233e8d8bef9SDimitry Andric   // Step 2: Check if the backedge's condition is in desirable form.
2234e8d8bef9SDimitry Andric 
2235e8d8bef9SDimitry Andric   auto MatchVariableBitMask = [&]() {
2236e8d8bef9SDimitry Andric     return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
2237e8d8bef9SDimitry Andric            match(CmpLHS,
2238e8d8bef9SDimitry Andric                  m_c_And(m_Value(CurrX),
2239e8d8bef9SDimitry Andric                          m_CombineAnd(
2240e8d8bef9SDimitry Andric                              m_Value(BitMask),
2241e8d8bef9SDimitry Andric                              m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)),
2242e8d8bef9SDimitry Andric                                              CurLoop))));
2243e8d8bef9SDimitry Andric   };
2244e8d8bef9SDimitry Andric   auto MatchConstantBitMask = [&]() {
2245e8d8bef9SDimitry Andric     return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
2246e8d8bef9SDimitry Andric            match(CmpLHS, m_And(m_Value(CurrX),
2247e8d8bef9SDimitry Andric                                m_CombineAnd(m_Value(BitMask), m_Power2()))) &&
2248e8d8bef9SDimitry Andric            (BitPos = ConstantExpr::getExactLogBase2(cast<Constant>(BitMask)));
2249e8d8bef9SDimitry Andric   };
2250e8d8bef9SDimitry Andric   auto MatchDecomposableConstantBitMask = [&]() {
2251e8d8bef9SDimitry Andric     APInt Mask;
2252e8d8bef9SDimitry Andric     return llvm::decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, CurrX, Mask) &&
2253e8d8bef9SDimitry Andric            ICmpInst::isEquality(Pred) && Mask.isPowerOf2() &&
2254e8d8bef9SDimitry Andric            (BitMask = ConstantInt::get(CurrX->getType(), Mask)) &&
2255e8d8bef9SDimitry Andric            (BitPos = ConstantInt::get(CurrX->getType(), Mask.logBase2()));
2256e8d8bef9SDimitry Andric   };
2257e8d8bef9SDimitry Andric 
2258e8d8bef9SDimitry Andric   if (!MatchVariableBitMask() && !MatchConstantBitMask() &&
2259e8d8bef9SDimitry Andric       !MatchDecomposableConstantBitMask()) {
2260e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n");
2261e8d8bef9SDimitry Andric     return false;
2262e8d8bef9SDimitry Andric   }
2263e8d8bef9SDimitry Andric 
2264e8d8bef9SDimitry Andric   // Step 3: Check if the recurrence is in desirable form.
2265e8d8bef9SDimitry Andric   auto *CurrXPN = dyn_cast<PHINode>(CurrX);
2266e8d8bef9SDimitry Andric   if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {
2267e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
2268e8d8bef9SDimitry Andric     return false;
2269e8d8bef9SDimitry Andric   }
2270e8d8bef9SDimitry Andric 
2271e8d8bef9SDimitry Andric   BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);
2272e8d8bef9SDimitry Andric   NextX =
2273e8d8bef9SDimitry Andric       dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB));
2274e8d8bef9SDimitry Andric 
2275fe6060f1SDimitry Andric   assert(CurLoop->isLoopInvariant(BaseX) &&
2276fe6060f1SDimitry Andric          "Expected BaseX to be avaliable in the preheader!");
2277fe6060f1SDimitry Andric 
2278e8d8bef9SDimitry Andric   if (!NextX || !match(NextX, m_Shl(m_Specific(CurrX), m_One()))) {
2279e8d8bef9SDimitry Andric     // FIXME: support right-shift?
2280e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
2281e8d8bef9SDimitry Andric     return false;
2282e8d8bef9SDimitry Andric   }
2283e8d8bef9SDimitry Andric 
2284e8d8bef9SDimitry Andric   // Step 4: Check if the backedge's destinations are in desirable form.
2285e8d8bef9SDimitry Andric 
2286e8d8bef9SDimitry Andric   assert(ICmpInst::isEquality(Pred) &&
2287e8d8bef9SDimitry Andric          "Should only get equality predicates here.");
2288e8d8bef9SDimitry Andric 
2289e8d8bef9SDimitry Andric   // cmp-br is commutative, so canonicalize to a single variant.
2290e8d8bef9SDimitry Andric   if (Pred != ICmpInst::Predicate::ICMP_EQ) {
2291e8d8bef9SDimitry Andric     Pred = ICmpInst::getInversePredicate(Pred);
2292e8d8bef9SDimitry Andric     std::swap(TrueBB, FalseBB);
2293e8d8bef9SDimitry Andric   }
2294e8d8bef9SDimitry Andric 
2295e8d8bef9SDimitry Andric   // We expect to exit loop when comparison yields false,
2296e8d8bef9SDimitry Andric   // so when it yields true we should branch back to loop header.
2297e8d8bef9SDimitry Andric   if (TrueBB != LoopHeaderBB) {
2298e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
2299e8d8bef9SDimitry Andric     return false;
2300e8d8bef9SDimitry Andric   }
2301e8d8bef9SDimitry Andric 
2302e8d8bef9SDimitry Andric   // Okay, idiom checks out.
2303e8d8bef9SDimitry Andric   return true;
2304e8d8bef9SDimitry Andric }
2305e8d8bef9SDimitry Andric 
2306e8d8bef9SDimitry Andric /// Look for the following loop:
2307e8d8bef9SDimitry Andric /// \code
2308e8d8bef9SDimitry Andric ///   entry:
2309e8d8bef9SDimitry Andric ///     <...>
2310e8d8bef9SDimitry Andric ///     %bitmask = shl i32 1, %bitpos
2311e8d8bef9SDimitry Andric ///     br label %loop
2312e8d8bef9SDimitry Andric ///
2313e8d8bef9SDimitry Andric ///   loop:
2314e8d8bef9SDimitry Andric ///     %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
2315e8d8bef9SDimitry Andric ///     %x.curr.bitmasked = and i32 %x.curr, %bitmask
2316e8d8bef9SDimitry Andric ///     %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
2317e8d8bef9SDimitry Andric ///     %x.next = shl i32 %x.curr, 1
2318e8d8bef9SDimitry Andric ///     <...>
2319e8d8bef9SDimitry Andric ///     br i1 %x.curr.isbitunset, label %loop, label %end
2320e8d8bef9SDimitry Andric ///
2321e8d8bef9SDimitry Andric ///   end:
2322e8d8bef9SDimitry Andric ///     %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2323e8d8bef9SDimitry Andric ///     %x.next.res = phi i32 [ %x.next, %loop ] <...>
2324e8d8bef9SDimitry Andric ///     <...>
2325e8d8bef9SDimitry Andric /// \endcode
2326e8d8bef9SDimitry Andric ///
2327e8d8bef9SDimitry Andric /// And transform it into:
2328e8d8bef9SDimitry Andric /// \code
2329e8d8bef9SDimitry Andric ///   entry:
2330e8d8bef9SDimitry Andric ///     %bitmask = shl i32 1, %bitpos
2331e8d8bef9SDimitry Andric ///     %lowbitmask = add i32 %bitmask, -1
2332e8d8bef9SDimitry Andric ///     %mask = or i32 %lowbitmask, %bitmask
2333e8d8bef9SDimitry Andric ///     %x.masked = and i32 %x, %mask
2334e8d8bef9SDimitry Andric ///     %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked,
2335e8d8bef9SDimitry Andric ///                                                         i1 true)
2336e8d8bef9SDimitry Andric ///     %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros
2337e8d8bef9SDimitry Andric ///     %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -1
2338e8d8bef9SDimitry Andric ///     %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos
2339e8d8bef9SDimitry Andric ///     %tripcount = add i32 %backedgetakencount, 1
2340e8d8bef9SDimitry Andric ///     %x.curr = shl i32 %x, %backedgetakencount
2341e8d8bef9SDimitry Andric ///     %x.next = shl i32 %x, %tripcount
2342e8d8bef9SDimitry Andric ///     br label %loop
2343e8d8bef9SDimitry Andric ///
2344e8d8bef9SDimitry Andric ///   loop:
2345e8d8bef9SDimitry Andric ///     %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ]
2346e8d8bef9SDimitry Andric ///     %loop.iv.next = add nuw i32 %loop.iv, 1
2347e8d8bef9SDimitry Andric ///     %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount
2348e8d8bef9SDimitry Andric ///     <...>
2349e8d8bef9SDimitry Andric ///     br i1 %loop.ivcheck, label %end, label %loop
2350e8d8bef9SDimitry Andric ///
2351e8d8bef9SDimitry Andric ///   end:
2352e8d8bef9SDimitry Andric ///     %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2353e8d8bef9SDimitry Andric ///     %x.next.res = phi i32 [ %x.next, %loop ] <...>
2354e8d8bef9SDimitry Andric ///     <...>
2355e8d8bef9SDimitry Andric /// \endcode
recognizeShiftUntilBitTest()2356e8d8bef9SDimitry Andric bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {
2357e8d8bef9SDimitry Andric   bool MadeChange = false;
2358e8d8bef9SDimitry Andric 
2359e8d8bef9SDimitry Andric   Value *X, *BitMask, *BitPos, *XCurr;
2360e8d8bef9SDimitry Andric   Instruction *XNext;
2361e8d8bef9SDimitry Andric   if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr,
2362e8d8bef9SDimitry Andric                                     XNext)) {
2363e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2364e8d8bef9SDimitry Andric                " shift-until-bittest idiom detection failed.\n");
2365e8d8bef9SDimitry Andric     return MadeChange;
2366e8d8bef9SDimitry Andric   }
2367e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n");
2368e8d8bef9SDimitry Andric 
2369e8d8bef9SDimitry Andric   // Ok, it is the idiom we were looking for, we *could* transform this loop,
2370e8d8bef9SDimitry Andric   // but is it profitable to transform?
2371e8d8bef9SDimitry Andric 
2372e8d8bef9SDimitry Andric   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2373e8d8bef9SDimitry Andric   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2374e8d8bef9SDimitry Andric   assert(LoopPreheaderBB && "There is always a loop preheader.");
2375e8d8bef9SDimitry Andric 
2376e8d8bef9SDimitry Andric   BasicBlock *SuccessorBB = CurLoop->getExitBlock();
2377fe6060f1SDimitry Andric   assert(SuccessorBB && "There is only a single successor.");
2378e8d8bef9SDimitry Andric 
2379e8d8bef9SDimitry Andric   IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
2380e8d8bef9SDimitry Andric   Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc());
2381e8d8bef9SDimitry Andric 
2382e8d8bef9SDimitry Andric   Intrinsic::ID IntrID = Intrinsic::ctlz;
2383e8d8bef9SDimitry Andric   Type *Ty = X->getType();
2384fe6060f1SDimitry Andric   unsigned Bitwidth = Ty->getScalarSizeInBits();
2385e8d8bef9SDimitry Andric 
2386e8d8bef9SDimitry Andric   TargetTransformInfo::TargetCostKind CostKind =
2387e8d8bef9SDimitry Andric       TargetTransformInfo::TCK_SizeAndLatency;
2388e8d8bef9SDimitry Andric 
2389e8d8bef9SDimitry Andric   // The rewrite is considered to be unprofitable iff and only iff the
2390e8d8bef9SDimitry Andric   // intrinsic/shift we'll use are not cheap. Note that we are okay with *just*
2391e8d8bef9SDimitry Andric   // making the loop countable, even if nothing else changes.
2392e8d8bef9SDimitry Andric   IntrinsicCostAttributes Attrs(
239306c3fb27SDimitry Andric       IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getTrue()});
2394fe6060f1SDimitry Andric   InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
2395e8d8bef9SDimitry Andric   if (Cost > TargetTransformInfo::TCC_Basic) {
2396e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2397e8d8bef9SDimitry Andric                " Intrinsic is too costly, not beneficial\n");
2398e8d8bef9SDimitry Andric     return MadeChange;
2399e8d8bef9SDimitry Andric   }
2400e8d8bef9SDimitry Andric   if (TTI->getArithmeticInstrCost(Instruction::Shl, Ty, CostKind) >
2401e8d8bef9SDimitry Andric       TargetTransformInfo::TCC_Basic) {
2402e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n");
2403e8d8bef9SDimitry Andric     return MadeChange;
2404e8d8bef9SDimitry Andric   }
2405e8d8bef9SDimitry Andric 
2406e8d8bef9SDimitry Andric   // Ok, transform appears worthwhile.
2407e8d8bef9SDimitry Andric   MadeChange = true;
2408e8d8bef9SDimitry Andric 
240906c3fb27SDimitry Andric   if (!isGuaranteedNotToBeUndefOrPoison(BitPos)) {
241006c3fb27SDimitry Andric     // BitMask may be computed from BitPos, Freeze BitPos so we can increase
241106c3fb27SDimitry Andric     // it's use count.
241206c3fb27SDimitry Andric     Instruction *InsertPt = nullptr;
241306c3fb27SDimitry Andric     if (auto *BitPosI = dyn_cast<Instruction>(BitPos))
24145f757f3fSDimitry Andric       InsertPt = &**BitPosI->getInsertionPointAfterDef();
241506c3fb27SDimitry Andric     else
241606c3fb27SDimitry Andric       InsertPt = &*DT->getRoot()->getFirstNonPHIOrDbgOrAlloca();
241706c3fb27SDimitry Andric     if (!InsertPt)
241806c3fb27SDimitry Andric       return false;
241906c3fb27SDimitry Andric     FreezeInst *BitPosFrozen =
242006c3fb27SDimitry Andric         new FreezeInst(BitPos, BitPos->getName() + ".fr", InsertPt);
242106c3fb27SDimitry Andric     BitPos->replaceUsesWithIf(BitPosFrozen, [BitPosFrozen](Use &U) {
242206c3fb27SDimitry Andric       return U.getUser() != BitPosFrozen;
242306c3fb27SDimitry Andric     });
242406c3fb27SDimitry Andric     BitPos = BitPosFrozen;
242506c3fb27SDimitry Andric   }
242606c3fb27SDimitry Andric 
2427e8d8bef9SDimitry Andric   // Step 1: Compute the loop trip count.
2428e8d8bef9SDimitry Andric 
2429e8d8bef9SDimitry Andric   Value *LowBitMask = Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty),
2430e8d8bef9SDimitry Andric                                         BitPos->getName() + ".lowbitmask");
2431e8d8bef9SDimitry Andric   Value *Mask =
2432e8d8bef9SDimitry Andric       Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask");
2433e8d8bef9SDimitry Andric   Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked");
2434e8d8bef9SDimitry Andric   CallInst *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(
243506c3fb27SDimitry Andric       IntrID, Ty, {XMasked, /*is_zero_poison=*/Builder.getTrue()},
2436e8d8bef9SDimitry Andric       /*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros");
2437e8d8bef9SDimitry Andric   Value *XMaskedNumActiveBits = Builder.CreateSub(
2438e8d8bef9SDimitry Andric       ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros,
2439fe6060f1SDimitry Andric       XMasked->getName() + ".numactivebits", /*HasNUW=*/true,
2440fe6060f1SDimitry Andric       /*HasNSW=*/Bitwidth != 2);
2441e8d8bef9SDimitry Andric   Value *XMaskedLeadingOnePos =
2442e8d8bef9SDimitry Andric       Builder.CreateAdd(XMaskedNumActiveBits, Constant::getAllOnesValue(Ty),
2443fe6060f1SDimitry Andric                         XMasked->getName() + ".leadingonepos", /*HasNUW=*/false,
2444fe6060f1SDimitry Andric                         /*HasNSW=*/Bitwidth > 2);
2445e8d8bef9SDimitry Andric 
2446e8d8bef9SDimitry Andric   Value *LoopBackedgeTakenCount = Builder.CreateSub(
2447fe6060f1SDimitry Andric       BitPos, XMaskedLeadingOnePos, CurLoop->getName() + ".backedgetakencount",
2448fe6060f1SDimitry Andric       /*HasNUW=*/true, /*HasNSW=*/true);
2449e8d8bef9SDimitry Andric   // We know loop's backedge-taken count, but what's loop's trip count?
2450e8d8bef9SDimitry Andric   // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
2451e8d8bef9SDimitry Andric   Value *LoopTripCount =
2452fe6060f1SDimitry Andric       Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
2453fe6060f1SDimitry Andric                         CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
2454fe6060f1SDimitry Andric                         /*HasNSW=*/Bitwidth != 2);
2455e8d8bef9SDimitry Andric 
2456e8d8bef9SDimitry Andric   // Step 2: Compute the recurrence's final value without a loop.
2457e8d8bef9SDimitry Andric 
2458e8d8bef9SDimitry Andric   // NewX is always safe to compute, because `LoopBackedgeTakenCount`
2459e8d8bef9SDimitry Andric   // will always be smaller than `bitwidth(X)`, i.e. we never get poison.
2460e8d8bef9SDimitry Andric   Value *NewX = Builder.CreateShl(X, LoopBackedgeTakenCount);
2461e8d8bef9SDimitry Andric   NewX->takeName(XCurr);
2462e8d8bef9SDimitry Andric   if (auto *I = dyn_cast<Instruction>(NewX))
2463e8d8bef9SDimitry Andric     I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
2464e8d8bef9SDimitry Andric 
2465e8d8bef9SDimitry Andric   Value *NewXNext;
2466e8d8bef9SDimitry Andric   // Rewriting XNext is more complicated, however, because `X << LoopTripCount`
2467e8d8bef9SDimitry Andric   // will be poison iff `LoopTripCount == bitwidth(X)` (which will happen
2468e8d8bef9SDimitry Andric   // iff `BitPos` is `bitwidth(x) - 1` and `X` is `1`). So unless we know
2469e8d8bef9SDimitry Andric   // that isn't the case, we'll need to emit an alternative, safe IR.
2470e8d8bef9SDimitry Andric   if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() ||
2471e8d8bef9SDimitry Andric       PatternMatch::match(
2472e8d8bef9SDimitry Andric           BitPos, PatternMatch::m_SpecificInt_ICMP(
2473e8d8bef9SDimitry Andric                       ICmpInst::ICMP_NE, APInt(Ty->getScalarSizeInBits(),
2474e8d8bef9SDimitry Andric                                                Ty->getScalarSizeInBits() - 1))))
2475e8d8bef9SDimitry Andric     NewXNext = Builder.CreateShl(X, LoopTripCount);
2476e8d8bef9SDimitry Andric   else {
2477e8d8bef9SDimitry Andric     // Otherwise, just additionally shift by one. It's the smallest solution,
2478e8d8bef9SDimitry Andric     // alternatively, we could check that NewX is INT_MIN (or BitPos is )
2479e8d8bef9SDimitry Andric     // and select 0 instead.
2480e8d8bef9SDimitry Andric     NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));
2481e8d8bef9SDimitry Andric   }
2482e8d8bef9SDimitry Andric 
2483e8d8bef9SDimitry Andric   NewXNext->takeName(XNext);
2484e8d8bef9SDimitry Andric   if (auto *I = dyn_cast<Instruction>(NewXNext))
2485e8d8bef9SDimitry Andric     I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
2486e8d8bef9SDimitry Andric 
2487e8d8bef9SDimitry Andric   // Step 3: Adjust the successor basic block to recieve the computed
2488e8d8bef9SDimitry Andric   //         recurrence's final value instead of the recurrence itself.
2489e8d8bef9SDimitry Andric 
2490e8d8bef9SDimitry Andric   XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB);
2491e8d8bef9SDimitry Andric   XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB);
2492e8d8bef9SDimitry Andric 
2493e8d8bef9SDimitry Andric   // Step 4: Rewrite the loop into a countable form, with canonical IV.
2494e8d8bef9SDimitry Andric 
2495e8d8bef9SDimitry Andric   // The new canonical induction variable.
24965f757f3fSDimitry Andric   Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->begin());
2497e8d8bef9SDimitry Andric   auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
2498e8d8bef9SDimitry Andric 
2499e8d8bef9SDimitry Andric   // The induction itself.
2500e8d8bef9SDimitry Andric   // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
2501e8d8bef9SDimitry Andric   Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
2502fe6060f1SDimitry Andric   auto *IVNext =
2503fe6060f1SDimitry Andric       Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
2504fe6060f1SDimitry Andric                         /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
2505e8d8bef9SDimitry Andric 
2506e8d8bef9SDimitry Andric   // The loop trip count check.
2507e8d8bef9SDimitry Andric   auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,
2508e8d8bef9SDimitry Andric                                        CurLoop->getName() + ".ivcheck");
2509e8d8bef9SDimitry Andric   Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);
2510e8d8bef9SDimitry Andric   LoopHeaderBB->getTerminator()->eraseFromParent();
2511e8d8bef9SDimitry Andric 
2512e8d8bef9SDimitry Andric   // Populate the IV PHI.
2513e8d8bef9SDimitry Andric   IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
2514e8d8bef9SDimitry Andric   IV->addIncoming(IVNext, LoopHeaderBB);
2515e8d8bef9SDimitry Andric 
2516e8d8bef9SDimitry Andric   // Step 5: Forget the "non-computable" trip-count SCEV associated with the
2517e8d8bef9SDimitry Andric   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2518e8d8bef9SDimitry Andric 
2519e8d8bef9SDimitry Andric   SE->forgetLoop(CurLoop);
2520e8d8bef9SDimitry Andric 
2521e8d8bef9SDimitry Andric   // Other passes will take care of actually deleting the loop if possible.
2522e8d8bef9SDimitry Andric 
2523e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n");
2524e8d8bef9SDimitry Andric 
2525e8d8bef9SDimitry Andric   ++NumShiftUntilBitTest;
2526e8d8bef9SDimitry Andric   return MadeChange;
2527e8d8bef9SDimitry Andric }
2528fe6060f1SDimitry Andric 
2529fe6060f1SDimitry Andric /// Return true if the idiom is detected in the loop.
2530fe6060f1SDimitry Andric ///
2531fe6060f1SDimitry Andric /// The core idiom we are trying to detect is:
2532fe6060f1SDimitry Andric /// \code
2533fe6060f1SDimitry Andric ///   entry:
2534fe6060f1SDimitry Andric ///     <...>
2535fe6060f1SDimitry Andric ///     %start = <...>
2536fe6060f1SDimitry Andric ///     %extraoffset = <...>
2537fe6060f1SDimitry Andric ///     <...>
2538fe6060f1SDimitry Andric ///     br label %for.cond
2539fe6060f1SDimitry Andric ///
2540fe6060f1SDimitry Andric ///   loop:
2541fe6060f1SDimitry Andric ///     %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
2542fe6060f1SDimitry Andric ///     %nbits = add nsw i8 %iv, %extraoffset
2543fe6060f1SDimitry Andric ///     %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
2544fe6060f1SDimitry Andric ///     %val.shifted.iszero = icmp eq i8 %val.shifted, 0
2545fe6060f1SDimitry Andric ///     %iv.next = add i8 %iv, 1
2546fe6060f1SDimitry Andric ///     <...>
2547fe6060f1SDimitry Andric ///     br i1 %val.shifted.iszero, label %end, label %loop
2548fe6060f1SDimitry Andric ///
2549fe6060f1SDimitry Andric ///   end:
2550fe6060f1SDimitry Andric ///     %iv.res = phi i8 [ %iv, %loop ] <...>
2551fe6060f1SDimitry Andric ///     %nbits.res = phi i8 [ %nbits, %loop ] <...>
2552fe6060f1SDimitry Andric ///     %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
2553fe6060f1SDimitry Andric ///     %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
2554fe6060f1SDimitry Andric ///     %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
2555fe6060f1SDimitry Andric ///     <...>
2556fe6060f1SDimitry Andric /// \endcode
detectShiftUntilZeroIdiom(Loop * CurLoop,ScalarEvolution * SE,Instruction * & ValShiftedIsZero,Intrinsic::ID & IntrinID,Instruction * & IV,Value * & Start,Value * & Val,const SCEV * & ExtraOffsetExpr,bool & InvertedCond)2557fe6060f1SDimitry Andric static bool detectShiftUntilZeroIdiom(Loop *CurLoop, ScalarEvolution *SE,
2558fe6060f1SDimitry Andric                                       Instruction *&ValShiftedIsZero,
2559fe6060f1SDimitry Andric                                       Intrinsic::ID &IntrinID, Instruction *&IV,
2560fe6060f1SDimitry Andric                                       Value *&Start, Value *&Val,
2561fe6060f1SDimitry Andric                                       const SCEV *&ExtraOffsetExpr,
2562fe6060f1SDimitry Andric                                       bool &InvertedCond) {
2563fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << DEBUG_TYPE
2564fe6060f1SDimitry Andric              " Performing shift-until-zero idiom detection.\n");
2565fe6060f1SDimitry Andric 
2566fe6060f1SDimitry Andric   // Give up if the loop has multiple blocks or multiple backedges.
2567fe6060f1SDimitry Andric   if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
2568fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
2569fe6060f1SDimitry Andric     return false;
2570fe6060f1SDimitry Andric   }
2571fe6060f1SDimitry Andric 
2572fe6060f1SDimitry Andric   Instruction *ValShifted, *NBits, *IVNext;
2573fe6060f1SDimitry Andric   Value *ExtraOffset;
2574fe6060f1SDimitry Andric 
2575fe6060f1SDimitry Andric   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2576fe6060f1SDimitry Andric   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2577fe6060f1SDimitry Andric   assert(LoopPreheaderBB && "There is always a loop preheader.");
2578fe6060f1SDimitry Andric 
2579fe6060f1SDimitry Andric   using namespace PatternMatch;
2580fe6060f1SDimitry Andric 
2581fe6060f1SDimitry Andric   // Step 1: Check if the loop backedge, condition is in desirable form.
2582fe6060f1SDimitry Andric 
2583fe6060f1SDimitry Andric   ICmpInst::Predicate Pred;
2584fe6060f1SDimitry Andric   BasicBlock *TrueBB, *FalseBB;
2585fe6060f1SDimitry Andric   if (!match(LoopHeaderBB->getTerminator(),
2586fe6060f1SDimitry Andric              m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB),
2587fe6060f1SDimitry Andric                   m_BasicBlock(FalseBB))) ||
2588fe6060f1SDimitry Andric       !match(ValShiftedIsZero,
2589fe6060f1SDimitry Andric              m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) ||
2590fe6060f1SDimitry Andric       !ICmpInst::isEquality(Pred)) {
2591fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
2592fe6060f1SDimitry Andric     return false;
2593fe6060f1SDimitry Andric   }
2594fe6060f1SDimitry Andric 
2595fe6060f1SDimitry Andric   // Step 2: Check if the comparison's operand is in desirable form.
2596fe6060f1SDimitry Andric   // FIXME: Val could be a one-input PHI node, which we should look past.
2597fe6060f1SDimitry Andric   if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop),
2598fe6060f1SDimitry Andric                                  m_Instruction(NBits)))) {
2599fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n");
2600fe6060f1SDimitry Andric     return false;
2601fe6060f1SDimitry Andric   }
2602fe6060f1SDimitry Andric   IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz
2603fe6060f1SDimitry Andric                                                          : Intrinsic::ctlz;
2604fe6060f1SDimitry Andric 
2605fe6060f1SDimitry Andric   // Step 3: Check if the shift amount is in desirable form.
2606fe6060f1SDimitry Andric 
2607fe6060f1SDimitry Andric   if (match(NBits, m_c_Add(m_Instruction(IV),
2608fe6060f1SDimitry Andric                            m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
2609fe6060f1SDimitry Andric       (NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap()))
2610fe6060f1SDimitry Andric     ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset));
2611fe6060f1SDimitry Andric   else if (match(NBits,
2612fe6060f1SDimitry Andric                  m_Sub(m_Instruction(IV),
2613fe6060f1SDimitry Andric                        m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
2614fe6060f1SDimitry Andric            NBits->hasNoSignedWrap())
2615fe6060f1SDimitry Andric     ExtraOffsetExpr = SE->getSCEV(ExtraOffset);
2616fe6060f1SDimitry Andric   else {
2617fe6060f1SDimitry Andric     IV = NBits;
2618fe6060f1SDimitry Andric     ExtraOffsetExpr = SE->getZero(NBits->getType());
2619fe6060f1SDimitry Andric   }
2620fe6060f1SDimitry Andric 
2621fe6060f1SDimitry Andric   // Step 4: Check if the recurrence is in desirable form.
2622fe6060f1SDimitry Andric   auto *IVPN = dyn_cast<PHINode>(IV);
2623fe6060f1SDimitry Andric   if (!IVPN || IVPN->getParent() != LoopHeaderBB) {
2624fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
2625fe6060f1SDimitry Andric     return false;
2626fe6060f1SDimitry Andric   }
2627fe6060f1SDimitry Andric 
2628fe6060f1SDimitry Andric   Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);
2629fe6060f1SDimitry Andric   IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB));
2630fe6060f1SDimitry Andric 
2631fe6060f1SDimitry Andric   if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) {
2632fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
2633fe6060f1SDimitry Andric     return false;
2634fe6060f1SDimitry Andric   }
2635fe6060f1SDimitry Andric 
2636fe6060f1SDimitry Andric   // Step 4: Check if the backedge's destinations are in desirable form.
2637fe6060f1SDimitry Andric 
2638fe6060f1SDimitry Andric   assert(ICmpInst::isEquality(Pred) &&
2639fe6060f1SDimitry Andric          "Should only get equality predicates here.");
2640fe6060f1SDimitry Andric 
2641fe6060f1SDimitry Andric   // cmp-br is commutative, so canonicalize to a single variant.
2642fe6060f1SDimitry Andric   InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ;
2643fe6060f1SDimitry Andric   if (InvertedCond) {
2644fe6060f1SDimitry Andric     Pred = ICmpInst::getInversePredicate(Pred);
2645fe6060f1SDimitry Andric     std::swap(TrueBB, FalseBB);
2646fe6060f1SDimitry Andric   }
2647fe6060f1SDimitry Andric 
2648fe6060f1SDimitry Andric   // We expect to exit loop when comparison yields true,
2649fe6060f1SDimitry Andric   // so when it yields false we should branch back to loop header.
2650fe6060f1SDimitry Andric   if (FalseBB != LoopHeaderBB) {
2651fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
2652fe6060f1SDimitry Andric     return false;
2653fe6060f1SDimitry Andric   }
2654fe6060f1SDimitry Andric 
2655fe6060f1SDimitry Andric   // The new, countable, loop will certainly only run a known number of
2656fe6060f1SDimitry Andric   // iterations, It won't be infinite. But the old loop might be infinite
2657fe6060f1SDimitry Andric   // under certain conditions. For logical shifts, the value will become zero
2658fe6060f1SDimitry Andric   // after at most bitwidth(%Val) loop iterations. However, for arithmetic
2659fe6060f1SDimitry Andric   // right-shift, iff the sign bit was set, the value will never become zero,
2660fe6060f1SDimitry Andric   // and the loop may never finish.
2661fe6060f1SDimitry Andric   if (ValShifted->getOpcode() == Instruction::AShr &&
2662fe6060f1SDimitry Andric       !isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) {
2663fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n");
2664fe6060f1SDimitry Andric     return false;
2665fe6060f1SDimitry Andric   }
2666fe6060f1SDimitry Andric 
2667fe6060f1SDimitry Andric   // Okay, idiom checks out.
2668fe6060f1SDimitry Andric   return true;
2669fe6060f1SDimitry Andric }
2670fe6060f1SDimitry Andric 
2671fe6060f1SDimitry Andric /// Look for the following loop:
2672fe6060f1SDimitry Andric /// \code
2673fe6060f1SDimitry Andric ///   entry:
2674fe6060f1SDimitry Andric ///     <...>
2675fe6060f1SDimitry Andric ///     %start = <...>
2676fe6060f1SDimitry Andric ///     %extraoffset = <...>
2677fe6060f1SDimitry Andric ///     <...>
2678fe6060f1SDimitry Andric ///     br label %for.cond
2679fe6060f1SDimitry Andric ///
2680fe6060f1SDimitry Andric ///   loop:
2681fe6060f1SDimitry Andric ///     %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
2682fe6060f1SDimitry Andric ///     %nbits = add nsw i8 %iv, %extraoffset
2683fe6060f1SDimitry Andric ///     %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
2684fe6060f1SDimitry Andric ///     %val.shifted.iszero = icmp eq i8 %val.shifted, 0
2685fe6060f1SDimitry Andric ///     %iv.next = add i8 %iv, 1
2686fe6060f1SDimitry Andric ///     <...>
2687fe6060f1SDimitry Andric ///     br i1 %val.shifted.iszero, label %end, label %loop
2688fe6060f1SDimitry Andric ///
2689fe6060f1SDimitry Andric ///   end:
2690fe6060f1SDimitry Andric ///     %iv.res = phi i8 [ %iv, %loop ] <...>
2691fe6060f1SDimitry Andric ///     %nbits.res = phi i8 [ %nbits, %loop ] <...>
2692fe6060f1SDimitry Andric ///     %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
2693fe6060f1SDimitry Andric ///     %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
2694fe6060f1SDimitry Andric ///     %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
2695fe6060f1SDimitry Andric ///     <...>
2696fe6060f1SDimitry Andric /// \endcode
2697fe6060f1SDimitry Andric ///
2698fe6060f1SDimitry Andric /// And transform it into:
2699fe6060f1SDimitry Andric /// \code
2700fe6060f1SDimitry Andric ///   entry:
2701fe6060f1SDimitry Andric ///     <...>
2702fe6060f1SDimitry Andric ///     %start = <...>
2703fe6060f1SDimitry Andric ///     %extraoffset = <...>
2704fe6060f1SDimitry Andric ///     <...>
2705fe6060f1SDimitry Andric ///     %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0)
2706fe6060f1SDimitry Andric ///     %val.numactivebits = sub i8 8, %val.numleadingzeros
2707fe6060f1SDimitry Andric ///     %extraoffset.neg = sub i8 0, %extraoffset
2708fe6060f1SDimitry Andric ///     %tmp = add i8 %val.numactivebits, %extraoffset.neg
2709fe6060f1SDimitry Andric ///     %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start)
2710fe6060f1SDimitry Andric ///     %loop.tripcount = sub i8 %iv.final, %start
2711fe6060f1SDimitry Andric ///     br label %loop
2712fe6060f1SDimitry Andric ///
2713fe6060f1SDimitry Andric ///   loop:
2714fe6060f1SDimitry Andric ///     %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ]
2715fe6060f1SDimitry Andric ///     %loop.iv.next = add i8 %loop.iv, 1
2716fe6060f1SDimitry Andric ///     %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount
2717fe6060f1SDimitry Andric ///     %iv = add i8 %loop.iv, %start
2718fe6060f1SDimitry Andric ///     <...>
2719fe6060f1SDimitry Andric ///     br i1 %loop.ivcheck, label %end, label %loop
2720fe6060f1SDimitry Andric ///
2721fe6060f1SDimitry Andric ///   end:
2722fe6060f1SDimitry Andric ///     %iv.res = phi i8 [ %iv.final, %loop ] <...>
2723fe6060f1SDimitry Andric ///     <...>
2724fe6060f1SDimitry Andric /// \endcode
recognizeShiftUntilZero()2725fe6060f1SDimitry Andric bool LoopIdiomRecognize::recognizeShiftUntilZero() {
2726fe6060f1SDimitry Andric   bool MadeChange = false;
2727fe6060f1SDimitry Andric 
2728fe6060f1SDimitry Andric   Instruction *ValShiftedIsZero;
2729fe6060f1SDimitry Andric   Intrinsic::ID IntrID;
2730fe6060f1SDimitry Andric   Instruction *IV;
2731fe6060f1SDimitry Andric   Value *Start, *Val;
2732fe6060f1SDimitry Andric   const SCEV *ExtraOffsetExpr;
2733fe6060f1SDimitry Andric   bool InvertedCond;
2734fe6060f1SDimitry Andric   if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV,
2735fe6060f1SDimitry Andric                                  Start, Val, ExtraOffsetExpr, InvertedCond)) {
2736fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2737fe6060f1SDimitry Andric                " shift-until-zero idiom detection failed.\n");
2738fe6060f1SDimitry Andric     return MadeChange;
2739fe6060f1SDimitry Andric   }
2740fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n");
2741fe6060f1SDimitry Andric 
2742fe6060f1SDimitry Andric   // Ok, it is the idiom we were looking for, we *could* transform this loop,
2743fe6060f1SDimitry Andric   // but is it profitable to transform?
2744fe6060f1SDimitry Andric 
2745fe6060f1SDimitry Andric   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2746fe6060f1SDimitry Andric   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2747fe6060f1SDimitry Andric   assert(LoopPreheaderBB && "There is always a loop preheader.");
2748fe6060f1SDimitry Andric 
2749fe6060f1SDimitry Andric   BasicBlock *SuccessorBB = CurLoop->getExitBlock();
2750fe6060f1SDimitry Andric   assert(SuccessorBB && "There is only a single successor.");
2751fe6060f1SDimitry Andric 
2752fe6060f1SDimitry Andric   IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
2753fe6060f1SDimitry Andric   Builder.SetCurrentDebugLocation(IV->getDebugLoc());
2754fe6060f1SDimitry Andric 
2755fe6060f1SDimitry Andric   Type *Ty = Val->getType();
2756fe6060f1SDimitry Andric   unsigned Bitwidth = Ty->getScalarSizeInBits();
2757fe6060f1SDimitry Andric 
2758fe6060f1SDimitry Andric   TargetTransformInfo::TargetCostKind CostKind =
2759fe6060f1SDimitry Andric       TargetTransformInfo::TCK_SizeAndLatency;
2760fe6060f1SDimitry Andric 
2761fe6060f1SDimitry Andric   // The rewrite is considered to be unprofitable iff and only iff the
2762fe6060f1SDimitry Andric   // intrinsic we'll use are not cheap. Note that we are okay with *just*
2763fe6060f1SDimitry Andric   // making the loop countable, even if nothing else changes.
2764fe6060f1SDimitry Andric   IntrinsicCostAttributes Attrs(
276506c3fb27SDimitry Andric       IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getFalse()});
2766fe6060f1SDimitry Andric   InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
2767fe6060f1SDimitry Andric   if (Cost > TargetTransformInfo::TCC_Basic) {
2768fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2769fe6060f1SDimitry Andric                " Intrinsic is too costly, not beneficial\n");
2770fe6060f1SDimitry Andric     return MadeChange;
2771fe6060f1SDimitry Andric   }
2772fe6060f1SDimitry Andric 
2773fe6060f1SDimitry Andric   // Ok, transform appears worthwhile.
2774fe6060f1SDimitry Andric   MadeChange = true;
2775fe6060f1SDimitry Andric 
2776fe6060f1SDimitry Andric   bool OffsetIsZero = false;
2777fe6060f1SDimitry Andric   if (auto *ExtraOffsetExprC = dyn_cast<SCEVConstant>(ExtraOffsetExpr))
2778fe6060f1SDimitry Andric     OffsetIsZero = ExtraOffsetExprC->isZero();
2779fe6060f1SDimitry Andric 
2780fe6060f1SDimitry Andric   // Step 1: Compute the loop's final IV value / trip count.
2781fe6060f1SDimitry Andric 
2782fe6060f1SDimitry Andric   CallInst *ValNumLeadingZeros = Builder.CreateIntrinsic(
278306c3fb27SDimitry Andric       IntrID, Ty, {Val, /*is_zero_poison=*/Builder.getFalse()},
2784fe6060f1SDimitry Andric       /*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros");
2785fe6060f1SDimitry Andric   Value *ValNumActiveBits = Builder.CreateSub(
2786fe6060f1SDimitry Andric       ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros,
2787fe6060f1SDimitry Andric       Val->getName() + ".numactivebits", /*HasNUW=*/true,
2788fe6060f1SDimitry Andric       /*HasNSW=*/Bitwidth != 2);
2789fe6060f1SDimitry Andric 
2790fe6060f1SDimitry Andric   SCEVExpander Expander(*SE, *DL, "loop-idiom");
2791fe6060f1SDimitry Andric   Expander.setInsertPoint(&*Builder.GetInsertPoint());
2792fe6060f1SDimitry Andric   Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);
2793fe6060f1SDimitry Andric 
2794fe6060f1SDimitry Andric   Value *ValNumActiveBitsOffset = Builder.CreateAdd(
2795fe6060f1SDimitry Andric       ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset",
2796fe6060f1SDimitry Andric       /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true);
2797fe6060f1SDimitry Andric   Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},
2798fe6060f1SDimitry Andric                                            {ValNumActiveBitsOffset, Start},
2799fe6060f1SDimitry Andric                                            /*FMFSource=*/nullptr, "iv.final");
2800fe6060f1SDimitry Andric 
2801fe6060f1SDimitry Andric   auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub(
2802fe6060f1SDimitry Andric       IVFinal, Start, CurLoop->getName() + ".backedgetakencount",
2803fe6060f1SDimitry Andric       /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true));
2804fe6060f1SDimitry Andric   // FIXME: or when the offset was `add nuw`
2805fe6060f1SDimitry Andric 
2806fe6060f1SDimitry Andric   // We know loop's backedge-taken count, but what's loop's trip count?
2807fe6060f1SDimitry Andric   Value *LoopTripCount =
2808fe6060f1SDimitry Andric       Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
2809fe6060f1SDimitry Andric                         CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
2810fe6060f1SDimitry Andric                         /*HasNSW=*/Bitwidth != 2);
2811fe6060f1SDimitry Andric 
2812fe6060f1SDimitry Andric   // Step 2: Adjust the successor basic block to recieve the original
2813fe6060f1SDimitry Andric   //         induction variable's final value instead of the orig. IV itself.
2814fe6060f1SDimitry Andric 
2815fe6060f1SDimitry Andric   IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);
2816fe6060f1SDimitry Andric 
2817fe6060f1SDimitry Andric   // Step 3: Rewrite the loop into a countable form, with canonical IV.
2818fe6060f1SDimitry Andric 
2819fe6060f1SDimitry Andric   // The new canonical induction variable.
28205f757f3fSDimitry Andric   Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->begin());
2821fe6060f1SDimitry Andric   auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
2822fe6060f1SDimitry Andric 
2823fe6060f1SDimitry Andric   // The induction itself.
28245f757f3fSDimitry Andric   Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->getFirstNonPHIIt());
2825fe6060f1SDimitry Andric   auto *CIVNext =
2826fe6060f1SDimitry Andric       Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next",
2827fe6060f1SDimitry Andric                         /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
2828fe6060f1SDimitry Andric 
2829fe6060f1SDimitry Andric   // The loop trip count check.
2830fe6060f1SDimitry Andric   auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,
2831fe6060f1SDimitry Andric                                         CurLoop->getName() + ".ivcheck");
2832fe6060f1SDimitry Andric   auto *NewIVCheck = CIVCheck;
2833fe6060f1SDimitry Andric   if (InvertedCond) {
2834fe6060f1SDimitry Andric     NewIVCheck = Builder.CreateNot(CIVCheck);
2835fe6060f1SDimitry Andric     NewIVCheck->takeName(ValShiftedIsZero);
2836fe6060f1SDimitry Andric   }
2837fe6060f1SDimitry Andric 
2838fe6060f1SDimitry Andric   // The original IV, but rebased to be an offset to the CIV.
2839fe6060f1SDimitry Andric   auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false,
2840fe6060f1SDimitry Andric                                      /*HasNSW=*/true); // FIXME: what about NUW?
2841fe6060f1SDimitry Andric   IVDePHId->takeName(IV);
2842fe6060f1SDimitry Andric 
2843fe6060f1SDimitry Andric   // The loop terminator.
2844fe6060f1SDimitry Andric   Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
2845fe6060f1SDimitry Andric   Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);
2846fe6060f1SDimitry Andric   LoopHeaderBB->getTerminator()->eraseFromParent();
2847fe6060f1SDimitry Andric 
2848fe6060f1SDimitry Andric   // Populate the IV PHI.
2849fe6060f1SDimitry Andric   CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
2850fe6060f1SDimitry Andric   CIV->addIncoming(CIVNext, LoopHeaderBB);
2851fe6060f1SDimitry Andric 
2852fe6060f1SDimitry Andric   // Step 4: Forget the "non-computable" trip-count SCEV associated with the
2853fe6060f1SDimitry Andric   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2854fe6060f1SDimitry Andric 
2855fe6060f1SDimitry Andric   SE->forgetLoop(CurLoop);
2856fe6060f1SDimitry Andric 
2857fe6060f1SDimitry Andric   // Step 5: Try to cleanup the loop's body somewhat.
2858fe6060f1SDimitry Andric   IV->replaceAllUsesWith(IVDePHId);
2859fe6060f1SDimitry Andric   IV->eraseFromParent();
2860fe6060f1SDimitry Andric 
2861fe6060f1SDimitry Andric   ValShiftedIsZero->replaceAllUsesWith(NewIVCheck);
2862fe6060f1SDimitry Andric   ValShiftedIsZero->eraseFromParent();
2863fe6060f1SDimitry Andric 
2864fe6060f1SDimitry Andric   // Other passes will take care of actually deleting the loop if possible.
2865fe6060f1SDimitry Andric 
2866fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n");
2867fe6060f1SDimitry Andric 
2868fe6060f1SDimitry Andric   ++NumShiftUntilZero;
2869fe6060f1SDimitry Andric   return MadeChange;
2870fe6060f1SDimitry Andric }
2871