1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements an idiom recognizer that transforms simple loops into a
11 // non-loop form.  In cases that this kicks in, it can be a significant
12 // performance win.
13 //
14 //===----------------------------------------------------------------------===//
15 //
16 // TODO List:
17 //
18 // Future loop memory idioms to recognize:
19 //   memcmp, memmove, strlen, etc.
20 // Future floating point idioms to recognize in -ffast-math mode:
21 //   fpowi
22 // Future integer operation idioms to recognize:
23 //   ctpop, ctlz, cttz
24 //
25 // Beware that isel's default lowering for ctpop is highly inefficient for
26 // i64 and larger types when i64 is legal and the value has few bits set.  It
27 // would be good to enhance isel to emit a loop for ctpop in this case.
28 //
29 // This could recognize common matrix multiplies and dot product idioms and
30 // replace them with calls to BLAS (if linked in??).
31 //
32 //===----------------------------------------------------------------------===//
33 
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/ADT/MapVector.h"
36 #include "llvm/ADT/SetVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Analysis/BasicAliasAnalysis.h"
40 #include "llvm/Analysis/GlobalsModRef.h"
41 #include "llvm/Analysis/LoopPass.h"
42 #include "llvm/Analysis/LoopAccessAnalysis.h"
43 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
44 #include "llvm/Analysis/ScalarEvolutionExpander.h"
45 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
46 #include "llvm/Analysis/TargetLibraryInfo.h"
47 #include "llvm/Analysis/TargetTransformInfo.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/Dominators.h"
51 #include "llvm/IR/IRBuilder.h"
52 #include "llvm/IR/IntrinsicInst.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/LoopUtils.h"
58 using namespace llvm;
59 
60 #define DEBUG_TYPE "loop-idiom"
61 
62 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
63 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
64 
65 namespace {
66 
67 class LoopIdiomRecognize : public LoopPass {
68   Loop *CurLoop;
69   AliasAnalysis *AA;
70   DominatorTree *DT;
71   LoopInfo *LI;
72   ScalarEvolution *SE;
73   TargetLibraryInfo *TLI;
74   const TargetTransformInfo *TTI;
75   const DataLayout *DL;
76 
77 public:
78   static char ID;
79   explicit LoopIdiomRecognize() : LoopPass(ID) {
80     initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
81   }
82 
83   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
84 
85   /// This transformation requires natural loop information & requires that
86   /// loop preheaders be inserted into the CFG.
87   ///
88   void getAnalysisUsage(AnalysisUsage &AU) const override {
89     AU.addRequired<TargetLibraryInfoWrapperPass>();
90     AU.addRequired<TargetTransformInfoWrapperPass>();
91     getLoopAnalysisUsage(AU);
92   }
93 
94 private:
95   typedef SmallVector<StoreInst *, 8> StoreList;
96   typedef MapVector<Value *, StoreList> StoreListMap;
97   StoreListMap StoreRefsForMemset;
98   StoreListMap StoreRefsForMemsetPattern;
99   StoreList StoreRefsForMemcpy;
100   bool HasMemset;
101   bool HasMemsetPattern;
102   bool HasMemcpy;
103 
104   /// \name Countable Loop Idiom Handling
105   /// @{
106 
107   bool runOnCountableLoop();
108   bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
109                       SmallVectorImpl<BasicBlock *> &ExitBlocks);
110 
111   void collectStores(BasicBlock *BB);
112   bool isLegalStore(StoreInst *SI, bool &ForMemset, bool &ForMemsetPattern,
113                     bool &ForMemcpy);
114   bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
115                          bool ForMemset);
116   bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
117 
118   bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
119                                unsigned StoreAlignment, Value *StoredVal,
120                                Instruction *TheStore,
121                                SmallPtrSetImpl<Instruction *> &Stores,
122                                const SCEVAddRecExpr *Ev, const SCEV *BECount,
123                                bool NegStride);
124   bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
125 
126   /// @}
127   /// \name Noncountable Loop Idiom Handling
128   /// @{
129 
130   bool runOnNoncountableLoop();
131 
132   bool recognizePopcount();
133   void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
134                                PHINode *CntPhi, Value *Var);
135 
136   /// @}
137 };
138 
139 } // End anonymous namespace.
140 
141 char LoopIdiomRecognize::ID = 0;
142 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
143                       false, false)
144 INITIALIZE_PASS_DEPENDENCY(LoopPass)
145 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
146 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
147 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
148                     false, false)
149 
150 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
151 
152 /// deleteDeadInstruction - Delete this instruction.  Before we do, go through
153 /// and zero out all the operands of this instruction.  If any of them become
154 /// dead, delete them and the computation tree that feeds them.
155 ///
156 static void deleteDeadInstruction(Instruction *I,
157                                   const TargetLibraryInfo *TLI) {
158   SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
159   I->replaceAllUsesWith(UndefValue::get(I->getType()));
160   I->eraseFromParent();
161   for (Value *Op : Operands)
162     RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
163 }
164 
165 //===----------------------------------------------------------------------===//
166 //
167 //          Implementation of LoopIdiomRecognize
168 //
169 //===----------------------------------------------------------------------===//
170 
171 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
172   if (skipOptnoneFunction(L))
173     return false;
174 
175   CurLoop = L;
176   // If the loop could not be converted to canonical form, it must have an
177   // indirectbr in it, just give up.
178   if (!L->getLoopPreheader())
179     return false;
180 
181   // Disable loop idiom recognition if the function's name is a common idiom.
182   StringRef Name = L->getHeader()->getParent()->getName();
183   if (Name == "memset" || Name == "memcpy")
184     return false;
185 
186   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
187   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
188   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
189   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
190   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
191   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
192       *CurLoop->getHeader()->getParent());
193   DL = &CurLoop->getHeader()->getModule()->getDataLayout();
194 
195   HasMemset = TLI->has(LibFunc::memset);
196   HasMemsetPattern = TLI->has(LibFunc::memset_pattern16);
197   HasMemcpy = TLI->has(LibFunc::memcpy);
198 
199   if (HasMemset || HasMemsetPattern || HasMemcpy)
200     if (SE->hasLoopInvariantBackedgeTakenCount(L))
201       return runOnCountableLoop();
202 
203   return runOnNoncountableLoop();
204 }
205 
206 bool LoopIdiomRecognize::runOnCountableLoop() {
207   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
208   assert(!isa<SCEVCouldNotCompute>(BECount) &&
209          "runOnCountableLoop() called on a loop without a predictable"
210          "backedge-taken count");
211 
212   // If this loop executes exactly one time, then it should be peeled, not
213   // optimized by this pass.
214   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
215     if (BECst->getAPInt() == 0)
216       return false;
217 
218   SmallVector<BasicBlock *, 8> ExitBlocks;
219   CurLoop->getUniqueExitBlocks(ExitBlocks);
220 
221   DEBUG(dbgs() << "loop-idiom Scanning: F["
222                << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
223                << CurLoop->getHeader()->getName() << "\n");
224 
225   bool MadeChange = false;
226   // Scan all the blocks in the loop that are not in subloops.
227   for (auto *BB : CurLoop->getBlocks()) {
228     // Ignore blocks in subloops.
229     if (LI->getLoopFor(BB) != CurLoop)
230       continue;
231 
232     MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
233   }
234   return MadeChange;
235 }
236 
237 static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
238   uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
239   assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
240          "Don't overflow unsigned.");
241   return (unsigned)SizeInBits >> 3;
242 }
243 
244 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
245   const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
246   return ConstStride->getAPInt();
247 }
248 
249 /// getMemSetPatternValue - If a strided store of the specified value is safe to
250 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
251 /// be passed in.  Otherwise, return null.
252 ///
253 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
254 /// just replicate their input array and then pass on to memset_pattern16.
255 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
256   // If the value isn't a constant, we can't promote it to being in a constant
257   // array.  We could theoretically do a store to an alloca or something, but
258   // that doesn't seem worthwhile.
259   Constant *C = dyn_cast<Constant>(V);
260   if (!C)
261     return nullptr;
262 
263   // Only handle simple values that are a power of two bytes in size.
264   uint64_t Size = DL->getTypeSizeInBits(V->getType());
265   if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
266     return nullptr;
267 
268   // Don't care enough about darwin/ppc to implement this.
269   if (DL->isBigEndian())
270     return nullptr;
271 
272   // Convert to size in bytes.
273   Size /= 8;
274 
275   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
276   // if the top and bottom are the same (e.g. for vectors and large integers).
277   if (Size > 16)
278     return nullptr;
279 
280   // If the constant is exactly 16 bytes, just use it.
281   if (Size == 16)
282     return C;
283 
284   // Otherwise, we'll use an array of the constants.
285   unsigned ArraySize = 16 / Size;
286   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
287   return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
288 }
289 
290 bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset,
291                                       bool &ForMemsetPattern, bool &ForMemcpy) {
292   // Don't touch volatile stores.
293   if (!SI->isSimple())
294     return false;
295 
296   // Avoid merging nontemporal stores.
297   if (SI->getMetadata(LLVMContext::MD_nontemporal))
298     return false;
299 
300   Value *StoredVal = SI->getValueOperand();
301   Value *StorePtr = SI->getPointerOperand();
302 
303   // Reject stores that are so large that they overflow an unsigned.
304   uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
305   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
306     return false;
307 
308   // See if the pointer expression is an AddRec like {base,+,1} on the current
309   // loop, which indicates a strided store.  If we have something else, it's a
310   // random store we can't handle.
311   const SCEVAddRecExpr *StoreEv =
312       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
313   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
314     return false;
315 
316   // Check to see if we have a constant stride.
317   if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
318     return false;
319 
320   // See if the store can be turned into a memset.
321 
322   // If the stored value is a byte-wise value (like i32 -1), then it may be
323   // turned into a memset of i8 -1, assuming that all the consecutive bytes
324   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
325   // but it can be turned into memset_pattern if the target supports it.
326   Value *SplatValue = isBytewiseValue(StoredVal);
327   Constant *PatternValue = nullptr;
328 
329   // If we're allowed to form a memset, and the stored value would be
330   // acceptable for memset, use it.
331   if (HasMemset && SplatValue &&
332       // Verify that the stored value is loop invariant.  If not, we can't
333       // promote the memset.
334       CurLoop->isLoopInvariant(SplatValue)) {
335     // It looks like we can use SplatValue.
336     ForMemset = true;
337     return true;
338   } else if (HasMemsetPattern &&
339              // Don't create memset_pattern16s with address spaces.
340              StorePtr->getType()->getPointerAddressSpace() == 0 &&
341              (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
342     // It looks like we can use PatternValue!
343     ForMemsetPattern = true;
344     return true;
345   }
346 
347   // Otherwise, see if the store can be turned into a memcpy.
348   if (HasMemcpy) {
349     // Check to see if the stride matches the size of the store.  If so, then we
350     // know that every byte is touched in the loop.
351     APInt Stride = getStoreStride(StoreEv);
352     unsigned StoreSize = getStoreSizeInBytes(SI, DL);
353     if (StoreSize != Stride && StoreSize != -Stride)
354       return false;
355 
356     // The store must be feeding a non-volatile load.
357     LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
358     if (!LI || !LI->isSimple())
359       return false;
360 
361     // See if the pointer expression is an AddRec like {base,+,1} on the current
362     // loop, which indicates a strided load.  If we have something else, it's a
363     // random load we can't handle.
364     const SCEVAddRecExpr *LoadEv =
365         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
366     if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
367       return false;
368 
369     // The store and load must share the same stride.
370     if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
371       return false;
372 
373     // Success.  This store can be converted into a memcpy.
374     ForMemcpy = true;
375     return true;
376   }
377   // This store can't be transformed into a memset/memcpy.
378   return false;
379 }
380 
381 void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
382   StoreRefsForMemset.clear();
383   StoreRefsForMemsetPattern.clear();
384   StoreRefsForMemcpy.clear();
385   for (Instruction &I : *BB) {
386     StoreInst *SI = dyn_cast<StoreInst>(&I);
387     if (!SI)
388       continue;
389 
390     bool ForMemset = false;
391     bool ForMemsetPattern = false;
392     bool ForMemcpy = false;
393     // Make sure this is a strided store with a constant stride.
394     if (!isLegalStore(SI, ForMemset, ForMemsetPattern, ForMemcpy))
395       continue;
396 
397     // Save the store locations.
398     if (ForMemset) {
399       // Find the base pointer.
400       Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
401       StoreRefsForMemset[Ptr].push_back(SI);
402     } else if (ForMemsetPattern) {
403       // Find the base pointer.
404       Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
405       StoreRefsForMemsetPattern[Ptr].push_back(SI);
406     } else if (ForMemcpy)
407       StoreRefsForMemcpy.push_back(SI);
408   }
409 }
410 
411 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
412 /// with the specified backedge count.  This block is known to be in the current
413 /// loop and not in any subloops.
414 bool LoopIdiomRecognize::runOnLoopBlock(
415     BasicBlock *BB, const SCEV *BECount,
416     SmallVectorImpl<BasicBlock *> &ExitBlocks) {
417   // We can only promote stores in this block if they are unconditionally
418   // executed in the loop.  For a block to be unconditionally executed, it has
419   // to dominate all the exit blocks of the loop.  Verify this now.
420   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
421     if (!DT->dominates(BB, ExitBlocks[i]))
422       return false;
423 
424   bool MadeChange = false;
425   // Look for store instructions, which may be optimized to memset/memcpy.
426   collectStores(BB);
427 
428   // Look for a single store or sets of stores with a common base, which can be
429   // optimized into a memset (memset_pattern).  The latter most commonly happens
430   // with structs and handunrolled loops.
431   for (auto &SL : StoreRefsForMemset)
432     MadeChange |= processLoopStores(SL.second, BECount, true);
433 
434   for (auto &SL : StoreRefsForMemsetPattern)
435     MadeChange |= processLoopStores(SL.second, BECount, false);
436 
437   // Optimize the store into a memcpy, if it feeds an similarly strided load.
438   for (auto &SI : StoreRefsForMemcpy)
439     MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
440 
441   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
442     Instruction *Inst = &*I++;
443     // Look for memset instructions, which may be optimized to a larger memset.
444     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
445       WeakVH InstPtr(&*I);
446       if (!processLoopMemSet(MSI, BECount))
447         continue;
448       MadeChange = true;
449 
450       // If processing the memset invalidated our iterator, start over from the
451       // top of the block.
452       if (!InstPtr)
453         I = BB->begin();
454       continue;
455     }
456   }
457 
458   return MadeChange;
459 }
460 
461 /// processLoopStores - See if this store(s) can be promoted to a memset.
462 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
463                                            const SCEV *BECount,
464                                            bool ForMemset) {
465   // Try to find consecutive stores that can be transformed into memsets.
466   SetVector<StoreInst *> Heads, Tails;
467   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
468 
469   // Do a quadratic search on all of the given stores and find
470   // all of the pairs of stores that follow each other.
471   SmallVector<unsigned, 16> IndexQueue;
472   for (unsigned i = 0, e = SL.size(); i < e; ++i) {
473     assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
474 
475     Value *FirstStoredVal = SL[i]->getValueOperand();
476     Value *FirstStorePtr = SL[i]->getPointerOperand();
477     const SCEVAddRecExpr *FirstStoreEv =
478         cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
479     APInt FirstStride = getStoreStride(FirstStoreEv);
480     unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL);
481 
482     // See if we can optimize just this store in isolation.
483     if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
484       Heads.insert(SL[i]);
485       continue;
486     }
487 
488     Value *FirstSplatValue = nullptr;
489     Constant *FirstPatternValue = nullptr;
490 
491     if (ForMemset)
492       FirstSplatValue = isBytewiseValue(FirstStoredVal);
493     else
494       FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
495 
496     assert((FirstSplatValue || FirstPatternValue) &&
497            "Expected either splat value or pattern value.");
498 
499     IndexQueue.clear();
500     // If a store has multiple consecutive store candidates, search Stores
501     // array according to the sequence: from i+1 to e, then from i-1 to 0.
502     // This is because usually pairing with immediate succeeding or preceding
503     // candidate create the best chance to find memset opportunity.
504     unsigned j = 0;
505     for (j = i + 1; j < e; ++j)
506       IndexQueue.push_back(j);
507     for (j = i; j > 0; --j)
508       IndexQueue.push_back(j - 1);
509 
510     for (auto &k : IndexQueue) {
511       assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
512       Value *SecondStorePtr = SL[k]->getPointerOperand();
513       const SCEVAddRecExpr *SecondStoreEv =
514           cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
515       APInt SecondStride = getStoreStride(SecondStoreEv);
516 
517       if (FirstStride != SecondStride)
518         continue;
519 
520       Value *SecondStoredVal = SL[k]->getValueOperand();
521       Value *SecondSplatValue = nullptr;
522       Constant *SecondPatternValue = nullptr;
523 
524       if (ForMemset)
525         SecondSplatValue = isBytewiseValue(SecondStoredVal);
526       else
527         SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
528 
529       assert((SecondSplatValue || SecondPatternValue) &&
530              "Expected either splat value or pattern value.");
531 
532       if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
533         if (ForMemset) {
534           if (FirstSplatValue != SecondSplatValue)
535             continue;
536         } else {
537           if (FirstPatternValue != SecondPatternValue)
538             continue;
539         }
540         Tails.insert(SL[k]);
541         Heads.insert(SL[i]);
542         ConsecutiveChain[SL[i]] = SL[k];
543         break;
544       }
545     }
546   }
547 
548   // We may run into multiple chains that merge into a single chain. We mark the
549   // stores that we transformed so that we don't visit the same store twice.
550   SmallPtrSet<Value *, 16> TransformedStores;
551   bool Changed = false;
552 
553   // For stores that start but don't end a link in the chain:
554   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
555        it != e; ++it) {
556     if (Tails.count(*it))
557       continue;
558 
559     // We found a store instr that starts a chain. Now follow the chain and try
560     // to transform it.
561     SmallPtrSet<Instruction *, 8> AdjacentStores;
562     StoreInst *I = *it;
563 
564     StoreInst *HeadStore = I;
565     unsigned StoreSize = 0;
566 
567     // Collect the chain into a list.
568     while (Tails.count(I) || Heads.count(I)) {
569       if (TransformedStores.count(I))
570         break;
571       AdjacentStores.insert(I);
572 
573       StoreSize += getStoreSizeInBytes(I, DL);
574       // Move to the next value in the chain.
575       I = ConsecutiveChain[I];
576     }
577 
578     Value *StoredVal = HeadStore->getValueOperand();
579     Value *StorePtr = HeadStore->getPointerOperand();
580     const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
581     APInt Stride = getStoreStride(StoreEv);
582 
583     // Check to see if the stride matches the size of the stores.  If so, then
584     // we know that every byte is touched in the loop.
585     if (StoreSize != Stride && StoreSize != -Stride)
586       continue;
587 
588     bool NegStride = StoreSize == -Stride;
589 
590     if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
591                                 StoredVal, HeadStore, AdjacentStores, StoreEv,
592                                 BECount, NegStride)) {
593       TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
594       Changed = true;
595     }
596   }
597 
598   return Changed;
599 }
600 
601 /// processLoopMemSet - See if this memset can be promoted to a large memset.
602 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
603                                            const SCEV *BECount) {
604   // We can only handle non-volatile memsets with a constant size.
605   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
606     return false;
607 
608   // If we're not allowed to hack on memset, we fail.
609   if (!TLI->has(LibFunc::memset))
610     return false;
611 
612   Value *Pointer = MSI->getDest();
613 
614   // See if the pointer expression is an AddRec like {base,+,1} on the current
615   // loop, which indicates a strided store.  If we have something else, it's a
616   // random store we can't handle.
617   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
618   if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
619     return false;
620 
621   // Reject memsets that are so large that they overflow an unsigned.
622   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
623   if ((SizeInBytes >> 32) != 0)
624     return false;
625 
626   // Check to see if the stride matches the size of the memset.  If so, then we
627   // know that every byte is touched in the loop.
628   const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
629   if (!ConstStride)
630     return false;
631 
632   APInt Stride = ConstStride->getAPInt();
633   if (SizeInBytes != Stride && SizeInBytes != -Stride)
634     return false;
635 
636   // Verify that the memset value is loop invariant.  If not, we can't promote
637   // the memset.
638   Value *SplatValue = MSI->getValue();
639   if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
640     return false;
641 
642   SmallPtrSet<Instruction *, 1> MSIs;
643   MSIs.insert(MSI);
644   bool NegStride = SizeInBytes == -Stride;
645   return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
646                                  MSI->getAlignment(), SplatValue, MSI, MSIs, Ev,
647                                  BECount, NegStride);
648 }
649 
650 /// mayLoopAccessLocation - Return true if the specified loop might access the
651 /// specified pointer location, which is a loop-strided access.  The 'Access'
652 /// argument specifies what the verboten forms of access are (read or write).
653 static bool
654 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
655                       const SCEV *BECount, unsigned StoreSize,
656                       AliasAnalysis &AA,
657                       SmallPtrSetImpl<Instruction *> &IgnoredStores) {
658   // Get the location that may be stored across the loop.  Since the access is
659   // strided positively through memory, we say that the modified location starts
660   // at the pointer and has infinite size.
661   uint64_t AccessSize = MemoryLocation::UnknownSize;
662 
663   // If the loop iterates a fixed number of times, we can refine the access size
664   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
665   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
666     AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
667 
668   // TODO: For this to be really effective, we have to dive into the pointer
669   // operand in the store.  Store to &A[i] of 100 will always return may alias
670   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
671   // which will then no-alias a store to &A[100].
672   MemoryLocation StoreLoc(Ptr, AccessSize);
673 
674   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
675        ++BI)
676     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
677       if (IgnoredStores.count(&*I) == 0 &&
678           (AA.getModRefInfo(&*I, StoreLoc) & Access))
679         return true;
680 
681   return false;
682 }
683 
684 // If we have a negative stride, Start refers to the end of the memory location
685 // we're trying to memset.  Therefore, we need to recompute the base pointer,
686 // which is just Start - BECount*Size.
687 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
688                                         Type *IntPtr, unsigned StoreSize,
689                                         ScalarEvolution *SE) {
690   const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
691   if (StoreSize != 1)
692     Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
693                            SCEV::FlagNUW);
694   return SE->getMinusSCEV(Start, Index);
695 }
696 
697 /// processLoopStridedStore - We see a strided store of some value.  If we can
698 /// transform this into a memset or memset_pattern in the loop preheader, do so.
699 bool LoopIdiomRecognize::processLoopStridedStore(
700     Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
701     Value *StoredVal, Instruction *TheStore,
702     SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
703     const SCEV *BECount, bool NegStride) {
704   Value *SplatValue = isBytewiseValue(StoredVal);
705   Constant *PatternValue = nullptr;
706 
707   if (!SplatValue)
708     PatternValue = getMemSetPatternValue(StoredVal, DL);
709 
710   assert((SplatValue || PatternValue) &&
711          "Expected either splat value or pattern value.");
712 
713   // The trip count of the loop and the base pointer of the addrec SCEV is
714   // guaranteed to be loop invariant, which means that it should dominate the
715   // header.  This allows us to insert code for it in the preheader.
716   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
717   BasicBlock *Preheader = CurLoop->getLoopPreheader();
718   IRBuilder<> Builder(Preheader->getTerminator());
719   SCEVExpander Expander(*SE, *DL, "loop-idiom");
720 
721   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
722   Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
723 
724   const SCEV *Start = Ev->getStart();
725   // Handle negative strided loops.
726   if (NegStride)
727     Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
728 
729   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
730   // this into a memset in the loop preheader now if we want.  However, this
731   // would be unsafe to do if there is anything else in the loop that may read
732   // or write to the aliased location.  Check for any overlap by generating the
733   // base pointer and checking the region.
734   Value *BasePtr =
735       Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
736   if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
737                             *AA, Stores)) {
738     Expander.clear();
739     // If we generated new code for the base pointer, clean up.
740     RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
741     return false;
742   }
743 
744   // Okay, everything looks good, insert the memset.
745 
746   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
747   // pointer size if it isn't already.
748   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
749 
750   const SCEV *NumBytesS =
751       SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
752   if (StoreSize != 1) {
753     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
754                                SCEV::FlagNUW);
755   }
756 
757   Value *NumBytes =
758       Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
759 
760   CallInst *NewCall;
761   if (SplatValue) {
762     NewCall =
763         Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
764   } else {
765     // Everything is emitted in default address space
766     Type *Int8PtrTy = DestInt8PtrTy;
767 
768     Module *M = TheStore->getModule();
769     Value *MSP =
770         M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
771                                Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
772 
773     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
774     // an constant array of 16-bytes.  Plop the value into a mergable global.
775     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
776                                             GlobalValue::PrivateLinkage,
777                                             PatternValue, ".memset_pattern");
778     GV->setUnnamedAddr(true); // Ok to merge these.
779     GV->setAlignment(16);
780     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
781     NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
782   }
783 
784   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
785                << "    from store to: " << *Ev << " at: " << *TheStore << "\n");
786   NewCall->setDebugLoc(TheStore->getDebugLoc());
787 
788   // Okay, the memset has been formed.  Zap the original store and anything that
789   // feeds into it.
790   for (auto *I : Stores)
791     deleteDeadInstruction(I, TLI);
792   ++NumMemSet;
793   return true;
794 }
795 
796 /// If the stored value is a strided load in the same loop with the same stride
797 /// this may be transformable into a memcpy.  This kicks in for stuff like
798 ///   for (i) A[i] = B[i];
799 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
800                                                     const SCEV *BECount) {
801   assert(SI->isSimple() && "Expected only non-volatile stores.");
802 
803   Value *StorePtr = SI->getPointerOperand();
804   const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
805   APInt Stride = getStoreStride(StoreEv);
806   unsigned StoreSize = getStoreSizeInBytes(SI, DL);
807   bool NegStride = StoreSize == -Stride;
808 
809   // The store must be feeding a non-volatile load.
810   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
811   assert(LI->isSimple() && "Expected only non-volatile stores.");
812 
813   // See if the pointer expression is an AddRec like {base,+,1} on the current
814   // loop, which indicates a strided load.  If we have something else, it's a
815   // random load we can't handle.
816   const SCEVAddRecExpr *LoadEv =
817       cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
818 
819   // The trip count of the loop and the base pointer of the addrec SCEV is
820   // guaranteed to be loop invariant, which means that it should dominate the
821   // header.  This allows us to insert code for it in the preheader.
822   BasicBlock *Preheader = CurLoop->getLoopPreheader();
823   IRBuilder<> Builder(Preheader->getTerminator());
824   SCEVExpander Expander(*SE, *DL, "loop-idiom");
825 
826   const SCEV *StrStart = StoreEv->getStart();
827   unsigned StrAS = SI->getPointerAddressSpace();
828   Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
829 
830   // Handle negative strided loops.
831   if (NegStride)
832     StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
833 
834   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
835   // this into a memcpy in the loop preheader now if we want.  However, this
836   // would be unsafe to do if there is anything else in the loop that may read
837   // or write the memory region we're storing to.  This includes the load that
838   // feeds the stores.  Check for an alias by generating the base address and
839   // checking everything.
840   Value *StoreBasePtr = Expander.expandCodeFor(
841       StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
842 
843   SmallPtrSet<Instruction *, 1> Stores;
844   Stores.insert(SI);
845   if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
846                             StoreSize, *AA, Stores)) {
847     Expander.clear();
848     // If we generated new code for the base pointer, clean up.
849     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
850     return false;
851   }
852 
853   const SCEV *LdStart = LoadEv->getStart();
854   unsigned LdAS = LI->getPointerAddressSpace();
855 
856   // Handle negative strided loops.
857   if (NegStride)
858     LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
859 
860   // For a memcpy, we have to make sure that the input array is not being
861   // mutated by the loop.
862   Value *LoadBasePtr = Expander.expandCodeFor(
863       LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
864 
865   if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
866                             *AA, Stores)) {
867     Expander.clear();
868     // If we generated new code for the base pointer, clean up.
869     RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
870     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
871     return false;
872   }
873 
874   // Okay, everything is safe, we can transform this!
875 
876   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
877   // pointer size if it isn't already.
878   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
879 
880   const SCEV *NumBytesS =
881       SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
882   if (StoreSize != 1)
883     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
884                                SCEV::FlagNUW);
885 
886   Value *NumBytes =
887       Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
888 
889   CallInst *NewCall =
890       Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
891                            std::min(SI->getAlignment(), LI->getAlignment()));
892   NewCall->setDebugLoc(SI->getDebugLoc());
893 
894   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
895                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
896                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
897 
898   // Okay, the memcpy has been formed.  Zap the original store and anything that
899   // feeds into it.
900   deleteDeadInstruction(SI, TLI);
901   ++NumMemCpy;
902   return true;
903 }
904 
905 bool LoopIdiomRecognize::runOnNoncountableLoop() {
906   return recognizePopcount();
907 }
908 
909 /// Check if the given conditional branch is based on the comparison between
910 /// a variable and zero, and if the variable is non-zero, the control yields to
911 /// the loop entry. If the branch matches the behavior, the variable involved
912 /// in the comparion is returned. This function will be called to see if the
913 /// precondition and postcondition of the loop are in desirable form.
914 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
915   if (!BI || !BI->isConditional())
916     return nullptr;
917 
918   ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
919   if (!Cond)
920     return nullptr;
921 
922   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
923   if (!CmpZero || !CmpZero->isZero())
924     return nullptr;
925 
926   ICmpInst::Predicate Pred = Cond->getPredicate();
927   if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
928       (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
929     return Cond->getOperand(0);
930 
931   return nullptr;
932 }
933 
934 /// Return true iff the idiom is detected in the loop.
935 ///
936 /// Additionally:
937 /// 1) \p CntInst is set to the instruction counting the population bit.
938 /// 2) \p CntPhi is set to the corresponding phi node.
939 /// 3) \p Var is set to the value whose population bits are being counted.
940 ///
941 /// The core idiom we are trying to detect is:
942 /// \code
943 ///    if (x0 != 0)
944 ///      goto loop-exit // the precondition of the loop
945 ///    cnt0 = init-val;
946 ///    do {
947 ///       x1 = phi (x0, x2);
948 ///       cnt1 = phi(cnt0, cnt2);
949 ///
950 ///       cnt2 = cnt1 + 1;
951 ///        ...
952 ///       x2 = x1 & (x1 - 1);
953 ///        ...
954 ///    } while(x != 0);
955 ///
956 /// loop-exit:
957 /// \endcode
958 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
959                                 Instruction *&CntInst, PHINode *&CntPhi,
960                                 Value *&Var) {
961   // step 1: Check to see if the look-back branch match this pattern:
962   //    "if (a!=0) goto loop-entry".
963   BasicBlock *LoopEntry;
964   Instruction *DefX2, *CountInst;
965   Value *VarX1, *VarX0;
966   PHINode *PhiX, *CountPhi;
967 
968   DefX2 = CountInst = nullptr;
969   VarX1 = VarX0 = nullptr;
970   PhiX = CountPhi = nullptr;
971   LoopEntry = *(CurLoop->block_begin());
972 
973   // step 1: Check if the loop-back branch is in desirable form.
974   {
975     if (Value *T = matchCondition(
976             dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
977       DefX2 = dyn_cast<Instruction>(T);
978     else
979       return false;
980   }
981 
982   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
983   {
984     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
985       return false;
986 
987     BinaryOperator *SubOneOp;
988 
989     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
990       VarX1 = DefX2->getOperand(1);
991     else {
992       VarX1 = DefX2->getOperand(0);
993       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
994     }
995     if (!SubOneOp)
996       return false;
997 
998     Instruction *SubInst = cast<Instruction>(SubOneOp);
999     ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
1000     if (!Dec ||
1001         !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1002           (SubInst->getOpcode() == Instruction::Add &&
1003            Dec->isAllOnesValue()))) {
1004       return false;
1005     }
1006   }
1007 
1008   // step 3: Check the recurrence of variable X
1009   {
1010     PhiX = dyn_cast<PHINode>(VarX1);
1011     if (!PhiX ||
1012         (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
1013       return false;
1014     }
1015   }
1016 
1017   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1018   {
1019     CountInst = nullptr;
1020     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1021                               IterE = LoopEntry->end();
1022          Iter != IterE; Iter++) {
1023       Instruction *Inst = &*Iter;
1024       if (Inst->getOpcode() != Instruction::Add)
1025         continue;
1026 
1027       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1028       if (!Inc || !Inc->isOne())
1029         continue;
1030 
1031       PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
1032       if (!Phi || Phi->getParent() != LoopEntry)
1033         continue;
1034 
1035       // Check if the result of the instruction is live of the loop.
1036       bool LiveOutLoop = false;
1037       for (User *U : Inst->users()) {
1038         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1039           LiveOutLoop = true;
1040           break;
1041         }
1042       }
1043 
1044       if (LiveOutLoop) {
1045         CountInst = Inst;
1046         CountPhi = Phi;
1047         break;
1048       }
1049     }
1050 
1051     if (!CountInst)
1052       return false;
1053   }
1054 
1055   // step 5: check if the precondition is in this form:
1056   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1057   {
1058     auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1059     Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1060     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1061       return false;
1062 
1063     CntInst = CountInst;
1064     CntPhi = CountPhi;
1065     Var = T;
1066   }
1067 
1068   return true;
1069 }
1070 
1071 /// Recognizes a population count idiom in a non-countable loop.
1072 ///
1073 /// If detected, transforms the relevant code to issue the popcount intrinsic
1074 /// function call, and returns true; otherwise, returns false.
1075 bool LoopIdiomRecognize::recognizePopcount() {
1076   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1077     return false;
1078 
1079   // Counting population are usually conducted by few arithmetic instructions.
1080   // Such instructions can be easily "absorbed" by vacant slots in a
1081   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1082   // in a compact loop.
1083 
1084   // Give up if the loop has multiple blocks or multiple backedges.
1085   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1086     return false;
1087 
1088   BasicBlock *LoopBody = *(CurLoop->block_begin());
1089   if (LoopBody->size() >= 20) {
1090     // The loop is too big, bail out.
1091     return false;
1092   }
1093 
1094   // It should have a preheader containing nothing but an unconditional branch.
1095   BasicBlock *PH = CurLoop->getLoopPreheader();
1096   if (!PH)
1097     return false;
1098   if (&PH->front() != PH->getTerminator())
1099     return false;
1100   auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
1101   if (!EntryBI || EntryBI->isConditional())
1102     return false;
1103 
1104   // It should have a precondition block where the generated popcount instrinsic
1105   // function can be inserted.
1106   auto *PreCondBB = PH->getSinglePredecessor();
1107   if (!PreCondBB)
1108     return false;
1109   auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1110   if (!PreCondBI || PreCondBI->isUnconditional())
1111     return false;
1112 
1113   Instruction *CntInst;
1114   PHINode *CntPhi;
1115   Value *Val;
1116   if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1117     return false;
1118 
1119   transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1120   return true;
1121 }
1122 
1123 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1124                                        DebugLoc DL) {
1125   Value *Ops[] = {Val};
1126   Type *Tys[] = {Val->getType()};
1127 
1128   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1129   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1130   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1131   CI->setDebugLoc(DL);
1132 
1133   return CI;
1134 }
1135 
1136 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1137                                                  Instruction *CntInst,
1138                                                  PHINode *CntPhi, Value *Var) {
1139   BasicBlock *PreHead = CurLoop->getLoopPreheader();
1140   auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1141   const DebugLoc DL = CntInst->getDebugLoc();
1142 
1143   // Assuming before transformation, the loop is following:
1144   //  if (x) // the precondition
1145   //     do { cnt++; x &= x - 1; } while(x);
1146 
1147   // Step 1: Insert the ctpop instruction at the end of the precondition block
1148   IRBuilder<> Builder(PreCondBr);
1149   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1150   {
1151     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1152     NewCount = PopCntZext =
1153         Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1154 
1155     if (NewCount != PopCnt)
1156       (cast<Instruction>(NewCount))->setDebugLoc(DL);
1157 
1158     // TripCnt is exactly the number of iterations the loop has
1159     TripCnt = NewCount;
1160 
1161     // If the population counter's initial value is not zero, insert Add Inst.
1162     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1163     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1164     if (!InitConst || !InitConst->isZero()) {
1165       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1166       (cast<Instruction>(NewCount))->setDebugLoc(DL);
1167     }
1168   }
1169 
1170   // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
1171   //   "if (NewCount == 0) loop-exit". Without this change, the intrinsic
1172   //   function would be partial dead code, and downstream passes will drag
1173   //   it back from the precondition block to the preheader.
1174   {
1175     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1176 
1177     Value *Opnd0 = PopCntZext;
1178     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1179     if (PreCond->getOperand(0) != Var)
1180       std::swap(Opnd0, Opnd1);
1181 
1182     ICmpInst *NewPreCond = cast<ICmpInst>(
1183         Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1184     PreCondBr->setCondition(NewPreCond);
1185 
1186     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1187   }
1188 
1189   // Step 3: Note that the population count is exactly the trip count of the
1190   // loop in question, which enable us to to convert the loop from noncountable
1191   // loop into a countable one. The benefit is twofold:
1192   //
1193   //  - If the loop only counts population, the entire loop becomes dead after
1194   //    the transformation. It is a lot easier to prove a countable loop dead
1195   //    than to prove a noncountable one. (In some C dialects, an infinite loop
1196   //    isn't dead even if it computes nothing useful. In general, DCE needs
1197   //    to prove a noncountable loop finite before safely delete it.)
1198   //
1199   //  - If the loop also performs something else, it remains alive.
1200   //    Since it is transformed to countable form, it can be aggressively
1201   //    optimized by some optimizations which are in general not applicable
1202   //    to a noncountable loop.
1203   //
1204   // After this step, this loop (conceptually) would look like following:
1205   //   newcnt = __builtin_ctpop(x);
1206   //   t = newcnt;
1207   //   if (x)
1208   //     do { cnt++; x &= x-1; t--) } while (t > 0);
1209   BasicBlock *Body = *(CurLoop->block_begin());
1210   {
1211     auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1212     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1213     Type *Ty = TripCnt->getType();
1214 
1215     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1216 
1217     Builder.SetInsertPoint(LbCond);
1218     Instruction *TcDec = cast<Instruction>(
1219         Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1220                           "tcdec", false, true));
1221 
1222     TcPhi->addIncoming(TripCnt, PreHead);
1223     TcPhi->addIncoming(TcDec, Body);
1224 
1225     CmpInst::Predicate Pred =
1226         (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1227     LbCond->setPredicate(Pred);
1228     LbCond->setOperand(0, TcDec);
1229     LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1230   }
1231 
1232   // Step 4: All the references to the original population counter outside
1233   //  the loop are replaced with the NewCount -- the value returned from
1234   //  __builtin_ctpop().
1235   CntInst->replaceUsesOutsideBlock(NewCount, Body);
1236 
1237   // step 5: Forget the "non-computable" trip-count SCEV associated with the
1238   //   loop. The loop would otherwise not be deleted even if it becomes empty.
1239   SE->forgetLoop(CurLoop);
1240 }
1241