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