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 is to recoginize idioms of population-count conducted in
73 /// a noncountable loop. Currently it only recognizes this pattern:
75 /// while(x) {cnt++; ...; x &= x - 1; ...}
77 class NclPopcountRecognize {
78 LoopIdiomRecognize &LIR;
80 BasicBlock *PreCondBB;
82 typedef IRBuilder<> IRBuilderTy;
85 explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
89 /// Take a glimpse of the loop to see if we need to go ahead recoginizing
91 bool preliminaryScreen();
93 /// Check if the given conditional branch is based on the comparison
94 /// between a variable and zero, and if the variable is non-zero, the
95 /// control yields to the loop entry. If the branch matches the behavior,
96 /// the variable involved in the comparion is returned. This function will
97 /// be called to see if the precondition and postcondition of the loop
98 /// are in desirable form.
99 Value *matchCondition(BranchInst *Br, BasicBlock *NonZeroTarget) const;
101 /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
102 /// is set to the instruction counting the population bit. 2) \p CntPhi
103 /// is set to the corresponding phi node. 3) \p Var is set to the value
104 /// whose population bits are being counted.
105 bool detectIdiom(Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
107 /// Insert ctpop intrinsic function and some obviously dead instructions.
108 void transform(Instruction *CntInst, PHINode *CntPhi, Value *Var);
110 /// Create llvm.ctpop.* intrinsic function.
111 CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
114 class LoopIdiomRecognize : public LoopPass {
118 TargetLibraryInfo *TLI;
119 const TargetTransformInfo *TTI;
123 explicit LoopIdiomRecognize() : LoopPass(ID) {
124 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
131 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
132 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
133 SmallVectorImpl<BasicBlock *> &ExitBlocks);
135 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
136 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
138 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
139 unsigned StoreAlignment, Value *SplatValue,
140 Instruction *TheStore, const SCEVAddRecExpr *Ev,
141 const SCEV *BECount);
142 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
143 const SCEVAddRecExpr *StoreEv,
144 const SCEVAddRecExpr *LoadEv,
145 const SCEV *BECount);
147 /// This transformation requires natural loop information & requires that
148 /// loop preheaders be inserted into the CFG.
150 void getAnalysisUsage(AnalysisUsage &AU) const override {
151 AU.addRequired<LoopInfoWrapperPass>();
152 AU.addPreserved<LoopInfoWrapperPass>();
153 AU.addRequiredID(LoopSimplifyID);
154 AU.addPreservedID(LoopSimplifyID);
155 AU.addRequiredID(LCSSAID);
156 AU.addPreservedID(LCSSAID);
157 AU.addRequired<AliasAnalysis>();
158 AU.addPreserved<AliasAnalysis>();
159 AU.addRequired<ScalarEvolution>();
160 AU.addPreserved<ScalarEvolution>();
161 AU.addPreserved<DominatorTreeWrapperPass>();
162 AU.addRequired<DominatorTreeWrapperPass>();
163 AU.addRequired<TargetLibraryInfoWrapperPass>();
164 AU.addRequired<TargetTransformInfoWrapperPass>();
167 DominatorTree *getDominatorTree() {
169 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
172 ScalarEvolution *getScalarEvolution() {
173 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
176 TargetLibraryInfo *getTargetLibraryInfo() {
178 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
183 const TargetTransformInfo *getTargetTransformInfo() {
185 : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
186 *CurLoop->getHeader()->getParent()));
189 Loop *getLoop() const { return CurLoop; }
192 bool runOnNoncountableLoop();
193 bool runOnCountableLoop();
196 } // End anonymous namespace.
198 char LoopIdiomRecognize::ID = 0;
199 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
201 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
202 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
203 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
204 INITIALIZE_PASS_DEPENDENCY(LCSSA)
205 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
206 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
207 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
208 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
209 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
212 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
214 /// deleteDeadInstruction - Delete this instruction. Before we do, go through
215 /// and zero out all the operands of this instruction. If any of them become
216 /// dead, delete them and the computation tree that feeds them.
218 static void deleteDeadInstruction(Instruction *I,
219 const TargetLibraryInfo *TLI) {
220 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
221 I->replaceAllUsesWith(UndefValue::get(I->getType()));
222 I->eraseFromParent();
223 for (Value *Op : Operands)
224 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
227 //===----------------------------------------------------------------------===//
229 // Implementation of NclPopcountRecognize
231 //===----------------------------------------------------------------------===//
233 NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR)
234 : LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {}
236 bool NclPopcountRecognize::preliminaryScreen() {
237 const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
238 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
241 // Counting population are usually conducted by few arithmetic instructions.
242 // Such instructions can be easilly "absorbed" by vacant slots in a
243 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
244 // in a compact loop.
246 // Give up if the loop has multiple blocks or multiple backedges.
247 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
250 BasicBlock *LoopBody = *(CurLoop->block_begin());
251 if (LoopBody->size() >= 20) {
252 // The loop is too big, bail out.
256 // It should have a preheader containing nothing but an unconditional branch.
257 BasicBlock *PH = CurLoop->getLoopPreheader();
260 if (&PH->front() != PH->getTerminator())
262 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
263 if (!EntryBI || EntryBI->isConditional())
266 // It should have a precondition block where the generated popcount instrinsic
267 // function can be inserted.
268 PreCondBB = PH->getSinglePredecessor();
271 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
272 if (!PreCondBI || PreCondBI->isUnconditional())
278 Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
279 BasicBlock *LoopEntry) const {
280 if (!Br || !Br->isConditional())
283 ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
287 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
288 if (!CmpZero || !CmpZero->isZero())
291 ICmpInst::Predicate Pred = Cond->getPredicate();
292 if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
293 (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
294 return Cond->getOperand(0);
299 bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst, PHINode *&CntPhi,
301 // Following code tries to detect this idiom:
304 // goto loop-exit // the precondition of the loop
307 // x1 = phi (x0, x2);
308 // cnt1 = phi(cnt0, cnt2);
312 // x2 = x1 & (x1 - 1);
319 // step 1: Check to see if the look-back branch match this pattern:
320 // "if (a!=0) goto loop-entry".
321 BasicBlock *LoopEntry;
322 Instruction *DefX2, *CountInst;
323 Value *VarX1, *VarX0;
324 PHINode *PhiX, *CountPhi;
326 DefX2 = CountInst = nullptr;
327 VarX1 = VarX0 = nullptr;
328 PhiX = CountPhi = nullptr;
329 LoopEntry = *(CurLoop->block_begin());
331 // step 1: Check if the loop-back branch is in desirable form.
333 if (Value *T = matchCondition(
334 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
335 DefX2 = dyn_cast<Instruction>(T);
340 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
342 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
345 BinaryOperator *SubOneOp;
347 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
348 VarX1 = DefX2->getOperand(1);
350 VarX1 = DefX2->getOperand(0);
351 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
356 Instruction *SubInst = cast<Instruction>(SubOneOp);
357 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
359 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
360 (SubInst->getOpcode() == Instruction::Add &&
361 Dec->isAllOnesValue()))) {
366 // step 3: Check the recurrence of variable X
368 PhiX = dyn_cast<PHINode>(VarX1);
370 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
375 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
378 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
379 IterE = LoopEntry->end();
380 Iter != IterE; Iter++) {
381 Instruction *Inst = Iter;
382 if (Inst->getOpcode() != Instruction::Add)
385 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
386 if (!Inc || !Inc->isOne())
389 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
390 if (!Phi || Phi->getParent() != LoopEntry)
393 // Check if the result of the instruction is live of the loop.
394 bool LiveOutLoop = false;
395 for (User *U : Inst->users()) {
396 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
413 // step 5: check if the precondition is in this form:
414 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
416 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
417 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
418 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
429 void NclPopcountRecognize::transform(Instruction *CntInst, PHINode *CntPhi,
432 ScalarEvolution *SE = LIR.getScalarEvolution();
433 TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
434 BasicBlock *PreHead = CurLoop->getLoopPreheader();
435 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
436 const DebugLoc DL = CntInst->getDebugLoc();
438 // Assuming before transformation, the loop is following:
439 // if (x) // the precondition
440 // do { cnt++; x &= x - 1; } while(x);
442 // Step 1: Insert the ctpop instruction at the end of the precondition block
443 IRBuilderTy Builder(PreCondBr);
444 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
446 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
447 NewCount = PopCntZext =
448 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
450 if (NewCount != PopCnt)
451 (cast<Instruction>(NewCount))->setDebugLoc(DL);
453 // TripCnt is exactly the number of iterations the loop has
456 // If the population counter's initial value is not zero, insert Add Inst.
457 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
458 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
459 if (!InitConst || !InitConst->isZero()) {
460 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
461 (cast<Instruction>(NewCount))->setDebugLoc(DL);
465 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
466 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
467 // function would be partial dead code, and downstream passes will drag
468 // it back from the precondition block to the preheader.
470 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
472 Value *Opnd0 = PopCntZext;
473 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
474 if (PreCond->getOperand(0) != Var)
475 std::swap(Opnd0, Opnd1);
477 ICmpInst *NewPreCond = cast<ICmpInst>(
478 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
479 PreCondBr->setCondition(NewPreCond);
481 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
484 // Step 3: Note that the population count is exactly the trip count of the
485 // loop in question, which enble us to to convert the loop from noncountable
486 // loop into a countable one. The benefit is twofold:
488 // - If the loop only counts population, the entire loop become dead after
489 // the transformation. It is lots easier to prove a countable loop dead
490 // than to prove a noncountable one. (In some C dialects, a infite loop
491 // isn't dead even if it computes nothing useful. In general, DCE needs
492 // to prove a noncountable loop finite before safely delete it.)
494 // - If the loop also performs something else, it remains alive.
495 // Since it is transformed to countable form, it can be aggressively
496 // optimized by some optimizations which are in general not applicable
497 // to a noncountable loop.
499 // After this step, this loop (conceptually) would look like following:
500 // newcnt = __builtin_ctpop(x);
503 // do { cnt++; x &= x-1; t--) } while (t > 0);
504 BasicBlock *Body = *(CurLoop->block_begin());
506 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
507 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
508 Type *Ty = TripCnt->getType();
510 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
512 Builder.SetInsertPoint(LbCond);
513 Value *Opnd1 = cast<Value>(TcPhi);
514 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
515 Instruction *TcDec = cast<Instruction>(
516 Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
518 TcPhi->addIncoming(TripCnt, PreHead);
519 TcPhi->addIncoming(TcDec, Body);
521 CmpInst::Predicate Pred =
522 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
523 LbCond->setPredicate(Pred);
524 LbCond->setOperand(0, TcDec);
525 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
528 // Step 4: All the references to the original population counter outside
529 // the loop are replaced with the NewCount -- the value returned from
530 // __builtin_ctpop().
531 CntInst->replaceUsesOutsideBlock(NewCount, Body);
533 // step 5: Forget the "non-computable" trip-count SCEV associated with the
534 // loop. The loop would otherwise not be deleted even if it becomes empty.
535 SE->forgetLoop(CurLoop);
538 CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
539 Value *Val, DebugLoc DL) {
540 Value *Ops[] = {Val};
541 Type *Tys[] = {Val->getType()};
543 Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
544 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
545 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
551 /// recognize - detect population count idiom in a non-countable loop. If
552 /// detected, transform the relevant code to popcount intrinsic function
553 /// call, and return true; otherwise, return false.
554 bool NclPopcountRecognize::recognize() {
556 if (!LIR.getTargetTransformInfo())
559 LIR.getScalarEvolution();
561 if (!preliminaryScreen())
564 Instruction *CntInst;
567 if (!detectIdiom(CntInst, CntPhi, Val))
570 transform(CntInst, CntPhi, Val);
574 //===----------------------------------------------------------------------===//
576 // Implementation of LoopIdiomRecognize
578 //===----------------------------------------------------------------------===//
580 bool LoopIdiomRecognize::runOnCountableLoop() {
581 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
582 assert(!isa<SCEVCouldNotCompute>(BECount) &&
583 "runOnCountableLoop() called on a loop without a predictable"
584 "backedge-taken count");
586 // If this loop executes exactly one time, then it should be peeled, not
587 // optimized by this pass.
588 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
589 if (BECst->getValue()->getValue() == 0)
593 (void)getDominatorTree();
595 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
596 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
599 (void)getTargetLibraryInfo();
601 SmallVector<BasicBlock *, 8> ExitBlocks;
602 CurLoop->getUniqueExitBlocks(ExitBlocks);
604 DEBUG(dbgs() << "loop-idiom Scanning: F["
605 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
606 << CurLoop->getHeader()->getName() << "\n");
608 bool MadeChange = false;
609 // Scan all the blocks in the loop that are not in subloops.
610 for (auto *BB : CurLoop->getBlocks()) {
611 // Ignore blocks in subloops.
612 if (LI.getLoopFor(BB) != CurLoop)
615 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
620 bool LoopIdiomRecognize::runOnNoncountableLoop() {
621 NclPopcountRecognize Popcount(*this);
622 if (Popcount.recognize())
628 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
629 if (skipOptnoneFunction(L))
634 // If the loop could not be converted to canonical form, it must have an
635 // indirectbr in it, just give up.
636 if (!L->getLoopPreheader())
639 // Disable loop idiom recognition if the function's name is a common idiom.
640 StringRef Name = L->getHeader()->getParent()->getName();
641 if (Name == "memset" || Name == "memcpy")
644 SE = &getAnalysis<ScalarEvolution>();
645 if (SE->hasLoopInvariantBackedgeTakenCount(L))
646 return runOnCountableLoop();
647 return runOnNoncountableLoop();
650 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
651 /// with the specified backedge count. This block is known to be in the current
652 /// loop and not in any subloops.
653 bool LoopIdiomRecognize::runOnLoopBlock(
654 BasicBlock *BB, const SCEV *BECount,
655 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
656 // We can only promote stores in this block if they are unconditionally
657 // executed in the loop. For a block to be unconditionally executed, it has
658 // to dominate all the exit blocks of the loop. Verify this now.
659 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
660 if (!DT->dominates(BB, ExitBlocks[i]))
663 bool MadeChange = false;
664 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
665 Instruction *Inst = I++;
666 // Look for store instructions, which may be optimized to memset/memcpy.
667 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
669 if (!processLoopStore(SI, BECount))
673 // If processing the store invalidated our iterator, start over from the
680 // Look for memset instructions, which may be optimized to a larger memset.
681 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
683 if (!processLoopMemSet(MSI, BECount))
687 // If processing the memset invalidated our iterator, start over from the
698 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
699 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
703 Value *StoredVal = SI->getValueOperand();
704 Value *StorePtr = SI->getPointerOperand();
706 // Reject stores that are so large that they overflow an unsigned.
707 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
708 uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
709 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
712 // See if the pointer expression is an AddRec like {base,+,1} on the current
713 // loop, which indicates a strided store. If we have something else, it's a
714 // random store we can't handle.
715 const SCEVAddRecExpr *StoreEv =
716 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
717 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
720 // Check to see if the stride matches the size of the store. If so, then we
721 // know that every byte is touched in the loop.
722 unsigned StoreSize = (unsigned)SizeInBits >> 3;
723 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
725 if (!Stride || StoreSize != Stride->getValue()->getValue()) {
726 // TODO: Could also handle negative stride here someday, that will require
727 // the validity check in mayLoopAccessLocation to be updated though.
728 // Enable this to print exact negative strides.
729 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
730 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
731 dbgs() << "BB: " << *SI->getParent();
737 // See if we can optimize just this store in isolation.
738 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
739 StoredVal, SI, StoreEv, BECount))
742 // If the stored value is a strided load in the same loop with the same stride
743 // this this may be transformable into a memcpy. This kicks in for stuff like
744 // for (i) A[i] = B[i];
745 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
746 const SCEVAddRecExpr *LoadEv =
747 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
748 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
749 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
750 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
753 // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
758 /// processLoopMemSet - See if this memset can be promoted to a large memset.
759 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
760 const SCEV *BECount) {
761 // We can only handle non-volatile memsets with a constant size.
762 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
765 // If we're not allowed to hack on memset, we fail.
766 if (!TLI->has(LibFunc::memset))
769 Value *Pointer = MSI->getDest();
771 // See if the pointer expression is an AddRec like {base,+,1} on the current
772 // loop, which indicates a strided store. If we have something else, it's a
773 // random store we can't handle.
774 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
775 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
778 // Reject memsets that are so large that they overflow an unsigned.
779 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
780 if ((SizeInBytes >> 32) != 0)
783 // Check to see if the stride matches the size of the memset. If so, then we
784 // know that every byte is touched in the loop.
785 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
787 // TODO: Could also handle negative stride here someday, that will require the
788 // validity check in mayLoopAccessLocation to be updated though.
789 if (!Stride || MSI->getLength() != Stride->getValue())
792 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
793 MSI->getAlignment(), MSI->getValue(), MSI, Ev,
797 /// mayLoopAccessLocation - Return true if the specified loop might access the
798 /// specified pointer location, which is a loop-strided access. The 'Access'
799 /// argument specifies what the verboten forms of access are (read or write).
800 static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
801 const SCEV *BECount, unsigned StoreSize,
803 Instruction *IgnoredStore) {
804 // Get the location that may be stored across the loop. Since the access is
805 // strided positively through memory, we say that the modified location starts
806 // at the pointer and has infinite size.
807 uint64_t AccessSize = MemoryLocation::UnknownSize;
809 // If the loop iterates a fixed number of times, we can refine the access size
810 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
811 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
812 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
814 // TODO: For this to be really effective, we have to dive into the pointer
815 // operand in the store. Store to &A[i] of 100 will always return may alias
816 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
817 // which will then no-alias a store to &A[100].
818 MemoryLocation StoreLoc(Ptr, AccessSize);
820 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
822 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
823 if (&*I != IgnoredStore && (AA.getModRefInfo(I, StoreLoc) & Access))
829 /// getMemSetPatternValue - If a strided store of the specified value is safe to
830 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
831 /// be passed in. Otherwise, return null.
833 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
834 /// just replicate their input array and then pass on to memset_pattern16.
835 static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
836 // If the value isn't a constant, we can't promote it to being in a constant
837 // array. We could theoretically do a store to an alloca or something, but
838 // that doesn't seem worthwhile.
839 Constant *C = dyn_cast<Constant>(V);
843 // Only handle simple values that are a power of two bytes in size.
844 uint64_t Size = DL.getTypeSizeInBits(V->getType());
845 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
848 // Don't care enough about darwin/ppc to implement this.
849 if (DL.isBigEndian())
852 // Convert to size in bytes.
855 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
856 // if the top and bottom are the same (e.g. for vectors and large integers).
860 // If the constant is exactly 16 bytes, just use it.
864 // Otherwise, we'll use an array of the constants.
865 unsigned ArraySize = 16 / Size;
866 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
867 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
870 /// processLoopStridedStore - We see a strided store of some value. If we can
871 /// transform this into a memset or memset_pattern in the loop preheader, do so.
872 bool LoopIdiomRecognize::processLoopStridedStore(
873 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
874 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
875 const SCEV *BECount) {
877 // If the stored value is a byte-wise value (like i32 -1), then it may be
878 // turned into a memset of i8 -1, assuming that all the consecutive bytes
879 // are stored. A store of i32 0x01020304 can never be turned into a memset,
880 // but it can be turned into memset_pattern if the target supports it.
881 Value *SplatValue = isBytewiseValue(StoredVal);
882 Constant *PatternValue = nullptr;
883 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
884 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
886 // If we're allowed to form a memset, and the stored value would be acceptable
887 // for memset, use it.
888 if (SplatValue && TLI->has(LibFunc::memset) &&
889 // Verify that the stored value is loop invariant. If not, we can't
890 // promote the memset.
891 CurLoop->isLoopInvariant(SplatValue)) {
892 // Keep and use SplatValue.
893 PatternValue = nullptr;
894 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
895 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
896 // Don't create memset_pattern16s with address spaces.
897 // It looks like we can use PatternValue!
898 SplatValue = nullptr;
900 // Otherwise, this isn't an idiom we can transform. For example, we can't
901 // do anything with a 3-byte store.
905 // The trip count of the loop and the base pointer of the addrec SCEV is
906 // guaranteed to be loop invariant, which means that it should dominate the
907 // header. This allows us to insert code for it in the preheader.
908 BasicBlock *Preheader = CurLoop->getLoopPreheader();
909 IRBuilder<> Builder(Preheader->getTerminator());
910 SCEVExpander Expander(*SE, DL, "loop-idiom");
912 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
914 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
915 // this into a memset in the loop preheader now if we want. However, this
916 // would be unsafe to do if there is anything else in the loop that may read
917 // or write to the aliased location. Check for any overlap by generating the
918 // base pointer and checking the region.
919 Value *BasePtr = Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
920 Preheader->getTerminator());
922 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
923 getAnalysis<AliasAnalysis>(), TheStore)) {
925 // If we generated new code for the base pointer, clean up.
926 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
930 // Okay, everything looks good, insert the memset.
932 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
933 // pointer size if it isn't already.
934 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
935 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
937 const SCEV *NumBytesS =
938 SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), SCEV::FlagNUW);
939 if (StoreSize != 1) {
940 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
945 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
950 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
952 // Everything is emitted in default address space
953 Type *Int8PtrTy = DestInt8PtrTy;
955 Module *M = TheStore->getParent()->getParent()->getParent();
957 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
958 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
960 // Otherwise we should form a memset_pattern16. PatternValue is known to be
961 // an constant array of 16-bytes. Plop the value into a mergable global.
962 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
963 GlobalValue::PrivateLinkage,
964 PatternValue, ".memset_pattern");
965 GV->setUnnamedAddr(true); // Ok to merge these.
966 GV->setAlignment(16);
967 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
968 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
971 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
972 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
973 NewCall->setDebugLoc(TheStore->getDebugLoc());
975 // Okay, the memset has been formed. Zap the original store and anything that
977 deleteDeadInstruction(TheStore, TLI);
982 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
983 /// same-strided load.
984 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
985 StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
986 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
987 // If we're not allowed to form memcpy, we fail.
988 if (!TLI->has(LibFunc::memcpy))
991 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
993 // The trip count of the loop and the base pointer of the addrec SCEV is
994 // guaranteed to be loop invariant, which means that it should dominate the
995 // header. This allows us to insert code for it in the preheader.
996 BasicBlock *Preheader = CurLoop->getLoopPreheader();
997 IRBuilder<> Builder(Preheader->getTerminator());
998 const DataLayout &DL = Preheader->getModule()->getDataLayout();
999 SCEVExpander Expander(*SE, DL, "loop-idiom");
1001 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
1002 // this into a memcpy in the loop preheader now if we want. However, this
1003 // would be unsafe to do if there is anything else in the loop that may read
1004 // or write the memory region we're storing to. This includes the load that
1005 // feeds the stores. Check for an alias by generating the base address and
1006 // checking everything.
1007 Value *StoreBasePtr = Expander.expandCodeFor(
1008 StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1009 Preheader->getTerminator());
1011 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
1012 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1014 // If we generated new code for the base pointer, clean up.
1015 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
1019 // For a memcpy, we have to make sure that the input array is not being
1020 // mutated by the loop.
1021 Value *LoadBasePtr = Expander.expandCodeFor(
1022 LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1023 Preheader->getTerminator());
1025 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
1026 getAnalysis<AliasAnalysis>(), SI)) {
1028 // If we generated new code for the base pointer, clean up.
1029 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1030 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
1034 // Okay, everything is safe, we can transform this!
1036 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
1037 // pointer size if it isn't already.
1038 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
1039 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
1041 const SCEV *NumBytesS =
1042 SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1), SCEV::FlagNUW);
1044 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
1048 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1051 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1052 std::min(SI->getAlignment(), LI->getAlignment()));
1053 NewCall->setDebugLoc(SI->getDebugLoc());
1055 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
1056 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1057 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
1059 // Okay, the memset has been formed. Zap the original store and anything that
1061 deleteDeadInstruction(SI, TLI);