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/TargetLibraryInfo.h"
51 #include "llvm/Analysis/TargetTransformInfo.h"
52 #include "llvm/Analysis/ValueTracking.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Transforms/Utils/Local.h"
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 population bit. 2) \p CntPhi
119 /// is set to the corresponding phi node. 3) \p Var is set to the value
120 /// whose population bits are being counted.
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 {
135 TargetLibraryInfo *TLI;
136 const TargetTransformInfo *TTI;
139 explicit LoopIdiomRecognize() : LoopPass(ID) {
140 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
147 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
148 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
149 SmallVectorImpl<BasicBlock*> &ExitBlocks);
151 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
152 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
154 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
155 unsigned StoreAlignment,
156 Value *SplatValue, Instruction *TheStore,
157 const SCEVAddRecExpr *Ev,
158 const SCEV *BECount);
159 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
160 const SCEVAddRecExpr *StoreEv,
161 const SCEVAddRecExpr *LoadEv,
162 const SCEV *BECount);
164 /// This transformation requires natural loop information & requires that
165 /// loop preheaders be inserted into the CFG.
167 void getAnalysisUsage(AnalysisUsage &AU) const override {
168 AU.addRequired<LoopInfoWrapperPass>();
169 AU.addPreserved<LoopInfoWrapperPass>();
170 AU.addRequiredID(LoopSimplifyID);
171 AU.addPreservedID(LoopSimplifyID);
172 AU.addRequiredID(LCSSAID);
173 AU.addPreservedID(LCSSAID);
174 AU.addRequired<AliasAnalysis>();
175 AU.addPreserved<AliasAnalysis>();
176 AU.addRequired<ScalarEvolution>();
177 AU.addPreserved<ScalarEvolution>();
178 AU.addPreserved<DominatorTreeWrapperPass>();
179 AU.addRequired<DominatorTreeWrapperPass>();
180 AU.addRequired<TargetLibraryInfoWrapperPass>();
181 AU.addRequired<TargetTransformInfoWrapperPass>();
184 DominatorTree *getDominatorTree() {
186 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
189 ScalarEvolution *getScalarEvolution() {
190 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
193 TargetLibraryInfo *getTargetLibraryInfo() {
195 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
200 const TargetTransformInfo *getTargetTransformInfo() {
202 : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
203 *CurLoop->getHeader()->getParent()));
206 Loop *getLoop() const { return CurLoop; }
209 bool runOnNoncountableLoop();
210 bool runOnCountableLoop();
214 char LoopIdiomRecognize::ID = 0;
215 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
217 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
218 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
219 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
220 INITIALIZE_PASS_DEPENDENCY(LCSSA)
221 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
222 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
223 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
224 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
225 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
228 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
230 /// deleteDeadInstruction - Delete this instruction. Before we do, go through
231 /// and zero out all the operands of this instruction. If any of them become
232 /// dead, delete them and the computation tree that feeds them.
234 static void deleteDeadInstruction(Instruction *I,
235 const TargetLibraryInfo *TLI) {
236 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
237 I->replaceAllUsesWith(UndefValue::get(I->getType()));
238 I->eraseFromParent();
239 for (Value *Op : Operands)
240 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
243 //===----------------------------------------------------------------------===//
245 // Implementation of LIRUtil
247 //===----------------------------------------------------------------------===//
249 // This function will return true iff the given block contains nothing but goto.
250 // A typical usage of this function is to check if the preheader function is
251 // "almost" empty such that generated intrinsic functions can be moved across
252 // the preheader and be placed at the end of the precondition block without
253 // the concern of breaking data dependence.
254 bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
255 if (BranchInst *Br = getBranch(BB)) {
256 return Br->isUnconditional() && Br == BB->begin();
261 BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
262 if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
263 BranchInst *Br = getBranch(BB);
264 return Br && Br->isConditional() ? BB : nullptr;
269 //===----------------------------------------------------------------------===//
271 // Implementation of NclPopcountRecognize
273 //===----------------------------------------------------------------------===//
275 NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
276 LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {
279 bool NclPopcountRecognize::preliminaryScreen() {
280 const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
281 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
284 // Counting population are usually conducted by few arithmetic instructions.
285 // Such instructions can be easilly "absorbed" by vacant slots in a
286 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
287 // in a compact loop.
289 // Give up if the loop has multiple blocks or multiple backedges.
290 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
293 BasicBlock *LoopBody = *(CurLoop->block_begin());
294 if (LoopBody->size() >= 20) {
295 // The loop is too big, bail out.
299 // It should have a preheader containing nothing but a goto instruction.
300 BasicBlock *PreHead = CurLoop->getLoopPreheader();
301 if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
304 // It should have a precondition block where the generated popcount instrinsic
305 // function will be inserted.
306 PreCondBB = LIRUtil::getPrecondBb(PreHead);
313 Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
314 BasicBlock *LoopEntry) const {
315 if (!Br || !Br->isConditional())
318 ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
322 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
323 if (!CmpZero || !CmpZero->isZero())
326 ICmpInst::Predicate Pred = Cond->getPredicate();
327 if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
328 (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
329 return Cond->getOperand(0);
334 bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
337 // Following code tries to detect this idiom:
340 // goto loop-exit // the precondition of the loop
343 // x1 = phi (x0, x2);
344 // cnt1 = phi(cnt0, cnt2);
348 // x2 = x1 & (x1 - 1);
355 // step 1: Check to see if the look-back branch match this pattern:
356 // "if (a!=0) goto loop-entry".
357 BasicBlock *LoopEntry;
358 Instruction *DefX2, *CountInst;
359 Value *VarX1, *VarX0;
360 PHINode *PhiX, *CountPhi;
362 DefX2 = CountInst = nullptr;
363 VarX1 = VarX0 = nullptr;
364 PhiX = CountPhi = nullptr;
365 LoopEntry = *(CurLoop->block_begin());
367 // step 1: Check if the loop-back branch is in desirable form.
369 if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
370 DefX2 = dyn_cast<Instruction>(T);
375 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
377 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
380 BinaryOperator *SubOneOp;
382 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
383 VarX1 = DefX2->getOperand(1);
385 VarX1 = DefX2->getOperand(0);
386 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
391 Instruction *SubInst = cast<Instruction>(SubOneOp);
392 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
394 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
395 (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
400 // step 3: Check the recurrence of variable X
402 PhiX = dyn_cast<PHINode>(VarX1);
404 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
409 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
412 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
413 IterE = LoopEntry->end(); Iter != IterE; Iter++) {
414 Instruction *Inst = Iter;
415 if (Inst->getOpcode() != Instruction::Add)
418 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
419 if (!Inc || !Inc->isOne())
422 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
423 if (!Phi || Phi->getParent() != LoopEntry)
426 // Check if the result of the instruction is live of the loop.
427 bool LiveOutLoop = false;
428 for (User *U : Inst->users()) {
429 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
430 LiveOutLoop = true; break;
445 // step 5: check if the precondition is in this form:
446 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
448 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
449 Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
450 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
461 void NclPopcountRecognize::transform(Instruction *CntInst,
462 PHINode *CntPhi, Value *Var) {
464 ScalarEvolution *SE = LIR.getScalarEvolution();
465 TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
466 BasicBlock *PreHead = CurLoop->getLoopPreheader();
467 BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
468 const DebugLoc DL = CntInst->getDebugLoc();
470 // Assuming before transformation, the loop is following:
471 // if (x) // the precondition
472 // do { cnt++; x &= x - 1; } while(x);
474 // Step 1: Insert the ctpop instruction at the end of the precondition block
475 IRBuilderTy Builder(PreCondBr);
476 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
478 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
479 NewCount = PopCntZext =
480 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
482 if (NewCount != PopCnt)
483 (cast<Instruction>(NewCount))->setDebugLoc(DL);
485 // TripCnt is exactly the number of iterations the loop has
488 // If the population counter's initial value is not zero, insert Add Inst.
489 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
490 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
491 if (!InitConst || !InitConst->isZero()) {
492 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
493 (cast<Instruction>(NewCount))->setDebugLoc(DL);
497 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
498 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
499 // function would be partial dead code, and downstream passes will drag
500 // it back from the precondition block to the preheader.
502 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
504 Value *Opnd0 = PopCntZext;
505 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
506 if (PreCond->getOperand(0) != Var)
507 std::swap(Opnd0, Opnd1);
509 ICmpInst *NewPreCond =
510 cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
511 PreCond->replaceAllUsesWith(NewPreCond);
513 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
516 // Step 3: Note that the population count is exactly the trip count of the
517 // loop in question, which enble us to to convert the loop from noncountable
518 // loop into a countable one. The benefit is twofold:
520 // - If the loop only counts population, the entire loop become dead after
521 // the transformation. It is lots easier to prove a countable loop dead
522 // than to prove a noncountable one. (In some C dialects, a infite loop
523 // isn't dead even if it computes nothing useful. In general, DCE needs
524 // to prove a noncountable loop finite before safely delete it.)
526 // - If the loop also performs something else, it remains alive.
527 // Since it is transformed to countable form, it can be aggressively
528 // optimized by some optimizations which are in general not applicable
529 // to a noncountable loop.
531 // After this step, this loop (conceptually) would look like following:
532 // newcnt = __builtin_ctpop(x);
535 // do { cnt++; x &= x-1; t--) } while (t > 0);
536 BasicBlock *Body = *(CurLoop->block_begin());
538 BranchInst *LbBr = LIRUtil::getBranch(Body);
539 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
540 Type *Ty = TripCnt->getType();
542 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
544 Builder.SetInsertPoint(LbCond);
545 Value *Opnd1 = cast<Value>(TcPhi);
546 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
548 cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
550 TcPhi->addIncoming(TripCnt, PreHead);
551 TcPhi->addIncoming(TcDec, Body);
553 CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
554 CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
555 LbCond->setPredicate(Pred);
556 LbCond->setOperand(0, TcDec);
557 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
560 // Step 4: All the references to the original population counter outside
561 // the loop are replaced with the NewCount -- the value returned from
562 // __builtin_ctpop().
563 CntInst->replaceUsesOutsideBlock(NewCount, Body);
565 // step 5: Forget the "non-computable" trip-count SCEV associated with the
566 // loop. The loop would otherwise not be deleted even if it becomes empty.
567 SE->forgetLoop(CurLoop);
570 CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
571 Value *Val, DebugLoc DL) {
572 Value *Ops[] = { Val };
573 Type *Tys[] = { Val->getType() };
575 Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
576 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
577 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
583 /// recognize - detect population count idiom in a non-countable loop. If
584 /// detected, transform the relevant code to popcount intrinsic function
585 /// call, and return true; otherwise, return false.
586 bool NclPopcountRecognize::recognize() {
588 if (!LIR.getTargetTransformInfo())
591 LIR.getScalarEvolution();
593 if (!preliminaryScreen())
596 Instruction *CntInst;
599 if (!detectIdiom(CntInst, CntPhi, Val))
602 transform(CntInst, CntPhi, Val);
606 //===----------------------------------------------------------------------===//
608 // Implementation of LoopIdiomRecognize
610 //===----------------------------------------------------------------------===//
612 bool LoopIdiomRecognize::runOnCountableLoop() {
613 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
614 assert(!isa<SCEVCouldNotCompute>(BECount) &&
615 "runOnCountableLoop() called on a loop without a predictable"
616 "backedge-taken count");
618 // If this loop executes exactly one time, then it should be peeled, not
619 // optimized by this pass.
620 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
621 if (BECst->getValue()->getValue() == 0)
625 (void)getDominatorTree();
627 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
628 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
631 (void)getTargetLibraryInfo();
633 SmallVector<BasicBlock*, 8> ExitBlocks;
634 CurLoop->getUniqueExitBlocks(ExitBlocks);
636 DEBUG(dbgs() << "loop-idiom Scanning: F["
637 << CurLoop->getHeader()->getParent()->getName()
638 << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
640 bool MadeChange = false;
641 // Scan all the blocks in the loop that are not in subloops.
642 for (Loop::block_iterator BI = CurLoop->block_begin(),
643 E = CurLoop->block_end(); BI != E; ++BI) {
644 // Ignore blocks in subloops.
645 if (LI.getLoopFor(*BI) != CurLoop)
648 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
653 bool LoopIdiomRecognize::runOnNoncountableLoop() {
654 NclPopcountRecognize Popcount(*this);
655 if (Popcount.recognize())
661 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
662 if (skipOptnoneFunction(L))
667 // If the loop could not be converted to canonical form, it must have an
668 // indirectbr in it, just give up.
669 if (!L->getLoopPreheader())
672 // Disable loop idiom recognition if the function's name is a common idiom.
673 StringRef Name = L->getHeader()->getParent()->getName();
674 if (Name == "memset" || Name == "memcpy")
677 SE = &getAnalysis<ScalarEvolution>();
678 if (SE->hasLoopInvariantBackedgeTakenCount(L))
679 return runOnCountableLoop();
680 return runOnNoncountableLoop();
683 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
684 /// with the specified backedge count. This block is known to be in the current
685 /// loop and not in any subloops.
686 bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
687 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
688 // We can only promote stores in this block if they are unconditionally
689 // executed in the loop. For a block to be unconditionally executed, it has
690 // to dominate all the exit blocks of the loop. Verify this now.
691 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
692 if (!DT->dominates(BB, ExitBlocks[i]))
695 bool MadeChange = false;
696 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
697 Instruction *Inst = I++;
698 // Look for store instructions, which may be optimized to memset/memcpy.
699 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
701 if (!processLoopStore(SI, BECount)) continue;
704 // If processing the store invalidated our iterator, start over from the
711 // Look for memset instructions, which may be optimized to a larger memset.
712 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
714 if (!processLoopMemSet(MSI, BECount)) continue;
717 // If processing the memset invalidated our iterator, start over from the
729 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
730 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
731 if (!SI->isSimple()) return false;
733 Value *StoredVal = SI->getValueOperand();
734 Value *StorePtr = SI->getPointerOperand();
736 // Reject stores that are so large that they overflow an unsigned.
737 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
738 uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
739 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
742 // See if the pointer expression is an AddRec like {base,+,1} on the current
743 // loop, which indicates a strided store. If we have something else, it's a
744 // random store we can't handle.
745 const SCEVAddRecExpr *StoreEv =
746 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
747 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
750 // Check to see if the stride matches the size of the store. If so, then we
751 // know that every byte is touched in the loop.
752 unsigned StoreSize = (unsigned)SizeInBits >> 3;
753 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
755 if (!Stride || StoreSize != Stride->getValue()->getValue()) {
756 // TODO: Could also handle negative stride here someday, that will require
757 // the validity check in mayLoopAccessLocation to be updated though.
758 // Enable this to print exact negative strides.
759 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
760 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
761 dbgs() << "BB: " << *SI->getParent();
767 // See if we can optimize just this store in isolation.
768 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
769 StoredVal, SI, StoreEv, BECount))
772 // If the stored value is a strided load in the same loop with the same stride
773 // this this may be transformable into a memcpy. This kicks in for stuff like
774 // for (i) A[i] = B[i];
775 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
776 const SCEVAddRecExpr *LoadEv =
777 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
778 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
779 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
780 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
783 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
788 /// processLoopMemSet - See if this memset can be promoted to a large memset.
789 bool LoopIdiomRecognize::
790 processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
791 // We can only handle non-volatile memsets with a constant size.
792 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
794 // If we're not allowed to hack on memset, we fail.
795 if (!TLI->has(LibFunc::memset))
798 Value *Pointer = MSI->getDest();
800 // See if the pointer expression is an AddRec like {base,+,1} on the current
801 // loop, which indicates a strided store. If we have something else, it's a
802 // random store we can't handle.
803 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
804 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
807 // Reject memsets that are so large that they overflow an unsigned.
808 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
809 if ((SizeInBytes >> 32) != 0)
812 // Check to see if the stride matches the size of the memset. If so, then we
813 // know that every byte is touched in the loop.
814 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
816 // TODO: Could also handle negative stride here someday, that will require the
817 // validity check in mayLoopAccessLocation to be updated though.
818 if (!Stride || MSI->getLength() != Stride->getValue())
821 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
822 MSI->getAlignment(), MSI->getValue(),
827 /// mayLoopAccessLocation - Return true if the specified loop might access the
828 /// specified pointer location, which is a loop-strided access. The 'Access'
829 /// argument specifies what the verboten forms of access are (read or write).
830 static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
831 Loop *L, const SCEV *BECount,
832 unsigned StoreSize, AliasAnalysis &AA,
833 Instruction *IgnoredStore) {
834 // Get the location that may be stored across the loop. Since the access is
835 // strided positively through memory, we say that the modified location starts
836 // at the pointer and has infinite size.
837 uint64_t AccessSize = AliasAnalysis::UnknownSize;
839 // If the loop iterates a fixed number of times, we can refine the access size
840 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
841 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
842 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
844 // TODO: For this to be really effective, we have to dive into the pointer
845 // operand in the store. Store to &A[i] of 100 will always return may alias
846 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
847 // which will then no-alias a store to &A[100].
848 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
850 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
852 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
853 if (&*I != IgnoredStore &&
854 (AA.getModRefInfo(I, StoreLoc) & Access))
860 /// getMemSetPatternValue - If a strided store of the specified value is safe to
861 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
862 /// be passed in. Otherwise, return null.
864 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
865 /// just replicate their input array and then pass on to memset_pattern16.
866 static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
867 // If the value isn't a constant, we can't promote it to being in a constant
868 // array. We could theoretically do a store to an alloca or something, but
869 // that doesn't seem worthwhile.
870 Constant *C = dyn_cast<Constant>(V);
871 if (!C) return nullptr;
873 // Only handle simple values that are a power of two bytes in size.
874 uint64_t Size = DL.getTypeSizeInBits(V->getType());
875 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
878 // Don't care enough about darwin/ppc to implement this.
879 if (DL.isBigEndian())
882 // Convert to size in bytes.
885 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
886 // if the top and bottom are the same (e.g. for vectors and large integers).
887 if (Size > 16) return nullptr;
889 // If the constant is exactly 16 bytes, just use it.
890 if (Size == 16) return C;
892 // Otherwise, we'll use an array of the constants.
893 unsigned ArraySize = 16/Size;
894 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
895 return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
899 /// processLoopStridedStore - We see a strided store of some value. If we can
900 /// transform this into a memset or memset_pattern in the loop preheader, do so.
901 bool LoopIdiomRecognize::
902 processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
903 unsigned StoreAlignment, Value *StoredVal,
904 Instruction *TheStore, const SCEVAddRecExpr *Ev,
905 const SCEV *BECount) {
907 // If the stored value is a byte-wise value (like i32 -1), then it may be
908 // turned into a memset of i8 -1, assuming that all the consecutive bytes
909 // are stored. A store of i32 0x01020304 can never be turned into a memset,
910 // but it can be turned into memset_pattern if the target supports it.
911 Value *SplatValue = isBytewiseValue(StoredVal);
912 Constant *PatternValue = nullptr;
913 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
914 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
916 // If we're allowed to form a memset, and the stored value would be acceptable
917 // for memset, use it.
918 if (SplatValue && TLI->has(LibFunc::memset) &&
919 // Verify that the stored value is loop invariant. If not, we can't
920 // promote the memset.
921 CurLoop->isLoopInvariant(SplatValue)) {
922 // Keep and use SplatValue.
923 PatternValue = nullptr;
924 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
925 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
926 // Don't create memset_pattern16s with address spaces.
927 // It looks like we can use PatternValue!
928 SplatValue = nullptr;
930 // Otherwise, this isn't an idiom we can transform. For example, we can't
931 // do anything with a 3-byte store.
935 // The trip count of the loop and the base pointer of the addrec SCEV is
936 // guaranteed to be loop invariant, which means that it should dominate the
937 // header. This allows us to insert code for it in the preheader.
938 BasicBlock *Preheader = CurLoop->getLoopPreheader();
939 IRBuilder<> Builder(Preheader->getTerminator());
940 SCEVExpander Expander(*SE, DL, "loop-idiom");
942 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
944 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
945 // this into a memset in the loop preheader now if we want. However, this
946 // would be unsafe to do if there is anything else in the loop that may read
947 // or write to the aliased location. Check for any overlap by generating the
948 // base pointer and checking the region.
950 Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
951 Preheader->getTerminator());
953 if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
955 StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
957 // If we generated new code for the base pointer, clean up.
958 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
962 // Okay, everything looks good, insert the memset.
964 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
965 // pointer size if it isn't already.
966 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
967 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
969 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
971 if (StoreSize != 1) {
972 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
977 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
981 NewCall = Builder.CreateMemSet(BasePtr,
986 // Everything is emitted in default address space
987 Type *Int8PtrTy = DestInt8PtrTy;
989 Module *M = TheStore->getParent()->getParent()->getParent();
990 Value *MSP = M->getOrInsertFunction("memset_pattern16",
997 // Otherwise we should form a memset_pattern16. PatternValue is known to be
998 // an constant array of 16-bytes. Plop the value into a mergable global.
999 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1000 GlobalValue::PrivateLinkage,
1001 PatternValue, ".memset_pattern");
1002 GV->setUnnamedAddr(true); // Ok to merge these.
1003 GV->setAlignment(16);
1004 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
1005 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
1008 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
1009 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
1010 NewCall->setDebugLoc(TheStore->getDebugLoc());
1012 // Okay, the memset has been formed. Zap the original store and anything that
1014 deleteDeadInstruction(TheStore, TLI);
1019 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
1020 /// same-strided load.
1021 bool LoopIdiomRecognize::
1022 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
1023 const SCEVAddRecExpr *StoreEv,
1024 const SCEVAddRecExpr *LoadEv,
1025 const SCEV *BECount) {
1026 // If we're not allowed to form memcpy, we fail.
1027 if (!TLI->has(LibFunc::memcpy))
1030 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1032 // The trip count of the loop and the base pointer of the addrec SCEV is
1033 // guaranteed to be loop invariant, which means that it should dominate the
1034 // header. This allows us to insert code for it in the preheader.
1035 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1036 IRBuilder<> Builder(Preheader->getTerminator());
1037 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1038 SCEVExpander Expander(*SE, DL, "loop-idiom");
1040 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
1041 // this into a memcpy in the loop preheader now if we want. However, this
1042 // would be unsafe to do if there is anything else in the loop that may read
1043 // or write the memory region we're storing to. This includes the load that
1044 // feeds the stores. Check for an alias by generating the base address and
1045 // checking everything.
1046 Value *StoreBasePtr =
1047 Expander.expandCodeFor(StoreEv->getStart(),
1048 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1049 Preheader->getTerminator());
1051 if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
1052 CurLoop, BECount, StoreSize,
1053 getAnalysis<AliasAnalysis>(), SI)) {
1055 // If we generated new code for the base pointer, clean up.
1056 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
1060 // For a memcpy, we have to make sure that the input array is not being
1061 // mutated by the loop.
1062 Value *LoadBasePtr =
1063 Expander.expandCodeFor(LoadEv->getStart(),
1064 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1065 Preheader->getTerminator());
1067 if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
1068 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1070 // If we generated new code for the base pointer, clean up.
1071 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1072 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
1076 // Okay, everything is safe, we can transform this!
1079 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1080 // pointer size if it isn't already.
1081 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
1082 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
1084 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
1087 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
1091 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1094 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1095 std::min(SI->getAlignment(), LI->getAlignment()));
1096 NewCall->setDebugLoc(SI->getDebugLoc());
1098 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
1099 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1100 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
1103 // Okay, the memset has been formed. Zap the original store and anything that
1105 deleteDeadInstruction(SI, TLI);