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