1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
18 // Future loop memory idioms to recognize:
19 // memcmp, memmove, strlen, etc.
20 // Future floating point idioms to recognize in -ffast-math mode:
22 // Future integer operation idioms to recognize:
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.
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; }
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.
39 // This could recognize common matrix multiplies and dot product idioms and
40 // replace them with calls to BLAS (if linked in??).
42 //===----------------------------------------------------------------------===//
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/TargetTransformInfo.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/IRBuilder.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Target/TargetLibraryInfo.h"
60 #include "llvm/Transforms/Utils/Local.h"
63 #define DEBUG_TYPE "loop-idiom"
65 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
66 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
70 class LoopIdiomRecognize;
72 /// This class defines some utility functions for loop idiom recognization.
75 /// Return true iff the block contains nothing but an uncondition branch
76 /// (aka goto instruction).
77 static bool isAlmostEmpty(BasicBlock *);
79 static BranchInst *getBranch(BasicBlock *BB) {
80 return dyn_cast<BranchInst>(BB->getTerminator());
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);
88 /// This class is to recoginize idioms of population-count conducted in
89 /// a noncountable loop. Currently it only recognizes this pattern:
91 /// while(x) {cnt++; ...; x &= x - 1; ...}
93 class NclPopcountRecognize {
94 LoopIdiomRecognize &LIR;
96 BasicBlock *PreCondBB;
98 typedef IRBuilder<> IRBuilderTy;
101 explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
105 /// Take a glimpse of the loop to see if we need to go ahead recoginizing
107 bool preliminaryScreen();
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;
117 /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
118 /// is set to the instruction counting the pupulation 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.
122 (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
124 /// Insert ctpop intrinsic function and some obviously dead instructions.
125 void transform (Instruction *CntInst, PHINode *CntPhi, Value *Var);
127 /// Create llvm.ctpop.* intrinsic function.
128 CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
131 class LoopIdiomRecognize : public LoopPass {
133 const DataLayout *DL;
136 TargetLibraryInfo *TLI;
137 const TargetTransformInfo *TTI;
140 explicit LoopIdiomRecognize() : LoopPass(ID) {
141 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
142 DL = nullptr; DT = nullptr; SE = nullptr; TLI = nullptr; TTI = nullptr;
145 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
146 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
147 SmallVectorImpl<BasicBlock*> &ExitBlocks);
149 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
150 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
152 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
153 unsigned StoreAlignment,
154 Value *SplatValue, Instruction *TheStore,
155 const SCEVAddRecExpr *Ev,
156 const SCEV *BECount);
157 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
158 const SCEVAddRecExpr *StoreEv,
159 const SCEVAddRecExpr *LoadEv,
160 const SCEV *BECount);
162 /// This transformation requires natural loop information & requires that
163 /// loop preheaders be inserted into the CFG.
165 void getAnalysisUsage(AnalysisUsage &AU) const override {
166 AU.addRequired<LoopInfo>();
167 AU.addPreserved<LoopInfo>();
168 AU.addRequiredID(LoopSimplifyID);
169 AU.addPreservedID(LoopSimplifyID);
170 AU.addRequiredID(LCSSAID);
171 AU.addPreservedID(LCSSAID);
172 AU.addRequired<AliasAnalysis>();
173 AU.addPreserved<AliasAnalysis>();
174 AU.addRequired<ScalarEvolution>();
175 AU.addPreserved<ScalarEvolution>();
176 AU.addPreserved<DominatorTreeWrapperPass>();
177 AU.addRequired<DominatorTreeWrapperPass>();
178 AU.addRequired<TargetLibraryInfo>();
179 AU.addRequired<TargetTransformInfo>();
182 const DataLayout *getDataLayout() {
185 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
186 DL = DLP ? &DLP->getDataLayout() : nullptr;
190 DominatorTree *getDominatorTree() {
192 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
195 ScalarEvolution *getScalarEvolution() {
196 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
199 TargetLibraryInfo *getTargetLibraryInfo() {
200 return TLI ? TLI : (TLI = &getAnalysis<TargetLibraryInfo>());
203 const TargetTransformInfo *getTargetTransformInfo() {
204 return TTI ? TTI : (TTI = &getAnalysis<TargetTransformInfo>());
207 Loop *getLoop() const { return CurLoop; }
210 bool runOnNoncountableLoop();
211 bool runOnCountableLoop();
215 char LoopIdiomRecognize::ID = 0;
216 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
218 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
219 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
220 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
221 INITIALIZE_PASS_DEPENDENCY(LCSSA)
222 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
223 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
224 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
225 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
226 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
229 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
231 /// deleteDeadInstruction - Delete this instruction. Before we do, go through
232 /// and zero out all the operands of this instruction. If any of them become
233 /// dead, delete them and the computation tree that feeds them.
235 static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE,
236 const TargetLibraryInfo *TLI) {
237 SmallVector<Instruction*, 32> NowDeadInsts;
239 NowDeadInsts.push_back(I);
241 // Before we touch this instruction, remove it from SE!
243 Instruction *DeadInst = NowDeadInsts.pop_back_val();
245 // This instruction is dead, zap it, in stages. Start by removing it from
247 SE.forgetValue(DeadInst);
249 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
250 Value *Op = DeadInst->getOperand(op);
251 DeadInst->setOperand(op, nullptr);
253 // If this operand just became dead, add it to the NowDeadInsts list.
254 if (!Op->use_empty()) continue;
256 if (Instruction *OpI = dyn_cast<Instruction>(Op))
257 if (isInstructionTriviallyDead(OpI, TLI))
258 NowDeadInsts.push_back(OpI);
261 DeadInst->eraseFromParent();
263 } while (!NowDeadInsts.empty());
266 /// deleteIfDeadInstruction - If the specified value is a dead instruction,
267 /// delete it and any recursively used instructions.
268 static void deleteIfDeadInstruction(Value *V, ScalarEvolution &SE,
269 const TargetLibraryInfo *TLI) {
270 if (Instruction *I = dyn_cast<Instruction>(V))
271 if (isInstructionTriviallyDead(I, TLI))
272 deleteDeadInstruction(I, SE, TLI);
275 //===----------------------------------------------------------------------===//
277 // Implementation of LIRUtil
279 //===----------------------------------------------------------------------===//
281 // This function will return true iff the given block contains nothing but goto.
282 // A typical usage of this function is to check if the preheader function is
283 // "almost" empty such that generated intrinsic functions can be moved across
284 // the preheader and be placed at the end of the precondition block without
285 // the concern of breaking data dependence.
286 bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
287 if (BranchInst *Br = getBranch(BB)) {
288 return Br->isUnconditional() && BB->size() == 1;
293 BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
294 if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
295 BranchInst *Br = getBranch(BB);
296 return Br && Br->isConditional() ? BB : nullptr;
301 //===----------------------------------------------------------------------===//
303 // Implementation of NclPopcountRecognize
305 //===----------------------------------------------------------------------===//
307 NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
308 LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {
311 bool NclPopcountRecognize::preliminaryScreen() {
312 const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
313 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
316 // Counting population are usually conducted by few arithmetic instructions.
317 // Such instructions can be easilly "absorbed" by vacant slots in a
318 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
319 // in a compact loop.
321 // Give up if the loop has multiple blocks or multiple backedges.
322 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
325 BasicBlock *LoopBody = *(CurLoop->block_begin());
326 if (LoopBody->size() >= 20) {
327 // The loop is too big, bail out.
331 // It should have a preheader containing nothing but a goto instruction.
332 BasicBlock *PreHead = CurLoop->getLoopPreheader();
333 if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
336 // It should have a precondition block where the generated popcount instrinsic
337 // function will be inserted.
338 PreCondBB = LIRUtil::getPrecondBb(PreHead);
345 Value *NclPopcountRecognize::matchCondition (BranchInst *Br,
346 BasicBlock *LoopEntry) const {
347 if (!Br || !Br->isConditional())
350 ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
354 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
355 if (!CmpZero || !CmpZero->isZero())
358 ICmpInst::Predicate Pred = Cond->getPredicate();
359 if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
360 (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
361 return Cond->getOperand(0);
366 bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
369 // Following code tries to detect this idiom:
372 // goto loop-exit // the precondition of the loop
375 // x1 = phi (x0, x2);
376 // cnt1 = phi(cnt0, cnt2);
380 // x2 = x1 & (x1 - 1);
387 // step 1: Check to see if the look-back branch match this pattern:
388 // "if (a!=0) goto loop-entry".
389 BasicBlock *LoopEntry;
390 Instruction *DefX2, *CountInst;
391 Value *VarX1, *VarX0;
392 PHINode *PhiX, *CountPhi;
394 DefX2 = CountInst = nullptr;
395 VarX1 = VarX0 = nullptr;
396 PhiX = CountPhi = nullptr;
397 LoopEntry = *(CurLoop->block_begin());
399 // step 1: Check if the loop-back branch is in desirable form.
401 if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
402 DefX2 = dyn_cast<Instruction>(T);
407 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
409 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
412 BinaryOperator *SubOneOp;
414 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
415 VarX1 = DefX2->getOperand(1);
417 VarX1 = DefX2->getOperand(0);
418 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
423 Instruction *SubInst = cast<Instruction>(SubOneOp);
424 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
426 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
427 (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
432 // step 3: Check the recurrence of variable X
434 PhiX = dyn_cast<PHINode>(VarX1);
436 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
441 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
444 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
445 IterE = LoopEntry->end(); Iter != IterE; Iter++) {
446 Instruction *Inst = Iter;
447 if (Inst->getOpcode() != Instruction::Add)
450 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
451 if (!Inc || !Inc->isOne())
454 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
455 if (!Phi || Phi->getParent() != LoopEntry)
458 // Check if the result of the instruction is live of the loop.
459 bool LiveOutLoop = false;
460 for (User *U : Inst->users()) {
461 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
462 LiveOutLoop = true; break;
477 // step 5: check if the precondition is in this form:
478 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
480 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
481 Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
482 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
493 void NclPopcountRecognize::transform(Instruction *CntInst,
494 PHINode *CntPhi, Value *Var) {
496 ScalarEvolution *SE = LIR.getScalarEvolution();
497 TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
498 BasicBlock *PreHead = CurLoop->getLoopPreheader();
499 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
500 const DebugLoc DL = CntInst->getDebugLoc();
502 // Assuming before transformation, the loop is following:
503 // if (x) // the precondition
504 // do { cnt++; x &= x - 1; } while(x);
506 // Step 1: Insert the ctpop instruction at the end of the precondition block
507 IRBuilderTy Builder(PreCondBr);
508 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
510 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
511 NewCount = PopCntZext =
512 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
514 if (NewCount != PopCnt)
515 (cast<Instruction>(NewCount))->setDebugLoc(DL);
517 // TripCnt is exactly the number of iterations the loop has
520 // If the population counter's initial value is not zero, insert Add Inst.
521 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
522 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
523 if (!InitConst || !InitConst->isZero()) {
524 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
525 (cast<Instruction>(NewCount))->setDebugLoc(DL);
529 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
530 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
531 // function would be partial dead code, and downstream passes will drag
532 // it back from the precondition block to the preheader.
534 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
536 Value *Opnd0 = PopCntZext;
537 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
538 if (PreCond->getOperand(0) != Var)
539 std::swap(Opnd0, Opnd1);
541 ICmpInst *NewPreCond =
542 cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
543 PreCond->replaceAllUsesWith(NewPreCond);
545 deleteDeadInstruction(PreCond, *SE, TLI);
548 // Step 3: Note that the population count is exactly the trip count of the
549 // loop in question, which enble us to to convert the loop from noncountable
550 // loop into a countable one. The benefit is twofold:
552 // - If the loop only counts population, the entire loop become dead after
553 // the transformation. It is lots easier to prove a countable loop dead
554 // than to prove a noncountable one. (In some C dialects, a infite loop
555 // isn't dead even if it computes nothing useful. In general, DCE needs
556 // to prove a noncountable loop finite before safely delete it.)
558 // - If the loop also performs something else, it remains alive.
559 // Since it is transformed to countable form, it can be aggressively
560 // optimized by some optimizations which are in general not applicable
561 // to a noncountable loop.
563 // After this step, this loop (conceptually) would look like following:
564 // newcnt = __builtin_ctpop(x);
567 // do { cnt++; x &= x-1; t--) } while (t > 0);
568 BasicBlock *Body = *(CurLoop->block_begin());
570 BranchInst *LbBr = LIRUtil::getBranch(Body);
571 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
572 Type *Ty = TripCnt->getType();
574 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
576 Builder.SetInsertPoint(LbCond);
577 Value *Opnd1 = cast<Value>(TcPhi);
578 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
580 cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
582 TcPhi->addIncoming(TripCnt, PreHead);
583 TcPhi->addIncoming(TcDec, Body);
585 CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
586 CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
587 LbCond->setPredicate(Pred);
588 LbCond->setOperand(0, TcDec);
589 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
592 // Step 4: All the references to the original population counter outside
593 // the loop are replaced with the NewCount -- the value returned from
594 // __builtin_ctpop().
596 SmallVector<Value *, 4> CntUses;
597 for (User *U : CntInst->users())
598 if (cast<Instruction>(U)->getParent() != Body)
599 CntUses.push_back(U);
600 for (unsigned Idx = 0; Idx < CntUses.size(); Idx++) {
601 (cast<Instruction>(CntUses[Idx]))->replaceUsesOfWith(CntInst, NewCount);
605 // step 5: Forget the "non-computable" trip-count SCEV associated with the
606 // loop. The loop would otherwise not be deleted even if it becomes empty.
607 SE->forgetLoop(CurLoop);
610 CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
611 Value *Val, DebugLoc DL) {
612 Value *Ops[] = { Val };
613 Type *Tys[] = { Val->getType() };
615 Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
616 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
617 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
623 /// recognize - detect population count idiom in a non-countable loop. If
624 /// detected, transform the relevant code to popcount intrinsic function
625 /// call, and return true; otherwise, return false.
626 bool NclPopcountRecognize::recognize() {
628 if (!LIR.getTargetTransformInfo())
631 LIR.getScalarEvolution();
633 if (!preliminaryScreen())
636 Instruction *CntInst;
639 if (!detectIdiom(CntInst, CntPhi, Val))
642 transform(CntInst, CntPhi, Val);
646 //===----------------------------------------------------------------------===//
648 // Implementation of LoopIdiomRecognize
650 //===----------------------------------------------------------------------===//
652 bool LoopIdiomRecognize::runOnCountableLoop() {
653 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
654 if (isa<SCEVCouldNotCompute>(BECount)) return false;
656 // If this loop executes exactly one time, then it should be peeled, not
657 // optimized by this pass.
658 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
659 if (BECst->getValue()->getValue() == 0)
662 // We require target data for now.
663 if (!getDataLayout())
667 (void)getDominatorTree();
669 LoopInfo &LI = getAnalysis<LoopInfo>();
670 TLI = &getAnalysis<TargetLibraryInfo>();
673 (void)getTargetLibraryInfo();
675 SmallVector<BasicBlock*, 8> ExitBlocks;
676 CurLoop->getUniqueExitBlocks(ExitBlocks);
678 DEBUG(dbgs() << "loop-idiom Scanning: F["
679 << CurLoop->getHeader()->getParent()->getName()
680 << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
682 bool MadeChange = false;
683 // Scan all the blocks in the loop that are not in subloops.
684 for (Loop::block_iterator BI = CurLoop->block_begin(),
685 E = CurLoop->block_end(); BI != E; ++BI) {
686 // Ignore blocks in subloops.
687 if (LI.getLoopFor(*BI) != CurLoop)
690 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
695 bool LoopIdiomRecognize::runOnNoncountableLoop() {
696 NclPopcountRecognize Popcount(*this);
697 if (Popcount.recognize())
703 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
704 if (skipOptnoneFunction(L))
709 // If the loop could not be converted to canonical form, it must have an
710 // indirectbr in it, just give up.
711 if (!L->getLoopPreheader())
714 // Disable loop idiom recognition if the function's name is a common idiom.
715 StringRef Name = L->getHeader()->getParent()->getName();
716 if (Name == "memset" || Name == "memcpy")
719 SE = &getAnalysis<ScalarEvolution>();
720 if (SE->hasLoopInvariantBackedgeTakenCount(L))
721 return runOnCountableLoop();
722 return runOnNoncountableLoop();
725 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
726 /// with the specified backedge count. This block is known to be in the current
727 /// loop and not in any subloops.
728 bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
729 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
730 // We can only promote stores in this block if they are unconditionally
731 // executed in the loop. For a block to be unconditionally executed, it has
732 // to dominate all the exit blocks of the loop. Verify this now.
733 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
734 if (!DT->dominates(BB, ExitBlocks[i]))
737 bool MadeChange = false;
738 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
739 Instruction *Inst = I++;
740 // Look for store instructions, which may be optimized to memset/memcpy.
741 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
743 if (!processLoopStore(SI, BECount)) continue;
746 // If processing the store invalidated our iterator, start over from the
753 // Look for memset instructions, which may be optimized to a larger memset.
754 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
756 if (!processLoopMemSet(MSI, BECount)) continue;
759 // If processing the memset invalidated our iterator, start over from the
771 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
772 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
773 if (!SI->isSimple()) return false;
775 Value *StoredVal = SI->getValueOperand();
776 Value *StorePtr = SI->getPointerOperand();
778 // Reject stores that are so large that they overflow an unsigned.
779 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
780 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
783 // See if the pointer expression is an AddRec like {base,+,1} on the current
784 // loop, which indicates a strided store. If we have something else, it's a
785 // random store we can't handle.
786 const SCEVAddRecExpr *StoreEv =
787 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
788 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
791 // Check to see if the stride matches the size of the store. If so, then we
792 // know that every byte is touched in the loop.
793 unsigned StoreSize = (unsigned)SizeInBits >> 3;
794 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
796 if (!Stride || StoreSize != Stride->getValue()->getValue()) {
797 // TODO: Could also handle negative stride here someday, that will require
798 // the validity check in mayLoopAccessLocation to be updated though.
799 // Enable this to print exact negative strides.
800 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
801 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
802 dbgs() << "BB: " << *SI->getParent();
808 // See if we can optimize just this store in isolation.
809 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
810 StoredVal, SI, StoreEv, BECount))
813 // If the stored value is a strided load in the same loop with the same stride
814 // this this may be transformable into a memcpy. This kicks in for stuff like
815 // for (i) A[i] = B[i];
816 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
817 const SCEVAddRecExpr *LoadEv =
818 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
819 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
820 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
821 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
824 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
829 /// processLoopMemSet - See if this memset can be promoted to a large memset.
830 bool LoopIdiomRecognize::
831 processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
832 // We can only handle non-volatile memsets with a constant size.
833 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
835 // If we're not allowed to hack on memset, we fail.
836 if (!TLI->has(LibFunc::memset))
839 Value *Pointer = MSI->getDest();
841 // See if the pointer expression is an AddRec like {base,+,1} on the current
842 // loop, which indicates a strided store. If we have something else, it's a
843 // random store we can't handle.
844 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
845 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
848 // Reject memsets that are so large that they overflow an unsigned.
849 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
850 if ((SizeInBytes >> 32) != 0)
853 // Check to see if the stride matches the size of the memset. If so, then we
854 // know that every byte is touched in the loop.
855 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
857 // TODO: Could also handle negative stride here someday, that will require the
858 // validity check in mayLoopAccessLocation to be updated though.
859 if (!Stride || MSI->getLength() != Stride->getValue())
862 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
863 MSI->getAlignment(), MSI->getValue(),
868 /// mayLoopAccessLocation - Return true if the specified loop might access the
869 /// specified pointer location, which is a loop-strided access. The 'Access'
870 /// argument specifies what the verboten forms of access are (read or write).
871 static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
872 Loop *L, const SCEV *BECount,
873 unsigned StoreSize, AliasAnalysis &AA,
874 Instruction *IgnoredStore) {
875 // Get the location that may be stored across the loop. Since the access is
876 // strided positively through memory, we say that the modified location starts
877 // at the pointer and has infinite size.
878 uint64_t AccessSize = AliasAnalysis::UnknownSize;
880 // If the loop iterates a fixed number of times, we can refine the access size
881 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
882 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
883 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
885 // TODO: For this to be really effective, we have to dive into the pointer
886 // operand in the store. Store to &A[i] of 100 will always return may alias
887 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
888 // which will then no-alias a store to &A[100].
889 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
891 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
893 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
894 if (&*I != IgnoredStore &&
895 (AA.getModRefInfo(I, StoreLoc) & Access))
901 /// getMemSetPatternValue - If a strided store of the specified value is safe to
902 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
903 /// be passed in. Otherwise, return null.
905 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
906 /// just replicate their input array and then pass on to memset_pattern16.
907 static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
908 // If the value isn't a constant, we can't promote it to being in a constant
909 // array. We could theoretically do a store to an alloca or something, but
910 // that doesn't seem worthwhile.
911 Constant *C = dyn_cast<Constant>(V);
912 if (!C) return nullptr;
914 // Only handle simple values that are a power of two bytes in size.
915 uint64_t Size = DL.getTypeSizeInBits(V->getType());
916 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
919 // Don't care enough about darwin/ppc to implement this.
920 if (DL.isBigEndian())
923 // Convert to size in bytes.
926 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
927 // if the top and bottom are the same (e.g. for vectors and large integers).
928 if (Size > 16) return nullptr;
930 // If the constant is exactly 16 bytes, just use it.
931 if (Size == 16) return C;
933 // Otherwise, we'll use an array of the constants.
934 unsigned ArraySize = 16/Size;
935 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
936 return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
940 /// processLoopStridedStore - We see a strided store of some value. If we can
941 /// transform this into a memset or memset_pattern in the loop preheader, do so.
942 bool LoopIdiomRecognize::
943 processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
944 unsigned StoreAlignment, Value *StoredVal,
945 Instruction *TheStore, const SCEVAddRecExpr *Ev,
946 const SCEV *BECount) {
948 // If the stored value is a byte-wise value (like i32 -1), then it may be
949 // turned into a memset of i8 -1, assuming that all the consecutive bytes
950 // are stored. A store of i32 0x01020304 can never be turned into a memset,
951 // but it can be turned into memset_pattern if the target supports it.
952 Value *SplatValue = isBytewiseValue(StoredVal);
953 Constant *PatternValue = nullptr;
955 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
957 // If we're allowed to form a memset, and the stored value would be acceptable
958 // for memset, use it.
959 if (SplatValue && TLI->has(LibFunc::memset) &&
960 // Verify that the stored value is loop invariant. If not, we can't
961 // promote the memset.
962 CurLoop->isLoopInvariant(SplatValue)) {
963 // Keep and use SplatValue.
964 PatternValue = nullptr;
965 } else if (DestAS == 0 &&
966 TLI->has(LibFunc::memset_pattern16) &&
967 (PatternValue = getMemSetPatternValue(StoredVal, *DL))) {
968 // Don't create memset_pattern16s with address spaces.
969 // It looks like we can use PatternValue!
970 SplatValue = nullptr;
972 // Otherwise, this isn't an idiom we can transform. For example, we can't
973 // do anything with a 3-byte store.
977 // The trip count of the loop and the base pointer of the addrec SCEV is
978 // guaranteed to be loop invariant, which means that it should dominate the
979 // header. This allows us to insert code for it in the preheader.
980 BasicBlock *Preheader = CurLoop->getLoopPreheader();
981 IRBuilder<> Builder(Preheader->getTerminator());
982 SCEVExpander Expander(*SE, "loop-idiom");
984 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
986 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
987 // this into a memset in the loop preheader now if we want. However, this
988 // would be unsafe to do if there is anything else in the loop that may read
989 // or write to the aliased location. Check for any overlap by generating the
990 // base pointer and checking the region.
992 Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
993 Preheader->getTerminator());
995 if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
997 StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
999 // If we generated new code for the base pointer, clean up.
1000 deleteIfDeadInstruction(BasePtr, *SE, TLI);
1004 // Okay, everything looks good, insert the memset.
1006 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1007 // pointer size if it isn't already.
1008 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
1009 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
1011 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
1013 if (StoreSize != 1) {
1014 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
1019 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
1023 NewCall = Builder.CreateMemSet(BasePtr,
1028 // Everything is emitted in default address space
1029 Type *Int8PtrTy = DestInt8PtrTy;
1031 Module *M = TheStore->getParent()->getParent()->getParent();
1032 Value *MSP = M->getOrInsertFunction("memset_pattern16",
1033 Builder.getVoidTy(),
1039 // Otherwise we should form a memset_pattern16. PatternValue is known to be
1040 // an constant array of 16-bytes. Plop the value into a mergable global.
1041 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1042 GlobalValue::InternalLinkage,
1043 PatternValue, ".memset_pattern");
1044 GV->setUnnamedAddr(true); // Ok to merge these.
1045 GV->setAlignment(16);
1046 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
1047 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
1050 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
1051 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
1052 NewCall->setDebugLoc(TheStore->getDebugLoc());
1054 // Okay, the memset has been formed. Zap the original store and anything that
1056 deleteDeadInstruction(TheStore, *SE, TLI);
1061 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
1062 /// same-strided load.
1063 bool LoopIdiomRecognize::
1064 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
1065 const SCEVAddRecExpr *StoreEv,
1066 const SCEVAddRecExpr *LoadEv,
1067 const SCEV *BECount) {
1068 // If we're not allowed to form memcpy, we fail.
1069 if (!TLI->has(LibFunc::memcpy))
1072 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1074 // The trip count of the loop and the base pointer of the addrec SCEV is
1075 // guaranteed to be loop invariant, which means that it should dominate the
1076 // header. This allows us to insert code for it in the preheader.
1077 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1078 IRBuilder<> Builder(Preheader->getTerminator());
1079 SCEVExpander Expander(*SE, "loop-idiom");
1081 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
1082 // this into a memcpy in the loop preheader now if we want. However, this
1083 // would be unsafe to do if there is anything else in the loop that may read
1084 // or write the memory region we're storing to. This includes the load that
1085 // feeds the stores. Check for an alias by generating the base address and
1086 // checking everything.
1087 Value *StoreBasePtr =
1088 Expander.expandCodeFor(StoreEv->getStart(),
1089 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1090 Preheader->getTerminator());
1092 if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
1093 CurLoop, BECount, StoreSize,
1094 getAnalysis<AliasAnalysis>(), SI)) {
1096 // If we generated new code for the base pointer, clean up.
1097 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1101 // For a memcpy, we have to make sure that the input array is not being
1102 // mutated by the loop.
1103 Value *LoadBasePtr =
1104 Expander.expandCodeFor(LoadEv->getStart(),
1105 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1106 Preheader->getTerminator());
1108 if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
1109 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1111 // If we generated new code for the base pointer, clean up.
1112 deleteIfDeadInstruction(LoadBasePtr, *SE, TLI);
1113 deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1117 // Okay, everything is safe, we can transform this!
1120 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1121 // pointer size if it isn't already.
1122 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
1123 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
1125 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
1128 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
1132 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1135 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1136 std::min(SI->getAlignment(), LI->getAlignment()));
1137 NewCall->setDebugLoc(SI->getDebugLoc());
1139 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
1140 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1141 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
1144 // Okay, the memset has been formed. Zap the original store and anything that
1146 deleteDeadInstruction(SI, *SE, TLI);