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