b7247cc2ca46cf451515c54e8414d6edb9d10e27
[oota-llvm.git] / lib / Transforms / Scalar / LoopIdiomRecognize.cpp
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 // We should enhance the memset/memcpy recognition to handle multiple stores in
30 // the loop.  This would handle things like:
31 //   void foo(_Complex float *P)
32 //     for (i) { __real__(*P) = 0;  __imag__(*P) = 0; }
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.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/BasicAliasAnalysis.h"
43 #include "llvm/Analysis/GlobalsModRef.h"
44 #include "llvm/Analysis/LoopPass.h"
45 #include "llvm/Analysis/ScalarEvolutionExpander.h"
46 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
47 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/Analysis/TargetTransformInfo.h"
50 #include "llvm/Analysis/ValueTracking.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Dominators.h"
53 #include "llvm/IR/IRBuilder.h"
54 #include "llvm/IR/IntrinsicInst.h"
55 #include "llvm/IR/Module.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Utils/Local.h"
59 using namespace llvm;
60
61 #define DEBUG_TYPE "loop-idiom"
62
63 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
64 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
65
66 namespace {
67
68 class LoopIdiomRecognize : public LoopPass {
69   Loop *CurLoop;
70   AliasAnalysis *AA;
71   DominatorTree *DT;
72   LoopInfo *LI;
73   ScalarEvolution *SE;
74   TargetLibraryInfo *TLI;
75   const TargetTransformInfo *TTI;
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<LoopInfoWrapperPass>();
90     AU.addPreserved<LoopInfoWrapperPass>();
91     AU.addRequiredID(LoopSimplifyID);
92     AU.addPreservedID(LoopSimplifyID);
93     AU.addRequiredID(LCSSAID);
94     AU.addPreservedID(LCSSAID);
95     AU.addRequired<AAResultsWrapperPass>();
96     AU.addPreserved<AAResultsWrapperPass>();
97     AU.addRequired<ScalarEvolutionWrapperPass>();
98     AU.addPreserved<ScalarEvolutionWrapperPass>();
99     AU.addPreserved<SCEVAAWrapperPass>();
100     AU.addRequired<DominatorTreeWrapperPass>();
101     AU.addPreserved<DominatorTreeWrapperPass>();
102     AU.addRequired<TargetLibraryInfoWrapperPass>();
103     AU.addRequired<TargetTransformInfoWrapperPass>();
104     AU.addPreserved<BasicAAWrapperPass>();
105     AU.addPreserved<GlobalsAAWrapperPass>();
106   }
107
108 private:
109   /// \name Countable Loop Idiom Handling
110   /// @{
111
112   bool runOnCountableLoop();
113   bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
114                       SmallVectorImpl<BasicBlock *> &ExitBlocks);
115
116   bool processLoopStore(StoreInst *SI, const SCEV *BECount);
117   bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
118
119   bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
120                                unsigned StoreAlignment, Value *SplatValue,
121                                Instruction *TheStore, const SCEVAddRecExpr *Ev,
122                                const SCEV *BECount, bool NegStride);
123   bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
124                                   const SCEVAddRecExpr *StoreEv,
125                                   const SCEVAddRecExpr *LoadEv,
126                                   const SCEV *BECount);
127
128   /// @}
129   /// \name Noncountable Loop Idiom Handling
130   /// @{
131
132   bool runOnNoncountableLoop();
133
134   bool recognizePopcount();
135   void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
136                                PHINode *CntPhi, Value *Var);
137
138   /// @}
139 };
140
141 } // End anonymous namespace.
142
143 char LoopIdiomRecognize::ID = 0;
144 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
145                       false, false)
146 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
147 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
148 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
149 INITIALIZE_PASS_DEPENDENCY(LCSSA)
150 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
151 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
152 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
153 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
154 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
155 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
156 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
157 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
158                     false, false)
159
160 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
161
162 /// deleteDeadInstruction - Delete this instruction.  Before we do, go through
163 /// and zero out all the operands of this instruction.  If any of them become
164 /// dead, delete them and the computation tree that feeds them.
165 ///
166 static void deleteDeadInstruction(Instruction *I,
167                                   const TargetLibraryInfo *TLI) {
168   SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
169   I->replaceAllUsesWith(UndefValue::get(I->getType()));
170   I->eraseFromParent();
171   for (Value *Op : Operands)
172     RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
173 }
174
175 //===----------------------------------------------------------------------===//
176 //
177 //          Implementation of LoopIdiomRecognize
178 //
179 //===----------------------------------------------------------------------===//
180
181 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
182   if (skipOptnoneFunction(L))
183     return false;
184
185   CurLoop = L;
186   // If the loop could not be converted to canonical form, it must have an
187   // indirectbr in it, just give up.
188   if (!L->getLoopPreheader())
189     return false;
190
191   // Disable loop idiom recognition if the function's name is a common idiom.
192   StringRef Name = L->getHeader()->getParent()->getName();
193   if (Name == "memset" || Name == "memcpy")
194     return false;
195
196   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
197   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
198   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
199   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
200   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
201   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
202       *CurLoop->getHeader()->getParent());
203
204   if (SE->hasLoopInvariantBackedgeTakenCount(L))
205     return runOnCountableLoop();
206
207   return runOnNoncountableLoop();
208 }
209
210 bool LoopIdiomRecognize::runOnCountableLoop() {
211   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
212   assert(!isa<SCEVCouldNotCompute>(BECount) &&
213          "runOnCountableLoop() called on a loop without a predictable"
214          "backedge-taken count");
215
216   // If this loop executes exactly one time, then it should be peeled, not
217   // optimized by this pass.
218   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
219     if (BECst->getValue()->getValue() == 0)
220       return false;
221
222   SmallVector<BasicBlock *, 8> ExitBlocks;
223   CurLoop->getUniqueExitBlocks(ExitBlocks);
224
225   DEBUG(dbgs() << "loop-idiom Scanning: F["
226                << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
227                << CurLoop->getHeader()->getName() << "\n");
228
229   bool MadeChange = false;
230   // Scan all the blocks in the loop that are not in subloops.
231   for (auto *BB : CurLoop->getBlocks()) {
232     // Ignore blocks in subloops.
233     if (LI->getLoopFor(BB) != CurLoop)
234       continue;
235
236     MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
237   }
238   return MadeChange;
239 }
240
241 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
242 /// with the specified backedge count.  This block is known to be in the current
243 /// loop and not in any subloops.
244 bool LoopIdiomRecognize::runOnLoopBlock(
245     BasicBlock *BB, const SCEV *BECount,
246     SmallVectorImpl<BasicBlock *> &ExitBlocks) {
247   // We can only promote stores in this block if they are unconditionally
248   // executed in the loop.  For a block to be unconditionally executed, it has
249   // to dominate all the exit blocks of the loop.  Verify this now.
250   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
251     if (!DT->dominates(BB, ExitBlocks[i]))
252       return false;
253
254   bool MadeChange = false;
255   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
256     Instruction *Inst = &*I++;
257     // Look for store instructions, which may be optimized to memset/memcpy.
258     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
259       WeakVH InstPtr(&*I);
260       if (!processLoopStore(SI, BECount))
261         continue;
262       MadeChange = true;
263
264       // If processing the store invalidated our iterator, start over from the
265       // top of the block.
266       if (!InstPtr)
267         I = BB->begin();
268       continue;
269     }
270
271     // Look for memset instructions, which may be optimized to a larger memset.
272     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
273       WeakVH InstPtr(&*I);
274       if (!processLoopMemSet(MSI, BECount))
275         continue;
276       MadeChange = true;
277
278       // If processing the memset invalidated our iterator, start over from the
279       // top of the block.
280       if (!InstPtr)
281         I = BB->begin();
282       continue;
283     }
284   }
285
286   return MadeChange;
287 }
288
289 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
290 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
291   if (!SI->isSimple())
292     return false;
293
294   Value *StoredVal = SI->getValueOperand();
295   Value *StorePtr = SI->getPointerOperand();
296
297   // Reject stores that are so large that they overflow an unsigned.
298   auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
299   uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
300   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
301     return false;
302
303   // See if the pointer expression is an AddRec like {base,+,1} on the current
304   // loop, which indicates a strided store.  If we have something else, it's a
305   // random store we can't handle.
306   const SCEVAddRecExpr *StoreEv =
307       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
308   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
309     return false;
310
311   // Check to see if the stride matches the size of the store.  If so, then we
312   // know that every byte is touched in the loop.
313   unsigned StoreSize = (unsigned)SizeInBits >> 3;
314
315   const SCEVConstant *ConstStride =
316       dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
317   if (!ConstStride)
318     return false;
319
320   APInt Stride = ConstStride->getValue()->getValue();
321   if (StoreSize != Stride && StoreSize != -Stride)
322     return false;
323
324   bool NegStride = StoreSize == -Stride;
325
326   // See if we can optimize just this store in isolation.
327   if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
328                               StoredVal, SI, StoreEv, BECount, NegStride))
329     return true;
330
331   // TODO: We don't handle negative stride memcpys.
332   if (NegStride)
333     return false;
334
335   // If the stored value is a strided load in the same loop with the same stride
336   // this may be transformable into a memcpy.  This kicks in for stuff like
337   //   for (i) A[i] = B[i];
338   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
339     const SCEVAddRecExpr *LoadEv =
340         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
341     if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
342         StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
343       if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
344         return true;
345   }
346   // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
347
348   return false;
349 }
350
351 /// processLoopMemSet - See if this memset can be promoted to a large memset.
352 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
353                                            const SCEV *BECount) {
354   // We can only handle non-volatile memsets with a constant size.
355   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
356     return false;
357
358   // If we're not allowed to hack on memset, we fail.
359   if (!TLI->has(LibFunc::memset))
360     return false;
361
362   Value *Pointer = MSI->getDest();
363
364   // See if the pointer expression is an AddRec like {base,+,1} on the current
365   // loop, which indicates a strided store.  If we have something else, it's a
366   // random store we can't handle.
367   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
368   if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
369     return false;
370
371   // Reject memsets that are so large that they overflow an unsigned.
372   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
373   if ((SizeInBytes >> 32) != 0)
374     return false;
375
376   // Check to see if the stride matches the size of the memset.  If so, then we
377   // know that every byte is touched in the loop.
378   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
379
380   // TODO: Could also handle negative stride here someday, that will require the
381   // validity check in mayLoopAccessLocation to be updated though.
382   if (!Stride || MSI->getLength() != Stride->getValue())
383     return false;
384
385   return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
386                                  MSI->getAlignment(), MSI->getValue(), MSI, Ev,
387                                  BECount, /*NegStride=*/false);
388 }
389
390 /// mayLoopAccessLocation - Return true if the specified loop might access the
391 /// specified pointer location, which is a loop-strided access.  The 'Access'
392 /// argument specifies what the verboten forms of access are (read or write).
393 static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
394                                   const SCEV *BECount, unsigned StoreSize,
395                                   AliasAnalysis &AA,
396                                   Instruction *IgnoredStore) {
397   // Get the location that may be stored across the loop.  Since the access is
398   // strided positively through memory, we say that the modified location starts
399   // at the pointer and has infinite size.
400   uint64_t AccessSize = MemoryLocation::UnknownSize;
401
402   // If the loop iterates a fixed number of times, we can refine the access size
403   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
404   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
405     AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
406
407   // TODO: For this to be really effective, we have to dive into the pointer
408   // operand in the store.  Store to &A[i] of 100 will always return may alias
409   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
410   // which will then no-alias a store to &A[100].
411   MemoryLocation StoreLoc(Ptr, AccessSize);
412
413   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
414        ++BI)
415     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
416       if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access))
417         return true;
418
419   return false;
420 }
421
422 /// getMemSetPatternValue - If a strided store of the specified value is safe to
423 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
424 /// be passed in.  Otherwise, return null.
425 ///
426 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
427 /// just replicate their input array and then pass on to memset_pattern16.
428 static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
429   // If the value isn't a constant, we can't promote it to being in a constant
430   // array.  We could theoretically do a store to an alloca or something, but
431   // that doesn't seem worthwhile.
432   Constant *C = dyn_cast<Constant>(V);
433   if (!C)
434     return nullptr;
435
436   // Only handle simple values that are a power of two bytes in size.
437   uint64_t Size = DL.getTypeSizeInBits(V->getType());
438   if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
439     return nullptr;
440
441   // Don't care enough about darwin/ppc to implement this.
442   if (DL.isBigEndian())
443     return nullptr;
444
445   // Convert to size in bytes.
446   Size /= 8;
447
448   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
449   // if the top and bottom are the same (e.g. for vectors and large integers).
450   if (Size > 16)
451     return nullptr;
452
453   // If the constant is exactly 16 bytes, just use it.
454   if (Size == 16)
455     return C;
456
457   // Otherwise, we'll use an array of the constants.
458   unsigned ArraySize = 16 / Size;
459   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
460   return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
461 }
462
463 /// processLoopStridedStore - We see a strided store of some value.  If we can
464 /// transform this into a memset or memset_pattern in the loop preheader, do so.
465 bool LoopIdiomRecognize::processLoopStridedStore(
466     Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
467     Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
468     const SCEV *BECount, bool NegStride) {
469
470   // If the stored value is a byte-wise value (like i32 -1), then it may be
471   // turned into a memset of i8 -1, assuming that all the consecutive bytes
472   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
473   // but it can be turned into memset_pattern if the target supports it.
474   Value *SplatValue = isBytewiseValue(StoredVal);
475   Constant *PatternValue = nullptr;
476   auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
477   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
478
479   // If we're allowed to form a memset, and the stored value would be acceptable
480   // for memset, use it.
481   if (SplatValue && TLI->has(LibFunc::memset) &&
482       // Verify that the stored value is loop invariant.  If not, we can't
483       // promote the memset.
484       CurLoop->isLoopInvariant(SplatValue)) {
485     // Keep and use SplatValue.
486     PatternValue = nullptr;
487   } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
488              (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
489     // Don't create memset_pattern16s with address spaces.
490     // It looks like we can use PatternValue!
491     SplatValue = nullptr;
492   } else {
493     // Otherwise, this isn't an idiom we can transform.  For example, we can't
494     // do anything with a 3-byte store.
495     return false;
496   }
497
498   // The trip count of the loop and the base pointer of the addrec SCEV is
499   // guaranteed to be loop invariant, which means that it should dominate the
500   // header.  This allows us to insert code for it in the preheader.
501   BasicBlock *Preheader = CurLoop->getLoopPreheader();
502   IRBuilder<> Builder(Preheader->getTerminator());
503   SCEVExpander Expander(*SE, DL, "loop-idiom");
504
505   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
506   Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
507
508   const SCEV *Start = Ev->getStart();
509   // If we have a negative stride, Start refers to the end of the memory
510   // location we're trying to memset.  Therefore, we need to recompute the start
511   // point, which is just Start - BECount*Size.
512   if (NegStride) {
513     const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
514     if (StoreSize != 1)
515       Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
516                              SCEV::FlagNUW);
517     Start = SE->getMinusSCEV(Ev->getStart(), Index);
518   }
519
520   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
521   // this into a memset in the loop preheader now if we want.  However, this
522   // would be unsafe to do if there is anything else in the loop that may read
523   // or write to the aliased location.  Check for any overlap by generating the
524   // base pointer and checking the region.
525   Value *BasePtr =
526       Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
527   if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
528                             *AA, TheStore)) {
529     Expander.clear();
530     // If we generated new code for the base pointer, clean up.
531     RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
532     return false;
533   }
534
535   // Okay, everything looks good, insert the memset.
536
537   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
538   // pointer size if it isn't already.
539   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
540
541   const SCEV *NumBytesS =
542       SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
543   if (StoreSize != 1) {
544     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
545                                SCEV::FlagNUW);
546   }
547
548   Value *NumBytes =
549       Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
550
551   CallInst *NewCall;
552   if (SplatValue) {
553     NewCall =
554         Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
555   } else {
556     // Everything is emitted in default address space
557     Type *Int8PtrTy = DestInt8PtrTy;
558
559     Module *M = TheStore->getParent()->getParent()->getParent();
560     Value *MSP =
561         M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
562                                Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
563
564     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
565     // an constant array of 16-bytes.  Plop the value into a mergable global.
566     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
567                                             GlobalValue::PrivateLinkage,
568                                             PatternValue, ".memset_pattern");
569     GV->setUnnamedAddr(true); // Ok to merge these.
570     GV->setAlignment(16);
571     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
572     NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
573   }
574
575   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
576                << "    from store to: " << *Ev << " at: " << *TheStore << "\n");
577   NewCall->setDebugLoc(TheStore->getDebugLoc());
578
579   // Okay, the memset has been formed.  Zap the original store and anything that
580   // feeds into it.
581   deleteDeadInstruction(TheStore, TLI);
582   ++NumMemSet;
583   return true;
584 }
585
586 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
587 /// same-strided load.
588 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
589     StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
590     const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
591   // If we're not allowed to form memcpy, we fail.
592   if (!TLI->has(LibFunc::memcpy))
593     return false;
594
595   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
596
597   // The trip count of the loop and the base pointer of the addrec SCEV is
598   // guaranteed to be loop invariant, which means that it should dominate the
599   // header.  This allows us to insert code for it in the preheader.
600   BasicBlock *Preheader = CurLoop->getLoopPreheader();
601   IRBuilder<> Builder(Preheader->getTerminator());
602   const DataLayout &DL = Preheader->getModule()->getDataLayout();
603   SCEVExpander Expander(*SE, DL, "loop-idiom");
604
605   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
606   // this into a memcpy in the loop preheader now if we want.  However, this
607   // would be unsafe to do if there is anything else in the loop that may read
608   // or write the memory region we're storing to.  This includes the load that
609   // feeds the stores.  Check for an alias by generating the base address and
610   // checking everything.
611   Value *StoreBasePtr = Expander.expandCodeFor(
612       StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
613       Preheader->getTerminator());
614
615   if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
616                             StoreSize, *AA, SI)) {
617     Expander.clear();
618     // If we generated new code for the base pointer, clean up.
619     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
620     return false;
621   }
622
623   // For a memcpy, we have to make sure that the input array is not being
624   // mutated by the loop.
625   Value *LoadBasePtr = Expander.expandCodeFor(
626       LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
627       Preheader->getTerminator());
628
629   if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
630                             *AA, SI)) {
631     Expander.clear();
632     // If we generated new code for the base pointer, clean up.
633     RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
634     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
635     return false;
636   }
637
638   // Okay, everything is safe, we can transform this!
639
640   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
641   // pointer size if it isn't already.
642   Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
643   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
644
645   const SCEV *NumBytesS =
646       SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
647   if (StoreSize != 1)
648     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
649                                SCEV::FlagNUW);
650
651   Value *NumBytes =
652       Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
653
654   CallInst *NewCall =
655       Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
656                            std::min(SI->getAlignment(), LI->getAlignment()));
657   NewCall->setDebugLoc(SI->getDebugLoc());
658
659   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
660                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
661                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
662
663   // Okay, the memcpy has been formed.  Zap the original store and anything that
664   // feeds into it.
665   deleteDeadInstruction(SI, TLI);
666   ++NumMemCpy;
667   return true;
668 }
669
670 bool LoopIdiomRecognize::runOnNoncountableLoop() {
671   if (recognizePopcount())
672     return true;
673
674   return false;
675 }
676
677 /// Check if the given conditional branch is based on the comparison between
678 /// a variable and zero, and if the variable is non-zero, the control yields to
679 /// the loop entry. If the branch matches the behavior, the variable involved
680 /// in the comparion is returned. This function will be called to see if the
681 /// precondition and postcondition of the loop are in desirable form.
682 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
683   if (!BI || !BI->isConditional())
684     return nullptr;
685
686   ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
687   if (!Cond)
688     return nullptr;
689
690   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
691   if (!CmpZero || !CmpZero->isZero())
692     return nullptr;
693
694   ICmpInst::Predicate Pred = Cond->getPredicate();
695   if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
696       (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
697     return Cond->getOperand(0);
698
699   return nullptr;
700 }
701
702 /// Return true iff the idiom is detected in the loop.
703 ///
704 /// Additionally:
705 /// 1) \p CntInst is set to the instruction counting the population bit.
706 /// 2) \p CntPhi is set to the corresponding phi node.
707 /// 3) \p Var is set to the value whose population bits are being counted.
708 ///
709 /// The core idiom we are trying to detect is:
710 /// \code
711 ///    if (x0 != 0)
712 ///      goto loop-exit // the precondition of the loop
713 ///    cnt0 = init-val;
714 ///    do {
715 ///       x1 = phi (x0, x2);
716 ///       cnt1 = phi(cnt0, cnt2);
717 ///
718 ///       cnt2 = cnt1 + 1;
719 ///        ...
720 ///       x2 = x1 & (x1 - 1);
721 ///        ...
722 ///    } while(x != 0);
723 ///
724 /// loop-exit:
725 /// \endcode
726 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
727                                 Instruction *&CntInst, PHINode *&CntPhi,
728                                 Value *&Var) {
729   // step 1: Check to see if the look-back branch match this pattern:
730   //    "if (a!=0) goto loop-entry".
731   BasicBlock *LoopEntry;
732   Instruction *DefX2, *CountInst;
733   Value *VarX1, *VarX0;
734   PHINode *PhiX, *CountPhi;
735
736   DefX2 = CountInst = nullptr;
737   VarX1 = VarX0 = nullptr;
738   PhiX = CountPhi = nullptr;
739   LoopEntry = *(CurLoop->block_begin());
740
741   // step 1: Check if the loop-back branch is in desirable form.
742   {
743     if (Value *T = matchCondition(
744             dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
745       DefX2 = dyn_cast<Instruction>(T);
746     else
747       return false;
748   }
749
750   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
751   {
752     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
753       return false;
754
755     BinaryOperator *SubOneOp;
756
757     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
758       VarX1 = DefX2->getOperand(1);
759     else {
760       VarX1 = DefX2->getOperand(0);
761       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
762     }
763     if (!SubOneOp)
764       return false;
765
766     Instruction *SubInst = cast<Instruction>(SubOneOp);
767     ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
768     if (!Dec ||
769         !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
770           (SubInst->getOpcode() == Instruction::Add &&
771            Dec->isAllOnesValue()))) {
772       return false;
773     }
774   }
775
776   // step 3: Check the recurrence of variable X
777   {
778     PhiX = dyn_cast<PHINode>(VarX1);
779     if (!PhiX ||
780         (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
781       return false;
782     }
783   }
784
785   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
786   {
787     CountInst = nullptr;
788     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
789                               IterE = LoopEntry->end();
790          Iter != IterE; Iter++) {
791       Instruction *Inst = &*Iter;
792       if (Inst->getOpcode() != Instruction::Add)
793         continue;
794
795       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
796       if (!Inc || !Inc->isOne())
797         continue;
798
799       PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
800       if (!Phi || Phi->getParent() != LoopEntry)
801         continue;
802
803       // Check if the result of the instruction is live of the loop.
804       bool LiveOutLoop = false;
805       for (User *U : Inst->users()) {
806         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
807           LiveOutLoop = true;
808           break;
809         }
810       }
811
812       if (LiveOutLoop) {
813         CountInst = Inst;
814         CountPhi = Phi;
815         break;
816       }
817     }
818
819     if (!CountInst)
820       return false;
821   }
822
823   // step 5: check if the precondition is in this form:
824   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
825   {
826     auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
827     Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
828     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
829       return false;
830
831     CntInst = CountInst;
832     CntPhi = CountPhi;
833     Var = T;
834   }
835
836   return true;
837 }
838
839 /// Recognizes a population count idiom in a non-countable loop.
840 ///
841 /// If detected, transforms the relevant code to issue the popcount intrinsic
842 /// function call, and returns true; otherwise, returns false.
843 bool LoopIdiomRecognize::recognizePopcount() {
844   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
845     return false;
846
847   // Counting population are usually conducted by few arithmetic instructions.
848   // Such instructions can be easily "absorbed" by vacant slots in a
849   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
850   // in a compact loop.
851
852   // Give up if the loop has multiple blocks or multiple backedges.
853   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
854     return false;
855
856   BasicBlock *LoopBody = *(CurLoop->block_begin());
857   if (LoopBody->size() >= 20) {
858     // The loop is too big, bail out.
859     return false;
860   }
861
862   // It should have a preheader containing nothing but an unconditional branch.
863   BasicBlock *PH = CurLoop->getLoopPreheader();
864   if (!PH)
865     return false;
866   if (&PH->front() != PH->getTerminator())
867     return false;
868   auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
869   if (!EntryBI || EntryBI->isConditional())
870     return false;
871
872   // It should have a precondition block where the generated popcount instrinsic
873   // function can be inserted.
874   auto *PreCondBB = PH->getSinglePredecessor();
875   if (!PreCondBB)
876     return false;
877   auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
878   if (!PreCondBI || PreCondBI->isUnconditional())
879     return false;
880
881   Instruction *CntInst;
882   PHINode *CntPhi;
883   Value *Val;
884   if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
885     return false;
886
887   transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
888   return true;
889 }
890
891 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
892                                        DebugLoc DL) {
893   Value *Ops[] = {Val};
894   Type *Tys[] = {Val->getType()};
895
896   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
897   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
898   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
899   CI->setDebugLoc(DL);
900
901   return CI;
902 }
903
904 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
905                                                  Instruction *CntInst,
906                                                  PHINode *CntPhi, Value *Var) {
907   BasicBlock *PreHead = CurLoop->getLoopPreheader();
908   auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
909   const DebugLoc DL = CntInst->getDebugLoc();
910
911   // Assuming before transformation, the loop is following:
912   //  if (x) // the precondition
913   //     do { cnt++; x &= x - 1; } while(x);
914
915   // Step 1: Insert the ctpop instruction at the end of the precondition block
916   IRBuilder<> Builder(PreCondBr);
917   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
918   {
919     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
920     NewCount = PopCntZext =
921         Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
922
923     if (NewCount != PopCnt)
924       (cast<Instruction>(NewCount))->setDebugLoc(DL);
925
926     // TripCnt is exactly the number of iterations the loop has
927     TripCnt = NewCount;
928
929     // If the population counter's initial value is not zero, insert Add Inst.
930     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
931     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
932     if (!InitConst || !InitConst->isZero()) {
933       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
934       (cast<Instruction>(NewCount))->setDebugLoc(DL);
935     }
936   }
937
938   // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
939   //   "if (NewCount == 0) loop-exit". Without this change, the intrinsic
940   //   function would be partial dead code, and downstream passes will drag
941   //   it back from the precondition block to the preheader.
942   {
943     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
944
945     Value *Opnd0 = PopCntZext;
946     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
947     if (PreCond->getOperand(0) != Var)
948       std::swap(Opnd0, Opnd1);
949
950     ICmpInst *NewPreCond = cast<ICmpInst>(
951         Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
952     PreCondBr->setCondition(NewPreCond);
953
954     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
955   }
956
957   // Step 3: Note that the population count is exactly the trip count of the
958   // loop in question, which enable us to to convert the loop from noncountable
959   // loop into a countable one. The benefit is twofold:
960   //
961   //  - If the loop only counts population, the entire loop becomes dead after
962   //    the transformation. It is a lot easier to prove a countable loop dead
963   //    than to prove a noncountable one. (In some C dialects, an infinite loop
964   //    isn't dead even if it computes nothing useful. In general, DCE needs
965   //    to prove a noncountable loop finite before safely delete it.)
966   //
967   //  - If the loop also performs something else, it remains alive.
968   //    Since it is transformed to countable form, it can be aggressively
969   //    optimized by some optimizations which are in general not applicable
970   //    to a noncountable loop.
971   //
972   // After this step, this loop (conceptually) would look like following:
973   //   newcnt = __builtin_ctpop(x);
974   //   t = newcnt;
975   //   if (x)
976   //     do { cnt++; x &= x-1; t--) } while (t > 0);
977   BasicBlock *Body = *(CurLoop->block_begin());
978   {
979     auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
980     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
981     Type *Ty = TripCnt->getType();
982
983     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
984
985     Builder.SetInsertPoint(LbCond);
986     Instruction *TcDec = cast<Instruction>(
987         Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
988                           "tcdec", false, true));
989
990     TcPhi->addIncoming(TripCnt, PreHead);
991     TcPhi->addIncoming(TcDec, Body);
992
993     CmpInst::Predicate Pred =
994         (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
995     LbCond->setPredicate(Pred);
996     LbCond->setOperand(0, TcDec);
997     LbCond->setOperand(1, ConstantInt::get(Ty, 0));
998   }
999
1000   // Step 4: All the references to the original population counter outside
1001   //  the loop are replaced with the NewCount -- the value returned from
1002   //  __builtin_ctpop().
1003   CntInst->replaceUsesOutsideBlock(NewCount, Body);
1004
1005   // step 5: Forget the "non-computable" trip-count SCEV associated with the
1006   //   loop. The loop would otherwise not be deleted even if it becomes empty.
1007   SE->forgetLoop(CurLoop);
1008 }