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 : public LoopPass {
74 TargetLibraryInfo *TLI;
75 const TargetTransformInfo *TTI;
79 explicit LoopIdiomRecognize() : LoopPass(ID) {
80 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
87 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
89 /// This transformation requires natural loop information & requires that
90 /// loop preheaders be inserted into the CFG.
92 void getAnalysisUsage(AnalysisUsage &AU) const override {
93 AU.addRequired<LoopInfoWrapperPass>();
94 AU.addPreserved<LoopInfoWrapperPass>();
95 AU.addRequiredID(LoopSimplifyID);
96 AU.addPreservedID(LoopSimplifyID);
97 AU.addRequiredID(LCSSAID);
98 AU.addPreservedID(LCSSAID);
99 AU.addRequired<AliasAnalysis>();
100 AU.addPreserved<AliasAnalysis>();
101 AU.addRequired<ScalarEvolution>();
102 AU.addPreserved<ScalarEvolution>();
103 AU.addPreserved<DominatorTreeWrapperPass>();
104 AU.addRequired<DominatorTreeWrapperPass>();
105 AU.addRequired<TargetLibraryInfoWrapperPass>();
106 AU.addRequired<TargetTransformInfoWrapperPass>();
109 DominatorTree *getDominatorTree() {
111 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
114 ScalarEvolution *getScalarEvolution() {
115 return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
118 TargetLibraryInfo *getTargetLibraryInfo() {
120 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
125 const TargetTransformInfo *getTargetTransformInfo() {
127 : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
128 *CurLoop->getHeader()->getParent()));
131 Loop *getLoop() const { return CurLoop; }
134 /// \name Countable Loop Idiom Handling
137 bool runOnCountableLoop();
138 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
139 SmallVectorImpl<BasicBlock *> &ExitBlocks);
141 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
142 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
144 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
145 unsigned StoreAlignment, Value *SplatValue,
146 Instruction *TheStore, const SCEVAddRecExpr *Ev,
147 const SCEV *BECount);
148 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
149 const SCEVAddRecExpr *StoreEv,
150 const SCEVAddRecExpr *LoadEv,
151 const SCEV *BECount);
154 /// \name Noncountable Loop Idiom Handling
157 bool runOnNoncountableLoop();
159 bool recognizePopcount();
160 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
161 PHINode *CntPhi, Value *Var);
166 } // End anonymous namespace.
168 char LoopIdiomRecognize::ID = 0;
169 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
171 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
172 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
173 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
174 INITIALIZE_PASS_DEPENDENCY(LCSSA)
175 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
176 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
177 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
178 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
179 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
182 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
184 /// deleteDeadInstruction - Delete this instruction. Before we do, go through
185 /// and zero out all the operands of this instruction. If any of them become
186 /// dead, delete them and the computation tree that feeds them.
188 static void deleteDeadInstruction(Instruction *I,
189 const TargetLibraryInfo *TLI) {
190 SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
191 I->replaceAllUsesWith(UndefValue::get(I->getType()));
192 I->eraseFromParent();
193 for (Value *Op : Operands)
194 RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
197 //===----------------------------------------------------------------------===//
199 // Implementation of LoopIdiomRecognize
201 //===----------------------------------------------------------------------===//
203 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
204 if (skipOptnoneFunction(L))
209 // If the loop could not be converted to canonical form, it must have an
210 // indirectbr in it, just give up.
211 if (!L->getLoopPreheader())
214 // Disable loop idiom recognition if the function's name is a common idiom.
215 StringRef Name = L->getHeader()->getParent()->getName();
216 if (Name == "memset" || Name == "memcpy")
219 SE = &getAnalysis<ScalarEvolution>();
220 if (SE->hasLoopInvariantBackedgeTakenCount(L))
221 return runOnCountableLoop();
222 return runOnNoncountableLoop();
225 bool LoopIdiomRecognize::runOnCountableLoop() {
226 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
227 assert(!isa<SCEVCouldNotCompute>(BECount) &&
228 "runOnCountableLoop() called on a loop without a predictable"
229 "backedge-taken count");
231 // If this loop executes exactly one time, then it should be peeled, not
232 // optimized by this pass.
233 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
234 if (BECst->getValue()->getValue() == 0)
238 (void)getDominatorTree();
240 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
241 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
244 (void)getTargetLibraryInfo();
246 SmallVector<BasicBlock *, 8> ExitBlocks;
247 CurLoop->getUniqueExitBlocks(ExitBlocks);
249 DEBUG(dbgs() << "loop-idiom Scanning: F["
250 << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
251 << CurLoop->getHeader()->getName() << "\n");
253 bool MadeChange = false;
254 // Scan all the blocks in the loop that are not in subloops.
255 for (auto *BB : CurLoop->getBlocks()) {
256 // Ignore blocks in subloops.
257 if (LI.getLoopFor(BB) != CurLoop)
260 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
265 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
266 /// with the specified backedge count. This block is known to be in the current
267 /// loop and not in any subloops.
268 bool LoopIdiomRecognize::runOnLoopBlock(
269 BasicBlock *BB, const SCEV *BECount,
270 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
271 // We can only promote stores in this block if they are unconditionally
272 // executed in the loop. For a block to be unconditionally executed, it has
273 // to dominate all the exit blocks of the loop. Verify this now.
274 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
275 if (!DT->dominates(BB, ExitBlocks[i]))
278 bool MadeChange = false;
279 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
280 Instruction *Inst = I++;
281 // Look for store instructions, which may be optimized to memset/memcpy.
282 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
284 if (!processLoopStore(SI, BECount))
288 // If processing the store invalidated our iterator, start over from the
295 // Look for memset instructions, which may be optimized to a larger memset.
296 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
298 if (!processLoopMemSet(MSI, BECount))
302 // If processing the memset invalidated our iterator, start over from the
313 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
314 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
318 Value *StoredVal = SI->getValueOperand();
319 Value *StorePtr = SI->getPointerOperand();
321 // Reject stores that are so large that they overflow an unsigned.
322 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
323 uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
324 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
327 // See if the pointer expression is an AddRec like {base,+,1} on the current
328 // loop, which indicates a strided store. If we have something else, it's a
329 // random store we can't handle.
330 const SCEVAddRecExpr *StoreEv =
331 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
332 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
335 // Check to see if the stride matches the size of the store. If so, then we
336 // know that every byte is touched in the loop.
337 unsigned StoreSize = (unsigned)SizeInBits >> 3;
338 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
340 if (!Stride || StoreSize != Stride->getValue()->getValue()) {
341 // TODO: Could also handle negative stride here someday, that will require
342 // the validity check in mayLoopAccessLocation to be updated though.
343 // Enable this to print exact negative strides.
344 if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
345 dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
346 dbgs() << "BB: " << *SI->getParent();
352 // See if we can optimize just this store in isolation.
353 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
354 StoredVal, SI, StoreEv, BECount))
357 // If the stored value is a strided load in the same loop with the same stride
358 // this this may be transformable into a memcpy. This kicks in for stuff like
359 // for (i) A[i] = B[i];
360 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
361 const SCEVAddRecExpr *LoadEv =
362 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
363 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
364 StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
365 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
368 // errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
373 /// processLoopMemSet - See if this memset can be promoted to a large memset.
374 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
375 const SCEV *BECount) {
376 // We can only handle non-volatile memsets with a constant size.
377 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
380 // If we're not allowed to hack on memset, we fail.
381 if (!TLI->has(LibFunc::memset))
384 Value *Pointer = MSI->getDest();
386 // See if the pointer expression is an AddRec like {base,+,1} on the current
387 // loop, which indicates a strided store. If we have something else, it's a
388 // random store we can't handle.
389 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
390 if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
393 // Reject memsets that are so large that they overflow an unsigned.
394 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
395 if ((SizeInBytes >> 32) != 0)
398 // Check to see if the stride matches the size of the memset. If so, then we
399 // know that every byte is touched in the loop.
400 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
402 // TODO: Could also handle negative stride here someday, that will require the
403 // validity check in mayLoopAccessLocation to be updated though.
404 if (!Stride || MSI->getLength() != Stride->getValue())
407 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
408 MSI->getAlignment(), MSI->getValue(), MSI, Ev,
412 /// mayLoopAccessLocation - Return true if the specified loop might access the
413 /// specified pointer location, which is a loop-strided access. The 'Access'
414 /// argument specifies what the verboten forms of access are (read or write).
415 static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
416 const SCEV *BECount, unsigned StoreSize,
418 Instruction *IgnoredStore) {
419 // Get the location that may be stored across the loop. Since the access is
420 // strided positively through memory, we say that the modified location starts
421 // at the pointer and has infinite size.
422 uint64_t AccessSize = MemoryLocation::UnknownSize;
424 // If the loop iterates a fixed number of times, we can refine the access size
425 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
426 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
427 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
429 // TODO: For this to be really effective, we have to dive into the pointer
430 // operand in the store. Store to &A[i] of 100 will always return may alias
431 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
432 // which will then no-alias a store to &A[100].
433 MemoryLocation StoreLoc(Ptr, AccessSize);
435 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
437 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
438 if (&*I != IgnoredStore && (AA.getModRefInfo(I, StoreLoc) & Access))
444 /// getMemSetPatternValue - If a strided store of the specified value is safe to
445 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
446 /// be passed in. Otherwise, return null.
448 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
449 /// just replicate their input array and then pass on to memset_pattern16.
450 static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
451 // If the value isn't a constant, we can't promote it to being in a constant
452 // array. We could theoretically do a store to an alloca or something, but
453 // that doesn't seem worthwhile.
454 Constant *C = dyn_cast<Constant>(V);
458 // Only handle simple values that are a power of two bytes in size.
459 uint64_t Size = DL.getTypeSizeInBits(V->getType());
460 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
463 // Don't care enough about darwin/ppc to implement this.
464 if (DL.isBigEndian())
467 // Convert to size in bytes.
470 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
471 // if the top and bottom are the same (e.g. for vectors and large integers).
475 // If the constant is exactly 16 bytes, just use it.
479 // Otherwise, we'll use an array of the constants.
480 unsigned ArraySize = 16 / Size;
481 ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
482 return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
485 /// processLoopStridedStore - We see a strided store of some value. If we can
486 /// transform this into a memset or memset_pattern in the loop preheader, do so.
487 bool LoopIdiomRecognize::processLoopStridedStore(
488 Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
489 Value *StoredVal, Instruction *TheStore, const SCEVAddRecExpr *Ev,
490 const SCEV *BECount) {
492 // If the stored value is a byte-wise value (like i32 -1), then it may be
493 // turned into a memset of i8 -1, assuming that all the consecutive bytes
494 // are stored. A store of i32 0x01020304 can never be turned into a memset,
495 // but it can be turned into memset_pattern if the target supports it.
496 Value *SplatValue = isBytewiseValue(StoredVal);
497 Constant *PatternValue = nullptr;
498 auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
499 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
501 // If we're allowed to form a memset, and the stored value would be acceptable
502 // for memset, use it.
503 if (SplatValue && TLI->has(LibFunc::memset) &&
504 // Verify that the stored value is loop invariant. If not, we can't
505 // promote the memset.
506 CurLoop->isLoopInvariant(SplatValue)) {
507 // Keep and use SplatValue.
508 PatternValue = nullptr;
509 } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
510 (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
511 // Don't create memset_pattern16s with address spaces.
512 // It looks like we can use PatternValue!
513 SplatValue = nullptr;
515 // Otherwise, this isn't an idiom we can transform. For example, we can't
516 // do anything with a 3-byte store.
520 // The trip count of the loop and the base pointer of the addrec SCEV is
521 // guaranteed to be loop invariant, which means that it should dominate the
522 // header. This allows us to insert code for it in the preheader.
523 BasicBlock *Preheader = CurLoop->getLoopPreheader();
524 IRBuilder<> Builder(Preheader->getTerminator());
525 SCEVExpander Expander(*SE, DL, "loop-idiom");
527 Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
529 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
530 // this into a memset in the loop preheader now if we want. However, this
531 // would be unsafe to do if there is anything else in the loop that may read
532 // or write to the aliased location. Check for any overlap by generating the
533 // base pointer and checking the region.
534 Value *BasePtr = Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
535 Preheader->getTerminator());
537 if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
538 getAnalysis<AliasAnalysis>(), TheStore)) {
540 // If we generated new code for the base pointer, clean up.
541 RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
545 // Okay, everything looks good, insert the memset.
547 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
548 // pointer size if it isn't already.
549 Type *IntPtr = Builder.getIntPtrTy(DL, DestAS);
550 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
552 const SCEV *NumBytesS =
553 SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), SCEV::FlagNUW);
554 if (StoreSize != 1) {
555 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
560 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
565 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
567 // Everything is emitted in default address space
568 Type *Int8PtrTy = DestInt8PtrTy;
570 Module *M = TheStore->getParent()->getParent()->getParent();
572 M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
573 Int8PtrTy, Int8PtrTy, IntPtr, (void *)nullptr);
575 // Otherwise we should form a memset_pattern16. PatternValue is known to be
576 // an constant array of 16-bytes. Plop the value into a mergable global.
577 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
578 GlobalValue::PrivateLinkage,
579 PatternValue, ".memset_pattern");
580 GV->setUnnamedAddr(true); // Ok to merge these.
581 GV->setAlignment(16);
582 Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
583 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
586 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
587 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
588 NewCall->setDebugLoc(TheStore->getDebugLoc());
590 // Okay, the memset has been formed. Zap the original store and anything that
592 deleteDeadInstruction(TheStore, TLI);
597 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
598 /// same-strided load.
599 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
600 StoreInst *SI, unsigned StoreSize, const SCEVAddRecExpr *StoreEv,
601 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
602 // If we're not allowed to form memcpy, we fail.
603 if (!TLI->has(LibFunc::memcpy))
606 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
608 // The trip count of the loop and the base pointer of the addrec SCEV is
609 // guaranteed to be loop invariant, which means that it should dominate the
610 // header. This allows us to insert code for it in the preheader.
611 BasicBlock *Preheader = CurLoop->getLoopPreheader();
612 IRBuilder<> Builder(Preheader->getTerminator());
613 const DataLayout &DL = Preheader->getModule()->getDataLayout();
614 SCEVExpander Expander(*SE, DL, "loop-idiom");
616 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
617 // this into a memcpy in the loop preheader now if we want. However, this
618 // would be unsafe to do if there is anything else in the loop that may read
619 // or write the memory region we're storing to. This includes the load that
620 // feeds the stores. Check for an alias by generating the base address and
621 // checking everything.
622 Value *StoreBasePtr = Expander.expandCodeFor(
623 StoreEv->getStart(), Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
624 Preheader->getTerminator());
626 if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
627 StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
629 // If we generated new code for the base pointer, clean up.
630 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
634 // For a memcpy, we have to make sure that the input array is not being
635 // mutated by the loop.
636 Value *LoadBasePtr = Expander.expandCodeFor(
637 LoadEv->getStart(), Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
638 Preheader->getTerminator());
640 if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
641 getAnalysis<AliasAnalysis>(), SI)) {
643 // If we generated new code for the base pointer, clean up.
644 RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
645 RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
649 // Okay, everything is safe, we can transform this!
651 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
652 // pointer size if it isn't already.
653 Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace());
654 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
656 const SCEV *NumBytesS =
657 SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1), SCEV::FlagNUW);
659 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
663 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
666 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
667 std::min(SI->getAlignment(), LI->getAlignment()));
668 NewCall->setDebugLoc(SI->getDebugLoc());
670 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
671 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
672 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
674 // Okay, the memset has been formed. Zap the original store and anything that
676 deleteDeadInstruction(SI, TLI);
681 bool LoopIdiomRecognize::runOnNoncountableLoop() {
682 if (recognizePopcount())
688 /// Check if the given conditional branch is based on the comparison between
689 /// a variable and zero, and if the variable is non-zero, the control yields to
690 /// the loop entry. If the branch matches the behavior, the variable involved
691 /// in the comparion is returned. This function will be called to see if the
692 /// precondition and postcondition of the loop are in desirable form.
693 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
694 if (!BI || !BI->isConditional())
697 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
701 ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
702 if (!CmpZero || !CmpZero->isZero())
705 ICmpInst::Predicate Pred = Cond->getPredicate();
706 if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
707 (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
708 return Cond->getOperand(0);
713 /// Return true iff the idiom is detected in the loop.
716 /// 1) \p CntInst is set to the instruction counting the population bit.
717 /// 2) \p CntPhi is set to the corresponding phi node.
718 /// 3) \p Var is set to the value whose population bits are being counted.
720 /// The core idiom we are trying to detect is:
723 /// goto loop-exit // the precondition of the loop
726 /// x1 = phi (x0, x2);
727 /// cnt1 = phi(cnt0, cnt2);
731 /// x2 = x1 & (x1 - 1);
737 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
738 Instruction *&CntInst, PHINode *&CntPhi,
740 // step 1: Check to see if the look-back branch match this pattern:
741 // "if (a!=0) goto loop-entry".
742 BasicBlock *LoopEntry;
743 Instruction *DefX2, *CountInst;
744 Value *VarX1, *VarX0;
745 PHINode *PhiX, *CountPhi;
747 DefX2 = CountInst = nullptr;
748 VarX1 = VarX0 = nullptr;
749 PhiX = CountPhi = nullptr;
750 LoopEntry = *(CurLoop->block_begin());
752 // step 1: Check if the loop-back branch is in desirable form.
754 if (Value *T = matchCondition(
755 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
756 DefX2 = dyn_cast<Instruction>(T);
761 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
763 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
766 BinaryOperator *SubOneOp;
768 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
769 VarX1 = DefX2->getOperand(1);
771 VarX1 = DefX2->getOperand(0);
772 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
777 Instruction *SubInst = cast<Instruction>(SubOneOp);
778 ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
780 !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
781 (SubInst->getOpcode() == Instruction::Add &&
782 Dec->isAllOnesValue()))) {
787 // step 3: Check the recurrence of variable X
789 PhiX = dyn_cast<PHINode>(VarX1);
791 (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
796 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
799 for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
800 IterE = LoopEntry->end();
801 Iter != IterE; Iter++) {
802 Instruction *Inst = Iter;
803 if (Inst->getOpcode() != Instruction::Add)
806 ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
807 if (!Inc || !Inc->isOne())
810 PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
811 if (!Phi || Phi->getParent() != LoopEntry)
814 // Check if the result of the instruction is live of the loop.
815 bool LiveOutLoop = false;
816 for (User *U : Inst->users()) {
817 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
834 // step 5: check if the precondition is in this form:
835 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
837 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
838 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
839 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
850 /// Recognizes a population count idiom in a non-countable loop.
852 /// If detected, transforms the relevant code to issue the popcount intrinsic
853 /// function call, and returns true; otherwise, returns false.
854 bool LoopIdiomRecognize::recognizePopcount() {
855 (void)getScalarEvolution();
856 (void)getTargetLibraryInfo();
857 (void)getTargetTransformInfo();
859 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
862 // Counting population are usually conducted by few arithmetic instructions.
863 // Such instructions can be easilly "absorbed" by vacant slots in a
864 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
865 // in a compact loop.
867 // Give up if the loop has multiple blocks or multiple backedges.
868 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
871 BasicBlock *LoopBody = *(CurLoop->block_begin());
872 if (LoopBody->size() >= 20) {
873 // The loop is too big, bail out.
877 // It should have a preheader containing nothing but an unconditional branch.
878 BasicBlock *PH = CurLoop->getLoopPreheader();
881 if (&PH->front() != PH->getTerminator())
883 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
884 if (!EntryBI || EntryBI->isConditional())
887 // It should have a precondition block where the generated popcount instrinsic
888 // function can be inserted.
889 auto *PreCondBB = PH->getSinglePredecessor();
892 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
893 if (!PreCondBI || PreCondBI->isUnconditional())
896 Instruction *CntInst;
899 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
902 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
906 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
908 Value *Ops[] = {Val};
909 Type *Tys[] = {Val->getType()};
911 Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
912 Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
913 CallInst *CI = IRBuilder.CreateCall(Func, Ops);
919 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
920 Instruction *CntInst,
921 PHINode *CntPhi, Value *Var) {
922 BasicBlock *PreHead = CurLoop->getLoopPreheader();
923 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
924 const DebugLoc DL = CntInst->getDebugLoc();
926 // Assuming before transformation, the loop is following:
927 // if (x) // the precondition
928 // do { cnt++; x &= x - 1; } while(x);
930 // Step 1: Insert the ctpop instruction at the end of the precondition block
931 IRBuilder<> Builder(PreCondBr);
932 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
934 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
935 NewCount = PopCntZext =
936 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
938 if (NewCount != PopCnt)
939 (cast<Instruction>(NewCount))->setDebugLoc(DL);
941 // TripCnt is exactly the number of iterations the loop has
944 // If the population counter's initial value is not zero, insert Add Inst.
945 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
946 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
947 if (!InitConst || !InitConst->isZero()) {
948 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
949 (cast<Instruction>(NewCount))->setDebugLoc(DL);
953 // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
954 // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
955 // function would be partial dead code, and downstream passes will drag
956 // it back from the precondition block to the preheader.
958 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
960 Value *Opnd0 = PopCntZext;
961 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
962 if (PreCond->getOperand(0) != Var)
963 std::swap(Opnd0, Opnd1);
965 ICmpInst *NewPreCond = cast<ICmpInst>(
966 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
967 PreCondBr->setCondition(NewPreCond);
969 RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
972 // Step 3: Note that the population count is exactly the trip count of the
973 // loop in question, which enble us to to convert the loop from noncountable
974 // loop into a countable one. The benefit is twofold:
976 // - If the loop only counts population, the entire loop become dead after
977 // the transformation. It is lots easier to prove a countable loop dead
978 // than to prove a noncountable one. (In some C dialects, a infite loop
979 // isn't dead even if it computes nothing useful. In general, DCE needs
980 // to prove a noncountable loop finite before safely delete it.)
982 // - If the loop also performs something else, it remains alive.
983 // Since it is transformed to countable form, it can be aggressively
984 // optimized by some optimizations which are in general not applicable
985 // to a noncountable loop.
987 // After this step, this loop (conceptually) would look like following:
988 // newcnt = __builtin_ctpop(x);
991 // do { cnt++; x &= x-1; t--) } while (t > 0);
992 BasicBlock *Body = *(CurLoop->block_begin());
994 auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
995 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
996 Type *Ty = TripCnt->getType();
998 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
1000 Builder.SetInsertPoint(LbCond);
1001 Value *Opnd1 = cast<Value>(TcPhi);
1002 Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
1003 Instruction *TcDec = cast<Instruction>(
1004 Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
1006 TcPhi->addIncoming(TripCnt, PreHead);
1007 TcPhi->addIncoming(TcDec, Body);
1009 CmpInst::Predicate Pred =
1010 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1011 LbCond->setPredicate(Pred);
1012 LbCond->setOperand(0, TcDec);
1013 LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
1016 // Step 4: All the references to the original population counter outside
1017 // the loop are replaced with the NewCount -- the value returned from
1018 // __builtin_ctpop().
1019 CntInst->replaceUsesOutsideBlock(NewCount, Body);
1021 // step 5: Forget the "non-computable" trip-count SCEV associated with the
1022 // loop. The loop would otherwise not be deleted even if it becomes empty.
1023 SE->forgetLoop(CurLoop);