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