LLVM 22.0.0git
LoopIdiomRecognize.cpp
Go to the documentation of this file.
1//===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements an idiom recognizer that transforms simple loops into a
10// non-loop form. In cases that this kicks in, it can be a significant
11// performance win.
12//
13// If compiling for code size we avoid idiom recognition if the resulting
14// code could be larger than the code for the original loop. One way this could
15// happen is if the loop is not removable after idiom recognition due to the
16// presence of non-idiom instructions. The initial implementation of the
17// heuristics applies to idioms in multi-block loops.
18//
19//===----------------------------------------------------------------------===//
20//
21// TODO List:
22//
23// Future loop memory idioms to recognize: memcmp, etc.
24//
25// This could recognize common matrix multiplies and dot product idioms and
26// replace them with calls to BLAS (if linked in??).
27//
28//===----------------------------------------------------------------------===//
29
31#include "llvm/ADT/APInt.h"
32#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/MapVector.h"
35#include "llvm/ADT/SetVector.h"
38#include "llvm/ADT/Statistic.h"
39#include "llvm/ADT/StringRef.h"
56#include "llvm/IR/BasicBlock.h"
57#include "llvm/IR/Constant.h"
58#include "llvm/IR/Constants.h"
59#include "llvm/IR/DataLayout.h"
60#include "llvm/IR/DebugLoc.h"
62#include "llvm/IR/Dominators.h"
63#include "llvm/IR/GlobalValue.h"
65#include "llvm/IR/IRBuilder.h"
66#include "llvm/IR/InstrTypes.h"
67#include "llvm/IR/Instruction.h"
70#include "llvm/IR/Intrinsics.h"
71#include "llvm/IR/LLVMContext.h"
72#include "llvm/IR/Module.h"
73#include "llvm/IR/PassManager.h"
75#include "llvm/IR/Type.h"
76#include "llvm/IR/User.h"
77#include "llvm/IR/Value.h"
78#include "llvm/IR/ValueHandle.h"
81#include "llvm/Support/Debug.h"
88#include <algorithm>
89#include <cassert>
90#include <cstdint>
91#include <utility>
92
93using namespace llvm;
94using namespace SCEVPatternMatch;
95
96#define DEBUG_TYPE "loop-idiom"
97
98STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
99STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
100STATISTIC(NumMemMove, "Number of memmove's formed from loop load+stores");
101STATISTIC(NumStrLen, "Number of strlen's and wcslen's formed from loop loads");
103 NumShiftUntilBitTest,
104 "Number of uncountable loops recognized as 'shift until bitttest' idiom");
105STATISTIC(NumShiftUntilZero,
106 "Number of uncountable loops recognized as 'shift until zero' idiom");
107
110 DisableLIRPAll("disable-" DEBUG_TYPE "-all",
111 cl::desc("Options to disable Loop Idiom Recognize Pass."),
114
117 DisableLIRPMemset("disable-" DEBUG_TYPE "-memset",
118 cl::desc("Proceed with loop idiom recognize pass, but do "
119 "not convert loop(s) to memset."),
122
125 DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy",
126 cl::desc("Proceed with loop idiom recognize pass, but do "
127 "not convert loop(s) to memcpy."),
130
133 DisableLIRPStrlen("disable-loop-idiom-strlen",
134 cl::desc("Proceed with loop idiom recognize pass, but do "
135 "not convert loop(s) to strlen."),
138
141 EnableLIRPWcslen("disable-loop-idiom-wcslen",
142 cl::desc("Proceed with loop idiom recognize pass, "
143 "enable conversion of loop(s) to wcslen."),
146
149 DisableLIRPHashRecognize("disable-" DEBUG_TYPE "-hashrecognize",
150 cl::desc("Proceed with loop idiom recognize pass, "
151 "but do not optimize CRC loops."),
153 cl::init(false), cl::ReallyHidden);
154
156 "use-lir-code-size-heurs",
157 cl::desc("Use loop idiom recognition code size heuristics when compiling "
158 "with -Os/-Oz"),
159 cl::init(true), cl::Hidden);
160
162 "loop-idiom-force-memset-pattern-intrinsic",
163 cl::desc("Use memset.pattern intrinsic whenever possible"), cl::init(false),
164 cl::Hidden);
165
166namespace {
167
168class LoopIdiomRecognize {
169 Loop *CurLoop = nullptr;
171 DominatorTree *DT;
172 LoopInfo *LI;
173 ScalarEvolution *SE;
176 const DataLayout *DL;
178 bool ApplyCodeSizeHeuristics;
179 std::unique_ptr<MemorySSAUpdater> MSSAU;
180
181public:
182 explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
183 LoopInfo *LI, ScalarEvolution *SE,
185 const TargetTransformInfo *TTI, MemorySSA *MSSA,
186 const DataLayout *DL,
188 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) {
189 if (MSSA)
190 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
191 }
192
193 bool runOnLoop(Loop *L);
194
195private:
196 using StoreList = SmallVector<StoreInst *, 8>;
197 using StoreListMap = MapVector<Value *, StoreList>;
198
199 StoreListMap StoreRefsForMemset;
200 StoreListMap StoreRefsForMemsetPattern;
201 StoreList StoreRefsForMemcpy;
202 bool HasMemset;
203 bool HasMemsetPattern;
204 bool HasMemcpy;
205
206 /// Return code for isLegalStore()
207 enum LegalStoreKind {
208 None = 0,
209 Memset,
210 MemsetPattern,
211 Memcpy,
212 UnorderedAtomicMemcpy,
213 DontUse // Dummy retval never to be used. Allows catching errors in retval
214 // handling.
215 };
216
217 /// \name Countable Loop Idiom Handling
218 /// @{
219
220 bool runOnCountableLoop();
221 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
222 SmallVectorImpl<BasicBlock *> &ExitBlocks);
223
224 void collectStores(BasicBlock *BB);
225 LegalStoreKind isLegalStore(StoreInst *SI);
226 enum class ForMemset { No, Yes };
227 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
228 ForMemset For);
229
230 template <typename MemInst>
231 bool processLoopMemIntrinsic(
232 BasicBlock *BB,
233 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
234 const SCEV *BECount);
235 bool processLoopMemCpy(MemCpyInst *MCI, const SCEV *BECount);
236 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
237
238 bool processLoopStridedStore(Value *DestPtr, const SCEV *StoreSizeSCEV,
239 MaybeAlign StoreAlignment, Value *StoredVal,
240 Instruction *TheStore,
241 SmallPtrSetImpl<Instruction *> &Stores,
242 const SCEVAddRecExpr *Ev, const SCEV *BECount,
243 bool IsNegStride, bool IsLoopMemset = false);
244 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
245 bool processLoopStoreOfLoopLoad(Value *DestPtr, Value *SourcePtr,
246 const SCEV *StoreSize, MaybeAlign StoreAlign,
247 MaybeAlign LoadAlign, Instruction *TheStore,
248 Instruction *TheLoad,
249 const SCEVAddRecExpr *StoreEv,
250 const SCEVAddRecExpr *LoadEv,
251 const SCEV *BECount);
252 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
253 bool IsLoopMemset = false);
254 bool optimizeCRCLoop(const PolynomialInfo &Info);
255
256 /// @}
257 /// \name Noncountable Loop Idiom Handling
258 /// @{
259
260 bool runOnNoncountableLoop();
261
262 bool recognizePopcount();
263 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
264 PHINode *CntPhi, Value *Var);
265 bool isProfitableToInsertFFS(Intrinsic::ID IntrinID, Value *InitX,
266 bool ZeroCheck, size_t CanonicalSize);
267 bool insertFFSIfProfitable(Intrinsic::ID IntrinID, Value *InitX,
268 Instruction *DefX, PHINode *CntPhi,
269 Instruction *CntInst);
270 bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz
271 bool recognizeShiftUntilLessThan();
272 void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB,
273 Instruction *CntInst, PHINode *CntPhi,
274 Value *Var, Instruction *DefX,
275 const DebugLoc &DL, bool ZeroCheck,
276 bool IsCntPhiUsedOutsideLoop,
277 bool InsertSub = false);
278
279 bool recognizeShiftUntilBitTest();
280 bool recognizeShiftUntilZero();
281 bool recognizeAndInsertStrLen();
282
283 /// @}
284};
285} // end anonymous namespace
286
289 LPMUpdater &) {
291 return PreservedAnalyses::all();
292
293 const auto *DL = &L.getHeader()->getDataLayout();
294
295 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
296 // pass. Function analyses need to be preserved across loop transformations
297 // but ORE cannot be preserved (see comment before the pass definition).
298 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
299
300 std::optional<PolynomialInfo> HR;
301
302 LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI,
303 AR.MSSA, DL, ORE);
304 if (!LIR.runOnLoop(&L))
305 return PreservedAnalyses::all();
306
308 if (AR.MSSA)
309 PA.preserve<MemorySSAAnalysis>();
310 return PA;
311}
312
314 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
315 I->eraseFromParent();
316}
317
318//===----------------------------------------------------------------------===//
319//
320// Implementation of LoopIdiomRecognize
321//
322//===----------------------------------------------------------------------===//
323
324bool LoopIdiomRecognize::runOnLoop(Loop *L) {
325 CurLoop = L;
326 // If the loop could not be converted to canonical form, it must have an
327 // indirectbr in it, just give up.
328 if (!L->getLoopPreheader())
329 return false;
330
331 // Disable loop idiom recognition if the function's name is a common idiom.
332 StringRef Name = L->getHeader()->getParent()->getName();
333 if (Name == "memset" || Name == "memcpy" || Name == "strlen" ||
334 Name == "wcslen")
335 return false;
336
337 // Determine if code size heuristics need to be applied.
338 ApplyCodeSizeHeuristics =
339 L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs;
340
341 HasMemset = TLI->has(LibFunc_memset);
342 // TODO: Unconditionally enable use of the memset pattern intrinsic (or at
343 // least, opt-in via target hook) once we are confident it will never result
344 // in worse codegen than without. For now, use it only when the target
345 // supports memset_pattern16 libcall (or unless this is overridden by
346 // command line option).
347 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
348 HasMemcpy = TLI->has(LibFunc_memcpy);
349
350 if (HasMemset || HasMemsetPattern || ForceMemsetPatternIntrinsic ||
351 HasMemcpy || !DisableLIRP::HashRecognize)
353 return runOnCountableLoop();
354
355 return runOnNoncountableLoop();
356}
357
358bool LoopIdiomRecognize::runOnCountableLoop() {
359 const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
361 "runOnCountableLoop() called on a loop without a predictable"
362 "backedge-taken count");
363
364 // If this loop executes exactly one time, then it should be peeled, not
365 // optimized by this pass.
366 if (BECount->isZero())
367 return false;
368
370 CurLoop->getUniqueExitBlocks(ExitBlocks);
371
372 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
373 << CurLoop->getHeader()->getParent()->getName()
374 << "] Countable Loop %" << CurLoop->getHeader()->getName()
375 << "\n");
376
377 // The following transforms hoist stores/memsets into the loop pre-header.
378 // Give up if the loop has instructions that may throw.
379 SimpleLoopSafetyInfo SafetyInfo;
380 SafetyInfo.computeLoopSafetyInfo(CurLoop);
381 if (SafetyInfo.anyBlockMayThrow())
382 return false;
383
384 bool MadeChange = false;
385
386 // Scan all the blocks in the loop that are not in subloops.
387 for (auto *BB : CurLoop->getBlocks()) {
388 // Ignore blocks in subloops.
389 if (LI->getLoopFor(BB) != CurLoop)
390 continue;
391
392 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
393 }
394
395 // Optimize a CRC loop if HashRecognize found one, provided we're not
396 // optimizing for size.
397 if (!DisableLIRP::HashRecognize && !ApplyCodeSizeHeuristics)
398 if (auto Res = HashRecognize(*CurLoop, *SE).getResult())
399 optimizeCRCLoop(*Res);
400
401 return MadeChange;
402}
403
404static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
405 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
406 return ConstStride->getAPInt();
407}
408
409/// getMemSetPatternValue - If a strided store of the specified value is safe to
410/// turn into a memset.patternn intrinsic, return the Constant that should
411/// be passed in. Otherwise, return null.
412///
413/// TODO this function could allow more constants than it does today (e.g.
414/// those over 16 bytes) now it has transitioned to being used for the
415/// memset.pattern intrinsic rather than directly the memset_pattern16
416/// libcall.
418 // FIXME: This could check for UndefValue because it can be merged into any
419 // other valid pattern.
420
421 // If the value isn't a constant, we can't promote it to being in a constant
422 // array. We could theoretically do a store to an alloca or something, but
423 // that doesn't seem worthwhile.
425 if (!C || isa<ConstantExpr>(C))
426 return nullptr;
427
428 // Only handle simple values that are a power of two bytes in size.
429 uint64_t Size = DL->getTypeSizeInBits(V->getType());
430 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
431 return nullptr;
432
433 // Don't care enough about darwin/ppc to implement this.
434 if (DL->isBigEndian())
435 return nullptr;
436
437 // Convert to size in bytes.
438 Size /= 8;
439
440 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
441 // if the top and bottom are the same (e.g. for vectors and large integers).
442 if (Size > 16)
443 return nullptr;
444
445 // For now, don't handle types that aren't int, floats, or pointers.
446 Type *CTy = C->getType();
447 if (!CTy->isIntOrPtrTy() && !CTy->isFloatingPointTy())
448 return nullptr;
449
450 return C;
451}
452
453LoopIdiomRecognize::LegalStoreKind
454LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
455 // Don't touch volatile stores.
456 if (SI->isVolatile())
457 return LegalStoreKind::None;
458 // We only want simple or unordered-atomic stores.
459 if (!SI->isUnordered())
460 return LegalStoreKind::None;
461
462 // Avoid merging nontemporal stores.
463 if (SI->getMetadata(LLVMContext::MD_nontemporal))
464 return LegalStoreKind::None;
465
466 Value *StoredVal = SI->getValueOperand();
467 Value *StorePtr = SI->getPointerOperand();
468
469 // Don't convert stores of non-integral pointer types to memsets (which stores
470 // integers).
471 if (DL->isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
472 return LegalStoreKind::None;
473
474 // Reject stores that are so large that they overflow an unsigned.
475 // When storing out scalable vectors we bail out for now, since the code
476 // below currently only works for constant strides.
477 TypeSize SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
478 if (SizeInBits.isScalable() || (SizeInBits.getFixedValue() & 7) ||
479 (SizeInBits.getFixedValue() >> 32) != 0)
480 return LegalStoreKind::None;
481
482 // See if the pointer expression is an AddRec like {base,+,1} on the current
483 // loop, which indicates a strided store. If we have something else, it's a
484 // random store we can't handle.
485 const SCEV *StoreEv = SE->getSCEV(StorePtr);
486 const SCEVConstant *Stride;
487 if (!match(StoreEv, m_scev_AffineAddRec(m_SCEV(), m_SCEVConstant(Stride),
488 m_SpecificLoop(CurLoop))))
489 return LegalStoreKind::None;
490
491 // See if the store can be turned into a memset.
492
493 // If the stored value is a byte-wise value (like i32 -1), then it may be
494 // turned into a memset of i8 -1, assuming that all the consecutive bytes
495 // are stored. A store of i32 0x01020304 can never be turned into a memset,
496 // but it can be turned into memset_pattern if the target supports it.
497 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
498
499 // Note: memset and memset_pattern on unordered-atomic is yet not supported
500 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
501
502 // If we're allowed to form a memset, and the stored value would be
503 // acceptable for memset, use it.
504 if (!UnorderedAtomic && HasMemset && SplatValue && !DisableLIRP::Memset &&
505 // Verify that the stored value is loop invariant. If not, we can't
506 // promote the memset.
507 CurLoop->isLoopInvariant(SplatValue)) {
508 // It looks like we can use SplatValue.
509 return LegalStoreKind::Memset;
510 }
511 if (!UnorderedAtomic && (HasMemsetPattern || ForceMemsetPatternIntrinsic) &&
513 // Don't create memset_pattern16s with address spaces.
514 StorePtr->getType()->getPointerAddressSpace() == 0 &&
515 getMemSetPatternValue(StoredVal, DL)) {
516 // It looks like we can use PatternValue!
517 return LegalStoreKind::MemsetPattern;
518 }
519
520 // Otherwise, see if the store can be turned into a memcpy.
521 if (HasMemcpy && !DisableLIRP::Memcpy) {
522 // Check to see if the stride matches the size of the store. If so, then we
523 // know that every byte is touched in the loop.
524 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
525 APInt StrideAP = Stride->getAPInt();
526 if (StoreSize != StrideAP && StoreSize != -StrideAP)
527 return LegalStoreKind::None;
528
529 // The store must be feeding a non-volatile load.
530 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
531
532 // Only allow non-volatile loads
533 if (!LI || LI->isVolatile())
534 return LegalStoreKind::None;
535 // Only allow simple or unordered-atomic loads
536 if (!LI->isUnordered())
537 return LegalStoreKind::None;
538
539 // See if the pointer expression is an AddRec like {base,+,1} on the current
540 // loop, which indicates a strided load. If we have something else, it's a
541 // random load we can't handle.
542 const SCEV *LoadEv = SE->getSCEV(LI->getPointerOperand());
543
544 // The store and load must share the same stride.
545 if (!match(LoadEv, m_scev_AffineAddRec(m_SCEV(), m_scev_Specific(Stride),
546 m_SpecificLoop(CurLoop))))
547 return LegalStoreKind::None;
548
549 // Success. This store can be converted into a memcpy.
550 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
551 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
552 : LegalStoreKind::Memcpy;
553 }
554 // This store can't be transformed into a memset/memcpy.
555 return LegalStoreKind::None;
556}
557
558void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
559 StoreRefsForMemset.clear();
560 StoreRefsForMemsetPattern.clear();
561 StoreRefsForMemcpy.clear();
562 for (Instruction &I : *BB) {
564 if (!SI)
565 continue;
566
567 // Make sure this is a strided store with a constant stride.
568 switch (isLegalStore(SI)) {
569 case LegalStoreKind::None:
570 // Nothing to do
571 break;
572 case LegalStoreKind::Memset: {
573 // Find the base pointer.
574 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
575 StoreRefsForMemset[Ptr].push_back(SI);
576 } break;
577 case LegalStoreKind::MemsetPattern: {
578 // Find the base pointer.
579 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
580 StoreRefsForMemsetPattern[Ptr].push_back(SI);
581 } break;
582 case LegalStoreKind::Memcpy:
583 case LegalStoreKind::UnorderedAtomicMemcpy:
584 StoreRefsForMemcpy.push_back(SI);
585 break;
586 default:
587 assert(false && "unhandled return value");
588 break;
589 }
590 }
591}
592
593/// runOnLoopBlock - Process the specified block, which lives in a counted loop
594/// with the specified backedge count. This block is known to be in the current
595/// loop and not in any subloops.
596bool LoopIdiomRecognize::runOnLoopBlock(
597 BasicBlock *BB, const SCEV *BECount,
598 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
599 // We can only promote stores in this block if they are unconditionally
600 // executed in the loop. For a block to be unconditionally executed, it has
601 // to dominate all the exit blocks of the loop. Verify this now.
602 for (BasicBlock *ExitBlock : ExitBlocks)
603 if (!DT->dominates(BB, ExitBlock))
604 return false;
605
606 bool MadeChange = false;
607 // Look for store instructions, which may be optimized to memset/memcpy.
608 collectStores(BB);
609
610 // Look for a single store or sets of stores with a common base, which can be
611 // optimized into a memset (memset_pattern). The latter most commonly happens
612 // with structs and handunrolled loops.
613 for (auto &SL : StoreRefsForMemset)
614 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
615
616 for (auto &SL : StoreRefsForMemsetPattern)
617 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
618
619 // Optimize the store into a memcpy, if it feeds an similarly strided load.
620 for (auto &SI : StoreRefsForMemcpy)
621 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
622
623 MadeChange |= processLoopMemIntrinsic<MemCpyInst>(
624 BB, &LoopIdiomRecognize::processLoopMemCpy, BECount);
625 MadeChange |= processLoopMemIntrinsic<MemSetInst>(
626 BB, &LoopIdiomRecognize::processLoopMemSet, BECount);
627
628 return MadeChange;
629}
630
631/// See if this store(s) can be promoted to a memset.
632bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
633 const SCEV *BECount, ForMemset For) {
634 // Try to find consecutive stores that can be transformed into memsets.
635 SetVector<StoreInst *> Heads, Tails;
637
638 // Do a quadratic search on all of the given stores and find
639 // all of the pairs of stores that follow each other.
640 SmallVector<unsigned, 16> IndexQueue;
641 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
642 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
643
644 Value *FirstStoredVal = SL[i]->getValueOperand();
645 Value *FirstStorePtr = SL[i]->getPointerOperand();
646 const SCEVAddRecExpr *FirstStoreEv =
647 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
648 APInt FirstStride = getStoreStride(FirstStoreEv);
649 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
650
651 // See if we can optimize just this store in isolation.
652 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
653 Heads.insert(SL[i]);
654 continue;
655 }
656
657 Value *FirstSplatValue = nullptr;
658 Constant *FirstPatternValue = nullptr;
659
660 if (For == ForMemset::Yes)
661 FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL);
662 else
663 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
664
665 assert((FirstSplatValue || FirstPatternValue) &&
666 "Expected either splat value or pattern value.");
667
668 IndexQueue.clear();
669 // If a store has multiple consecutive store candidates, search Stores
670 // array according to the sequence: from i+1 to e, then from i-1 to 0.
671 // This is because usually pairing with immediate succeeding or preceding
672 // candidate create the best chance to find memset opportunity.
673 unsigned j = 0;
674 for (j = i + 1; j < e; ++j)
675 IndexQueue.push_back(j);
676 for (j = i; j > 0; --j)
677 IndexQueue.push_back(j - 1);
678
679 for (auto &k : IndexQueue) {
680 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
681 Value *SecondStorePtr = SL[k]->getPointerOperand();
682 const SCEVAddRecExpr *SecondStoreEv =
683 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
684 APInt SecondStride = getStoreStride(SecondStoreEv);
685
686 if (FirstStride != SecondStride)
687 continue;
688
689 Value *SecondStoredVal = SL[k]->getValueOperand();
690 Value *SecondSplatValue = nullptr;
691 Constant *SecondPatternValue = nullptr;
692
693 if (For == ForMemset::Yes)
694 SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL);
695 else
696 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
697
698 assert((SecondSplatValue || SecondPatternValue) &&
699 "Expected either splat value or pattern value.");
700
701 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
702 if (For == ForMemset::Yes) {
703 if (isa<UndefValue>(FirstSplatValue))
704 FirstSplatValue = SecondSplatValue;
705 if (FirstSplatValue != SecondSplatValue)
706 continue;
707 } else {
708 if (isa<UndefValue>(FirstPatternValue))
709 FirstPatternValue = SecondPatternValue;
710 if (FirstPatternValue != SecondPatternValue)
711 continue;
712 }
713 Tails.insert(SL[k]);
714 Heads.insert(SL[i]);
715 ConsecutiveChain[SL[i]] = SL[k];
716 break;
717 }
718 }
719 }
720
721 // We may run into multiple chains that merge into a single chain. We mark the
722 // stores that we transformed so that we don't visit the same store twice.
723 SmallPtrSet<Value *, 16> TransformedStores;
724 bool Changed = false;
725
726 // For stores that start but don't end a link in the chain:
727 for (StoreInst *I : Heads) {
728 if (Tails.count(I))
729 continue;
730
731 // We found a store instr that starts a chain. Now follow the chain and try
732 // to transform it.
733 SmallPtrSet<Instruction *, 8> AdjacentStores;
734 StoreInst *HeadStore = I;
735 unsigned StoreSize = 0;
736
737 // Collect the chain into a list.
738 while (Tails.count(I) || Heads.count(I)) {
739 if (TransformedStores.count(I))
740 break;
741 AdjacentStores.insert(I);
742
743 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
744 // Move to the next value in the chain.
745 I = ConsecutiveChain[I];
746 }
747
748 Value *StoredVal = HeadStore->getValueOperand();
749 Value *StorePtr = HeadStore->getPointerOperand();
750 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
751 APInt Stride = getStoreStride(StoreEv);
752
753 // Check to see if the stride matches the size of the stores. If so, then
754 // we know that every byte is touched in the loop.
755 if (StoreSize != Stride && StoreSize != -Stride)
756 continue;
757
758 bool IsNegStride = StoreSize == -Stride;
759
760 Type *IntIdxTy = DL->getIndexType(StorePtr->getType());
761 const SCEV *StoreSizeSCEV = SE->getConstant(IntIdxTy, StoreSize);
762 if (processLoopStridedStore(StorePtr, StoreSizeSCEV,
763 MaybeAlign(HeadStore->getAlign()), StoredVal,
764 HeadStore, AdjacentStores, StoreEv, BECount,
765 IsNegStride)) {
766 TransformedStores.insert_range(AdjacentStores);
767 Changed = true;
768 }
769 }
770
771 return Changed;
772}
773
774/// processLoopMemIntrinsic - Template function for calling different processor
775/// functions based on mem intrinsic type.
776template <typename MemInst>
777bool LoopIdiomRecognize::processLoopMemIntrinsic(
778 BasicBlock *BB,
779 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
780 const SCEV *BECount) {
781 bool MadeChange = false;
782 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
783 Instruction *Inst = &*I++;
784 // Look for memory instructions, which may be optimized to a larger one.
785 if (MemInst *MI = dyn_cast<MemInst>(Inst)) {
786 WeakTrackingVH InstPtr(&*I);
787 if (!(this->*Processor)(MI, BECount))
788 continue;
789 MadeChange = true;
790
791 // If processing the instruction invalidated our iterator, start over from
792 // the top of the block.
793 if (!InstPtr)
794 I = BB->begin();
795 }
796 }
797 return MadeChange;
798}
799
800/// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy
801bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI,
802 const SCEV *BECount) {
803 // We can only handle non-volatile memcpys with a constant size.
804 if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength()))
805 return false;
806
807 // If we're not allowed to hack on memcpy, we fail.
808 if ((!HasMemcpy && !MCI->isForceInlined()) || DisableLIRP::Memcpy)
809 return false;
810
811 Value *Dest = MCI->getDest();
812 Value *Source = MCI->getSource();
813 if (!Dest || !Source)
814 return false;
815
816 // See if the load and store pointer expressions are AddRec like {base,+,1} on
817 // the current loop, which indicates a strided load and store. If we have
818 // something else, it's a random load or store we can't handle.
819 const SCEV *StoreEv = SE->getSCEV(Dest);
820 const SCEV *LoadEv = SE->getSCEV(Source);
821 const APInt *StoreStrideValue, *LoadStrideValue;
822 if (!match(StoreEv,
823 m_scev_AffineAddRec(m_SCEV(), m_scev_APInt(StoreStrideValue),
824 m_SpecificLoop(CurLoop))) ||
825 !match(LoadEv,
826 m_scev_AffineAddRec(m_SCEV(), m_scev_APInt(LoadStrideValue),
827 m_SpecificLoop(CurLoop))))
828 return false;
829
830 // Reject memcpys that are so large that they overflow an unsigned.
831 uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue();
832 if ((SizeInBytes >> 32) != 0)
833 return false;
834
835 // Huge stride value - give up
836 if (StoreStrideValue->getBitWidth() > 64 ||
837 LoadStrideValue->getBitWidth() > 64)
838 return false;
839
840 if (SizeInBytes != *StoreStrideValue && SizeInBytes != -*StoreStrideValue) {
841 ORE.emit([&]() {
842 return OptimizationRemarkMissed(DEBUG_TYPE, "SizeStrideUnequal", MCI)
843 << ore::NV("Inst", "memcpy") << " in "
844 << ore::NV("Function", MCI->getFunction())
845 << " function will not be hoisted: "
846 << ore::NV("Reason", "memcpy size is not equal to stride");
847 });
848 return false;
849 }
850
851 int64_t StoreStrideInt = StoreStrideValue->getSExtValue();
852 int64_t LoadStrideInt = LoadStrideValue->getSExtValue();
853 // Check if the load stride matches the store stride.
854 if (StoreStrideInt != LoadStrideInt)
855 return false;
856
857 return processLoopStoreOfLoopLoad(
858 Dest, Source, SE->getConstant(Dest->getType(), SizeInBytes),
859 MCI->getDestAlign(), MCI->getSourceAlign(), MCI, MCI,
860 cast<SCEVAddRecExpr>(StoreEv), cast<SCEVAddRecExpr>(LoadEv), BECount);
861}
862
863/// processLoopMemSet - See if this memset can be promoted to a large memset.
864bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
865 const SCEV *BECount) {
866 // We can only handle non-volatile memsets.
867 if (MSI->isVolatile())
868 return false;
869
870 // If we're not allowed to hack on memset, we fail.
871 if (!HasMemset || DisableLIRP::Memset)
872 return false;
873
874 Value *Pointer = MSI->getDest();
875
876 // See if the pointer expression is an AddRec like {base,+,1} on the current
877 // loop, which indicates a strided store. If we have something else, it's a
878 // random store we can't handle.
879 const SCEV *Ev = SE->getSCEV(Pointer);
880 const SCEV *PointerStrideSCEV;
881 if (!match(Ev, m_scev_AffineAddRec(m_SCEV(), m_SCEV(PointerStrideSCEV),
882 m_SpecificLoop(CurLoop)))) {
883 LLVM_DEBUG(dbgs() << " Pointer is not affine, abort\n");
884 return false;
885 }
886
887 const SCEV *MemsetSizeSCEV = SE->getSCEV(MSI->getLength());
888
889 bool IsNegStride = false;
890 const bool IsConstantSize = isa<ConstantInt>(MSI->getLength());
891
892 if (IsConstantSize) {
893 // Memset size is constant.
894 // Check if the pointer stride matches the memset size. If so, then
895 // we know that every byte is touched in the loop.
896 LLVM_DEBUG(dbgs() << " memset size is constant\n");
897 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
898 const APInt *Stride;
899 if (!match(PointerStrideSCEV, m_scev_APInt(Stride)))
900 return false;
901
902 if (SizeInBytes != *Stride && SizeInBytes != -*Stride)
903 return false;
904
905 IsNegStride = SizeInBytes == -*Stride;
906 } else {
907 // Memset size is non-constant.
908 // Check if the pointer stride matches the memset size.
909 // To be conservative, the pass would not promote pointers that aren't in
910 // address space zero. Also, the pass only handles memset length and stride
911 // that are invariant for the top level loop.
912 LLVM_DEBUG(dbgs() << " memset size is non-constant\n");
913 if (Pointer->getType()->getPointerAddressSpace() != 0) {
914 LLVM_DEBUG(dbgs() << " pointer is not in address space zero, "
915 << "abort\n");
916 return false;
917 }
918 if (!SE->isLoopInvariant(MemsetSizeSCEV, CurLoop)) {
919 LLVM_DEBUG(dbgs() << " memset size is not a loop-invariant, "
920 << "abort\n");
921 return false;
922 }
923
924 // Compare positive direction PointerStrideSCEV with MemsetSizeSCEV
925 IsNegStride = PointerStrideSCEV->isNonConstantNegative();
926 const SCEV *PositiveStrideSCEV =
927 IsNegStride ? SE->getNegativeSCEV(PointerStrideSCEV)
928 : PointerStrideSCEV;
929 LLVM_DEBUG(dbgs() << " MemsetSizeSCEV: " << *MemsetSizeSCEV << "\n"
930 << " PositiveStrideSCEV: " << *PositiveStrideSCEV
931 << "\n");
932
933 if (PositiveStrideSCEV != MemsetSizeSCEV) {
934 // If an expression is covered by the loop guard, compare again and
935 // proceed with optimization if equal.
936 const SCEV *FoldedPositiveStride =
937 SE->applyLoopGuards(PositiveStrideSCEV, CurLoop);
938 const SCEV *FoldedMemsetSize =
939 SE->applyLoopGuards(MemsetSizeSCEV, CurLoop);
940
941 LLVM_DEBUG(dbgs() << " Try to fold SCEV based on loop guard\n"
942 << " FoldedMemsetSize: " << *FoldedMemsetSize << "\n"
943 << " FoldedPositiveStride: " << *FoldedPositiveStride
944 << "\n");
945
946 if (FoldedPositiveStride != FoldedMemsetSize) {
947 LLVM_DEBUG(dbgs() << " SCEV don't match, abort\n");
948 return false;
949 }
950 }
951 }
952
953 // Verify that the memset value is loop invariant. If not, we can't promote
954 // the memset.
955 Value *SplatValue = MSI->getValue();
956 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
957 return false;
958
960 MSIs.insert(MSI);
961 return processLoopStridedStore(Pointer, SE->getSCEV(MSI->getLength()),
962 MSI->getDestAlign(), SplatValue, MSI, MSIs,
963 cast<SCEVAddRecExpr>(Ev), BECount, IsNegStride,
964 /*IsLoopMemset=*/true);
965}
966
967/// mayLoopAccessLocation - Return true if the specified loop might access the
968/// specified pointer location, which is a loop-strided access. The 'Access'
969/// argument specifies what the verboten forms of access are (read or write).
970static bool
972 const SCEV *BECount, const SCEV *StoreSizeSCEV,
974 SmallPtrSetImpl<Instruction *> &IgnoredInsts) {
975 // Get the location that may be stored across the loop. Since the access is
976 // strided positively through memory, we say that the modified location starts
977 // at the pointer and has infinite size.
979
980 // If the loop iterates a fixed number of times, we can refine the access size
981 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
982 const APInt *BECst, *ConstSize;
983 if (match(BECount, m_scev_APInt(BECst)) &&
984 match(StoreSizeSCEV, m_scev_APInt(ConstSize))) {
985 std::optional<uint64_t> BEInt = BECst->tryZExtValue();
986 std::optional<uint64_t> SizeInt = ConstSize->tryZExtValue();
987 // FIXME: Should this check for overflow?
988 if (BEInt && SizeInt)
989 AccessSize = LocationSize::precise((*BEInt + 1) * *SizeInt);
990 }
991
992 // TODO: For this to be really effective, we have to dive into the pointer
993 // operand in the store. Store to &A[i] of 100 will always return may alias
994 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
995 // which will then no-alias a store to &A[100].
996 MemoryLocation StoreLoc(Ptr, AccessSize);
997
998 for (BasicBlock *B : L->blocks())
999 for (Instruction &I : *B)
1000 if (!IgnoredInsts.contains(&I) &&
1001 isModOrRefSet(AA.getModRefInfo(&I, StoreLoc) & Access))
1002 return true;
1003 return false;
1004}
1005
1006// If we have a negative stride, Start refers to the end of the memory location
1007// we're trying to memset. Therefore, we need to recompute the base pointer,
1008// which is just Start - BECount*Size.
1009static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
1010 Type *IntPtr, const SCEV *StoreSizeSCEV,
1011 ScalarEvolution *SE) {
1012 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
1013 if (!StoreSizeSCEV->isOne()) {
1014 // index = back edge count * store size
1015 Index = SE->getMulExpr(Index,
1016 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
1018 }
1019 // base pointer = start - index * store size
1020 return SE->getMinusSCEV(Start, Index);
1021}
1022
1023/// Compute the number of bytes as a SCEV from the backedge taken count.
1024///
1025/// This also maps the SCEV into the provided type and tries to handle the
1026/// computation in a way that will fold cleanly.
1027static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
1028 const SCEV *StoreSizeSCEV, Loop *CurLoop,
1029 const DataLayout *DL, ScalarEvolution *SE) {
1030 const SCEV *TripCountSCEV =
1031 SE->getTripCountFromExitCount(BECount, IntPtr, CurLoop);
1032 return SE->getMulExpr(TripCountSCEV,
1033 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
1035}
1036
1037/// processLoopStridedStore - We see a strided store of some value. If we can
1038/// transform this into a memset or memset_pattern in the loop preheader, do so.
1039bool LoopIdiomRecognize::processLoopStridedStore(
1040 Value *DestPtr, const SCEV *StoreSizeSCEV, MaybeAlign StoreAlignment,
1041 Value *StoredVal, Instruction *TheStore,
1043 const SCEV *BECount, bool IsNegStride, bool IsLoopMemset) {
1044 Module *M = TheStore->getModule();
1045
1046 // The trip count of the loop and the base pointer of the addrec SCEV is
1047 // guaranteed to be loop invariant, which means that it should dominate the
1048 // header. This allows us to insert code for it in the preheader.
1049 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
1050 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1051 IRBuilder<> Builder(Preheader->getTerminator());
1052 SCEVExpander Expander(*SE, *DL, "loop-idiom");
1053 SCEVExpanderCleaner ExpCleaner(Expander);
1054
1055 Type *DestInt8PtrTy = Builder.getPtrTy(DestAS);
1056 Type *IntIdxTy = DL->getIndexType(DestPtr->getType());
1057
1058 bool Changed = false;
1059 const SCEV *Start = Ev->getStart();
1060 // Handle negative strided loops.
1061 if (IsNegStride)
1062 Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSizeSCEV, SE);
1063
1064 // TODO: ideally we should still be able to generate memset if SCEV expander
1065 // is taught to generate the dependencies at the latest point.
1066 if (!Expander.isSafeToExpand(Start))
1067 return Changed;
1068
1069 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
1070 // this into a memset in the loop preheader now if we want. However, this
1071 // would be unsafe to do if there is anything else in the loop that may read
1072 // or write to the aliased location. Check for any overlap by generating the
1073 // base pointer and checking the region.
1074 Value *BasePtr =
1075 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
1076
1077 // From here on out, conservatively report to the pass manager that we've
1078 // changed the IR, even if we later clean up these added instructions. There
1079 // may be structural differences e.g. in the order of use lists not accounted
1080 // for in just a textual dump of the IR. This is written as a variable, even
1081 // though statically all the places this dominates could be replaced with
1082 // 'true', with the hope that anyone trying to be clever / "more precise" with
1083 // the return value will read this comment, and leave them alone.
1084 Changed = true;
1085
1086 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1087 StoreSizeSCEV, *AA, Stores))
1088 return Changed;
1089
1090 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
1091 return Changed;
1092
1093 // Okay, everything looks good, insert the memset.
1094 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
1095 Constant *PatternValue = nullptr;
1096 if (!SplatValue)
1097 PatternValue = getMemSetPatternValue(StoredVal, DL);
1098
1099 // MemsetArg is the number of bytes for the memset libcall, and the number
1100 // of pattern repetitions if the memset.pattern intrinsic is being used.
1101 Value *MemsetArg;
1102 std::optional<int64_t> BytesWritten;
1103
1104 if (PatternValue && (HasMemsetPattern || ForceMemsetPatternIntrinsic)) {
1105 const SCEV *TripCountS =
1106 SE->getTripCountFromExitCount(BECount, IntIdxTy, CurLoop);
1107 if (!Expander.isSafeToExpand(TripCountS))
1108 return Changed;
1109 const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1110 if (!ConstStoreSize)
1111 return Changed;
1112 Value *TripCount = Expander.expandCodeFor(TripCountS, IntIdxTy,
1113 Preheader->getTerminator());
1114 uint64_t PatternRepsPerTrip =
1115 (ConstStoreSize->getValue()->getZExtValue() * 8) /
1116 DL->getTypeSizeInBits(PatternValue->getType());
1117 // If ConstStoreSize is not equal to the width of PatternValue, then
1118 // MemsetArg is TripCount * (ConstStoreSize/PatternValueWidth). Else
1119 // MemSetArg is just TripCount.
1120 MemsetArg =
1121 PatternRepsPerTrip == 1
1122 ? TripCount
1123 : Builder.CreateMul(TripCount,
1124 Builder.getIntN(IntIdxTy->getIntegerBitWidth(),
1125 PatternRepsPerTrip));
1126 if (auto *CI = dyn_cast<ConstantInt>(TripCount))
1127 BytesWritten =
1128 CI->getZExtValue() * ConstStoreSize->getValue()->getZExtValue();
1129
1130 } else {
1131 const SCEV *NumBytesS =
1132 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
1133
1134 // TODO: ideally we should still be able to generate memset if SCEV expander
1135 // is taught to generate the dependencies at the latest point.
1136 if (!Expander.isSafeToExpand(NumBytesS))
1137 return Changed;
1138 MemsetArg =
1139 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1140 if (auto *CI = dyn_cast<ConstantInt>(MemsetArg))
1141 BytesWritten = CI->getZExtValue();
1142 }
1143 assert(MemsetArg && "MemsetArg should have been set");
1144
1145 AAMDNodes AATags = TheStore->getAAMetadata();
1146 for (Instruction *Store : Stores)
1147 AATags = AATags.merge(Store->getAAMetadata());
1148 if (BytesWritten)
1149 AATags = AATags.extendTo(BytesWritten.value());
1150 else
1151 AATags = AATags.extendTo(-1);
1152
1153 CallInst *NewCall;
1154 if (SplatValue) {
1155 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, MemsetArg,
1156 MaybeAlign(StoreAlignment),
1157 /*isVolatile=*/false, AATags);
1158 } else if (ForceMemsetPatternIntrinsic ||
1159 isLibFuncEmittable(M, TLI, LibFunc_memset_pattern16)) {
1160 assert(isa<SCEVConstant>(StoreSizeSCEV) && "Expected constant store size");
1161
1162 NewCall = Builder.CreateIntrinsic(
1163 Intrinsic::experimental_memset_pattern,
1164 {DestInt8PtrTy, PatternValue->getType(), IntIdxTy},
1165 {BasePtr, PatternValue, MemsetArg,
1166 ConstantInt::getFalse(M->getContext())});
1167 if (StoreAlignment)
1168 cast<MemSetPatternInst>(NewCall)->setDestAlignment(*StoreAlignment);
1169 NewCall->setAAMetadata(AATags);
1170 } else {
1171 // Neither a memset, nor memset_pattern16
1172 return Changed;
1173 }
1174
1175 NewCall->setDebugLoc(TheStore->getDebugLoc());
1176
1177 if (MSSAU) {
1178 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1179 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1180 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1181 }
1182
1183 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
1184 << " from store to: " << *Ev << " at: " << *TheStore
1185 << "\n");
1186
1187 ORE.emit([&]() {
1188 OptimizationRemark R(DEBUG_TYPE, "ProcessLoopStridedStore",
1189 NewCall->getDebugLoc(), Preheader);
1190 R << "Transformed loop-strided store in "
1191 << ore::NV("Function", TheStore->getFunction())
1192 << " function into a call to "
1193 << ore::NV("NewFunction", NewCall->getCalledFunction())
1194 << "() intrinsic";
1195 if (!Stores.empty())
1196 R << ore::setExtraArgs();
1197 for (auto *I : Stores) {
1198 R << ore::NV("FromBlock", I->getParent()->getName())
1199 << ore::NV("ToBlock", Preheader->getName());
1200 }
1201 return R;
1202 });
1203
1204 // Okay, the memset has been formed. Zap the original store and anything that
1205 // feeds into it.
1206 for (auto *I : Stores) {
1207 if (MSSAU)
1208 MSSAU->removeMemoryAccess(I, true);
1210 }
1211 if (MSSAU && VerifyMemorySSA)
1212 MSSAU->getMemorySSA()->verifyMemorySSA();
1213 ++NumMemSet;
1214 ExpCleaner.markResultUsed();
1215 return true;
1216}
1217
1218/// If the stored value is a strided load in the same loop with the same stride
1219/// this may be transformable into a memcpy. This kicks in for stuff like
1220/// for (i) A[i] = B[i];
1221bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
1222 const SCEV *BECount) {
1223 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
1224
1225 Value *StorePtr = SI->getPointerOperand();
1226 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1227 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
1228
1229 // The store must be feeding a non-volatile load.
1230 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1231 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
1232
1233 // See if the pointer expression is an AddRec like {base,+,1} on the current
1234 // loop, which indicates a strided load. If we have something else, it's a
1235 // random load we can't handle.
1236 Value *LoadPtr = LI->getPointerOperand();
1237 const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1238
1239 const SCEV *StoreSizeSCEV = SE->getConstant(StorePtr->getType(), StoreSize);
1240 return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSizeSCEV,
1241 SI->getAlign(), LI->getAlign(), SI, LI,
1242 StoreEv, LoadEv, BECount);
1243}
1244
1245namespace {
1246class MemmoveVerifier {
1247public:
1248 explicit MemmoveVerifier(const Value &LoadBasePtr, const Value &StoreBasePtr,
1249 const DataLayout &DL)
1251 LoadBasePtr.stripPointerCasts(), LoadOff, DL)),
1253 StoreBasePtr.stripPointerCasts(), StoreOff, DL)),
1254 IsSameObject(BP1 == BP2) {}
1255
1256 bool loadAndStoreMayFormMemmove(unsigned StoreSize, bool IsNegStride,
1257 const Instruction &TheLoad,
1258 bool IsMemCpy) const {
1259 if (IsMemCpy) {
1260 // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr
1261 // for negative stride.
1262 if ((!IsNegStride && LoadOff <= StoreOff) ||
1263 (IsNegStride && LoadOff >= StoreOff))
1264 return false;
1265 } else {
1266 // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr
1267 // for negative stride. LoadBasePtr shouldn't overlap with StoreBasePtr.
1268 int64_t LoadSize =
1269 DL.getTypeSizeInBits(TheLoad.getType()).getFixedValue() / 8;
1270 if (BP1 != BP2 || LoadSize != int64_t(StoreSize))
1271 return false;
1272 if ((!IsNegStride && LoadOff < StoreOff + int64_t(StoreSize)) ||
1273 (IsNegStride && LoadOff + LoadSize > StoreOff))
1274 return false;
1275 }
1276 return true;
1277 }
1278
1279private:
1280 const DataLayout &DL;
1281 int64_t LoadOff = 0;
1282 int64_t StoreOff = 0;
1283 const Value *BP1;
1284 const Value *BP2;
1285
1286public:
1287 const bool IsSameObject;
1288};
1289} // namespace
1290
1291bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
1292 Value *DestPtr, Value *SourcePtr, const SCEV *StoreSizeSCEV,
1293 MaybeAlign StoreAlign, MaybeAlign LoadAlign, Instruction *TheStore,
1294 Instruction *TheLoad, const SCEVAddRecExpr *StoreEv,
1295 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
1296
1297 // FIXME: until llvm.memcpy.inline supports dynamic sizes, we need to
1298 // conservatively bail here, since otherwise we may have to transform
1299 // llvm.memcpy.inline into llvm.memcpy which is illegal.
1300 if (auto *MCI = dyn_cast<MemCpyInst>(TheStore); MCI && MCI->isForceInlined())
1301 return false;
1302
1303 // The trip count of the loop and the base pointer of the addrec SCEV is
1304 // guaranteed to be loop invariant, which means that it should dominate the
1305 // header. This allows us to insert code for it in the preheader.
1306 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1307 IRBuilder<> Builder(Preheader->getTerminator());
1308 SCEVExpander Expander(*SE, *DL, "loop-idiom");
1309
1310 SCEVExpanderCleaner ExpCleaner(Expander);
1311
1312 bool Changed = false;
1313 const SCEV *StrStart = StoreEv->getStart();
1314 unsigned StrAS = DestPtr->getType()->getPointerAddressSpace();
1315 Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS));
1316
1317 APInt Stride = getStoreStride(StoreEv);
1318 const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1319
1320 // TODO: Deal with non-constant size; Currently expect constant store size
1321 assert(ConstStoreSize && "store size is expected to be a constant");
1322
1323 int64_t StoreSize = ConstStoreSize->getValue()->getZExtValue();
1324 bool IsNegStride = StoreSize == -Stride;
1325
1326 // Handle negative strided loops.
1327 if (IsNegStride)
1328 StrStart =
1329 getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1330
1331 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
1332 // this into a memcpy in the loop preheader now if we want. However, this
1333 // would be unsafe to do if there is anything else in the loop that may read
1334 // or write the memory region we're storing to. This includes the load that
1335 // feeds the stores. Check for an alias by generating the base address and
1336 // checking everything.
1337 Value *StoreBasePtr = Expander.expandCodeFor(
1338 StrStart, Builder.getPtrTy(StrAS), Preheader->getTerminator());
1339
1340 // From here on out, conservatively report to the pass manager that we've
1341 // changed the IR, even if we later clean up these added instructions. There
1342 // may be structural differences e.g. in the order of use lists not accounted
1343 // for in just a textual dump of the IR. This is written as a variable, even
1344 // though statically all the places this dominates could be replaced with
1345 // 'true', with the hope that anyone trying to be clever / "more precise" with
1346 // the return value will read this comment, and leave them alone.
1347 Changed = true;
1348
1349 SmallPtrSet<Instruction *, 2> IgnoredInsts;
1350 IgnoredInsts.insert(TheStore);
1351
1352 bool IsMemCpy = isa<MemCpyInst>(TheStore);
1353 const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store";
1354
1355 bool LoopAccessStore =
1356 mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1357 StoreSizeSCEV, *AA, IgnoredInsts);
1358 if (LoopAccessStore) {
1359 // For memmove case it's not enough to guarantee that loop doesn't access
1360 // TheStore and TheLoad. Additionally we need to make sure that TheStore is
1361 // the only user of TheLoad.
1362 if (!TheLoad->hasOneUse())
1363 return Changed;
1364 IgnoredInsts.insert(TheLoad);
1365 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
1366 BECount, StoreSizeSCEV, *AA, IgnoredInsts)) {
1367 ORE.emit([&]() {
1368 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessStore",
1369 TheStore)
1370 << ore::NV("Inst", InstRemark) << " in "
1371 << ore::NV("Function", TheStore->getFunction())
1372 << " function will not be hoisted: "
1373 << ore::NV("Reason", "The loop may access store location");
1374 });
1375 return Changed;
1376 }
1377 IgnoredInsts.erase(TheLoad);
1378 }
1379
1380 const SCEV *LdStart = LoadEv->getStart();
1381 unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace();
1382
1383 // Handle negative strided loops.
1384 if (IsNegStride)
1385 LdStart =
1386 getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1387
1388 // For a memcpy, we have to make sure that the input array is not being
1389 // mutated by the loop.
1390 Value *LoadBasePtr = Expander.expandCodeFor(LdStart, Builder.getPtrTy(LdAS),
1391 Preheader->getTerminator());
1392
1393 // If the store is a memcpy instruction, we must check if it will write to
1394 // the load memory locations. So remove it from the ignored stores.
1395 MemmoveVerifier Verifier(*LoadBasePtr, *StoreBasePtr, *DL);
1396 if (IsMemCpy && !Verifier.IsSameObject)
1397 IgnoredInsts.erase(TheStore);
1398 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1399 StoreSizeSCEV, *AA, IgnoredInsts)) {
1400 ORE.emit([&]() {
1401 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessLoad", TheLoad)
1402 << ore::NV("Inst", InstRemark) << " in "
1403 << ore::NV("Function", TheStore->getFunction())
1404 << " function will not be hoisted: "
1405 << ore::NV("Reason", "The loop may access load location");
1406 });
1407 return Changed;
1408 }
1409
1410 bool IsAtomic = TheStore->isAtomic() || TheLoad->isAtomic();
1411 bool UseMemMove = IsMemCpy ? Verifier.IsSameObject : LoopAccessStore;
1412
1413 if (IsAtomic) {
1414 // For now don't support unordered atomic memmove.
1415 if (UseMemMove)
1416 return Changed;
1417
1418 // We cannot allow unaligned ops for unordered load/store, so reject
1419 // anything where the alignment isn't at least the element size.
1420 assert((StoreAlign && LoadAlign) &&
1421 "Expect unordered load/store to have align.");
1422 if (*StoreAlign < StoreSize || *LoadAlign < StoreSize)
1423 return Changed;
1424
1425 // If the element.atomic memcpy is not lowered into explicit
1426 // loads/stores later, then it will be lowered into an element-size
1427 // specific lib call. If the lib call doesn't exist for our store size, then
1428 // we shouldn't generate the memcpy.
1429 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1430 return Changed;
1431 }
1432
1433 if (UseMemMove)
1434 if (!Verifier.loadAndStoreMayFormMemmove(StoreSize, IsNegStride, *TheLoad,
1435 IsMemCpy))
1436 return Changed;
1437
1438 if (avoidLIRForMultiBlockLoop())
1439 return Changed;
1440
1441 // Okay, everything is safe, we can transform this!
1442
1443 const SCEV *NumBytesS =
1444 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
1445
1446 Value *NumBytes =
1447 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1448
1449 AAMDNodes AATags = TheLoad->getAAMetadata();
1450 AAMDNodes StoreAATags = TheStore->getAAMetadata();
1451 AATags = AATags.merge(StoreAATags);
1452 if (auto CI = dyn_cast<ConstantInt>(NumBytes))
1453 AATags = AATags.extendTo(CI->getZExtValue());
1454 else
1455 AATags = AATags.extendTo(-1);
1456
1457 CallInst *NewCall = nullptr;
1458 // Check whether to generate an unordered atomic memcpy:
1459 // If the load or store are atomic, then they must necessarily be unordered
1460 // by previous checks.
1461 if (!IsAtomic) {
1462 if (UseMemMove)
1463 NewCall = Builder.CreateMemMove(StoreBasePtr, StoreAlign, LoadBasePtr,
1464 LoadAlign, NumBytes,
1465 /*isVolatile=*/false, AATags);
1466 else
1467 NewCall =
1468 Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign,
1469 NumBytes, /*isVolatile=*/false, AATags);
1470 } else {
1471 // Create the call.
1472 // Note that unordered atomic loads/stores are *required* by the spec to
1473 // have an alignment but non-atomic loads/stores may not.
1474 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1475 StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, StoreSize,
1476 AATags);
1477 }
1478 NewCall->setDebugLoc(TheStore->getDebugLoc());
1479
1480 if (MSSAU) {
1481 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1482 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1483 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1484 }
1485
1486 LLVM_DEBUG(dbgs() << " Formed new call: " << *NewCall << "\n"
1487 << " from load ptr=" << *LoadEv << " at: " << *TheLoad
1488 << "\n"
1489 << " from store ptr=" << *StoreEv << " at: " << *TheStore
1490 << "\n");
1491
1492 ORE.emit([&]() {
1493 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad",
1494 NewCall->getDebugLoc(), Preheader)
1495 << "Formed a call to "
1496 << ore::NV("NewFunction", NewCall->getCalledFunction())
1497 << "() intrinsic from " << ore::NV("Inst", InstRemark)
1498 << " instruction in " << ore::NV("Function", TheStore->getFunction())
1499 << " function"
1501 << ore::NV("FromBlock", TheStore->getParent()->getName())
1502 << ore::NV("ToBlock", Preheader->getName());
1503 });
1504
1505 // Okay, a new call to memcpy/memmove has been formed. Zap the original store
1506 // and anything that feeds into it.
1507 if (MSSAU)
1508 MSSAU->removeMemoryAccess(TheStore, true);
1509 deleteDeadInstruction(TheStore);
1510 if (MSSAU && VerifyMemorySSA)
1511 MSSAU->getMemorySSA()->verifyMemorySSA();
1512 if (UseMemMove)
1513 ++NumMemMove;
1514 else
1515 ++NumMemCpy;
1516 ExpCleaner.markResultUsed();
1517 return true;
1518}
1519
1520// When compiling for codesize we avoid idiom recognition for a multi-block loop
1521// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1522//
1523bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1524 bool IsLoopMemset) {
1525 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1526 if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) {
1527 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1528 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1529 << " avoided: multi-block top-level loop\n");
1530 return true;
1531 }
1532 }
1533
1534 return false;
1535}
1536
1537bool LoopIdiomRecognize::optimizeCRCLoop(const PolynomialInfo &Info) {
1538 // FIXME: Hexagon has a special HexagonLoopIdiom that optimizes CRC using
1539 // carry-less multiplication instructions, which is more efficient than our
1540 // Sarwate table-lookup optimization. Hence, until we're able to emit
1541 // target-specific instructions for Hexagon, subsuming HexagonLoopIdiom,
1542 // disable the optimization for Hexagon.
1543 Module &M = *CurLoop->getHeader()->getModule();
1544 Triple TT(M.getTargetTriple());
1545 if (TT.getArch() == Triple::hexagon)
1546 return false;
1547
1548 // First, create a new GlobalVariable corresponding to the
1549 // Sarwate-lookup-table.
1550 Type *CRCTy = Info.LHS->getType();
1551 unsigned CRCBW = CRCTy->getIntegerBitWidth();
1552 std::array<Constant *, 256> CRCConstants;
1553 transform(HashRecognize::genSarwateTable(Info.RHS, Info.ByteOrderSwapped),
1554 CRCConstants.begin(),
1555 [CRCTy](const APInt &E) { return ConstantInt::get(CRCTy, E); });
1556 Constant *ConstArray =
1557 ConstantArray::get(ArrayType::get(CRCTy, 256), CRCConstants);
1558 GlobalVariable *GV =
1559 new GlobalVariable(M, ConstArray->getType(), true,
1560 GlobalValue::PrivateLinkage, ConstArray, ".crctable");
1561
1564
1565 // Next, mark all PHIs for removal except IV.
1566 {
1567 for (PHINode &PN : CurLoop->getHeader()->phis()) {
1568 if (&PN == IV)
1569 continue;
1570 PN.replaceAllUsesWith(PoisonValue::get(PN.getType()));
1571 Cleanup.push_back(&PN);
1572 }
1573 }
1574
1575 // Next, fix up the trip count.
1576 {
1577 unsigned NewBTC = (Info.TripCount / 8) - 1;
1578 BasicBlock *LoopBlk = CurLoop->getLoopLatch();
1579 BranchInst *BrInst = cast<BranchInst>(LoopBlk->getTerminator());
1580 CmpPredicate ExitPred = BrInst->getSuccessor(0) == LoopBlk
1583 Instruction *ExitCond = CurLoop->getLatchCmpInst();
1584 Value *ExitLimit = ConstantInt::get(IV->getType(), NewBTC);
1585 IRBuilder<> Builder(ExitCond);
1586 Value *NewExitCond =
1587 Builder.CreateICmp(ExitPred, IV, ExitLimit, "exit.cond");
1588 ExitCond->replaceAllUsesWith(NewExitCond);
1589 deleteDeadInstruction(ExitCond);
1590 }
1591
1592 // Finally, fill the loop with the Sarwate-table-lookup logic, and replace all
1593 // uses of ComputedValue.
1594 //
1595 // Little-endian:
1596 // crc = (crc >> 8) ^ tbl[(iv'th byte of data) ^ (bottom byte of crc)]
1597 // Big-Endian:
1598 // crc = (crc << 8) ^ tbl[(iv'th byte of data) ^ (top byte of crc)]
1599 {
1600 auto LoByte = [](IRBuilderBase &Builder, Value *Op, const Twine &Name) {
1601 Type *OpTy = Op->getType();
1602 unsigned OpBW = OpTy->getIntegerBitWidth();
1603 return OpBW > 8
1604 ? Builder.CreateAnd(Op, ConstantInt::get(OpTy, 0XFF), Name)
1605 : Op;
1606 };
1607 auto HiIdx = [LoByte, CRCBW](IRBuilderBase &Builder, Value *Op,
1608 const Twine &Name) {
1609 Type *OpTy = Op->getType();
1610
1611 // When the bitwidth of the CRC mismatches the Op's bitwidth, we need to
1612 // use the CRC's bitwidth as the reference for shifting right.
1613 return LoByte(Builder,
1614 CRCBW > 8 ? Builder.CreateLShr(
1615 Op, ConstantInt::get(OpTy, CRCBW - 8), Name)
1616 : Op,
1617 Name + ".lo.byte");
1618 };
1619
1620 IRBuilder<> Builder(CurLoop->getHeader(),
1621 CurLoop->getHeader()->getFirstNonPHIIt());
1622
1623 // Create the CRC PHI, and initialize its incoming value to the initial
1624 // value of CRC.
1625 PHINode *CRCPhi = Builder.CreatePHI(CRCTy, 2, "crc");
1626 CRCPhi->addIncoming(Info.LHS, CurLoop->getLoopPreheader());
1627
1628 // CRC is now an evolving variable, initialized to the PHI.
1629 Value *CRC = CRCPhi;
1630
1631 // TableIndexer = ((top|bottom) byte of CRC). It is XOR'ed with (iv'th byte
1632 // of LHSAux), if LHSAux is non-nullptr.
1633 Value *Indexer = CRC;
1634 if (Value *Data = Info.LHSAux) {
1635 Type *DataTy = Data->getType();
1636
1637 // To index into the (iv'th byte of LHSAux), we multiply iv by 8, and we
1638 // shift right by that amount, and take the lo-byte (in the little-endian
1639 // case), or shift left by that amount, and take the hi-idx (in the
1640 // big-endian case).
1641 Value *IVBits = Builder.CreateZExtOrTrunc(
1642 Builder.CreateShl(IV, 3, "iv.bits"), DataTy, "iv.indexer");
1643 Value *DataIndexer =
1644 Info.ByteOrderSwapped
1645 ? Builder.CreateShl(Data, IVBits, "data.indexer")
1646 : Builder.CreateLShr(Data, IVBits, "data.indexer");
1647 Indexer = Builder.CreateXor(
1648 DataIndexer,
1649 Builder.CreateZExtOrTrunc(Indexer, DataTy, "crc.indexer.cast"),
1650 "crc.data.indexer");
1651 }
1652
1653 Indexer = Info.ByteOrderSwapped ? HiIdx(Builder, Indexer, "indexer.hi")
1654 : LoByte(Builder, Indexer, "indexer.lo");
1655
1656 // Always index into a GEP using the index type.
1657 Indexer = Builder.CreateZExt(
1658 Indexer, SE->getDataLayout().getIndexType(GV->getType()),
1659 "indexer.ext");
1660
1661 // CRCTableLd = CRCTable[(iv'th byte of data) ^ (top|bottom) byte of CRC].
1662 Value *CRCTableGEP =
1663 Builder.CreateInBoundsGEP(CRCTy, GV, Indexer, "tbl.ptradd");
1664 Value *CRCTableLd = Builder.CreateLoad(CRCTy, CRCTableGEP, "tbl.ld");
1665
1666 // CRCNext = (CRC (<<|>>) 8) ^ CRCTableLd, or simply CRCTableLd in case of
1667 // CRC-8.
1668 Value *CRCNext = CRCTableLd;
1669 if (CRCBW > 8) {
1670 Value *CRCShift = Info.ByteOrderSwapped
1671 ? Builder.CreateShl(CRC, 8, "crc.be.shift")
1672 : Builder.CreateLShr(CRC, 8, "crc.le.shift");
1673 CRCNext = Builder.CreateXor(CRCShift, CRCTableLd, "crc.next");
1674 }
1675
1676 // Connect the back-edge for the loop, and RAUW the ComputedValue.
1677 CRCPhi->addIncoming(CRCNext, CurLoop->getLoopLatch());
1678 Info.ComputedValue->replaceUsesOutsideBlock(CRCNext,
1679 CurLoop->getLoopLatch());
1680 }
1681
1682 // Cleanup.
1683 {
1684 for (PHINode *PN : Cleanup)
1686 SE->forgetLoop(CurLoop);
1687 }
1688 return true;
1689}
1690
1691bool LoopIdiomRecognize::runOnNoncountableLoop() {
1692 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
1693 << CurLoop->getHeader()->getParent()->getName()
1694 << "] Noncountable Loop %"
1695 << CurLoop->getHeader()->getName() << "\n");
1696
1697 return recognizePopcount() || recognizeAndInsertFFS() ||
1698 recognizeShiftUntilBitTest() || recognizeShiftUntilZero() ||
1699 recognizeShiftUntilLessThan() || recognizeAndInsertStrLen();
1700}
1701
1702/// Check if the given conditional branch is based on the comparison between
1703/// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
1704/// true), the control yields to the loop entry. If the branch matches the
1705/// behavior, the variable involved in the comparison is returned. This function
1706/// will be called to see if the precondition and postcondition of the loop are
1707/// in desirable form.
1709 bool JmpOnZero = false) {
1710 if (!BI || !BI->isConditional())
1711 return nullptr;
1712
1714 if (!Cond)
1715 return nullptr;
1716
1717 auto *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1718 if (!CmpZero || !CmpZero->isZero())
1719 return nullptr;
1720
1721 BasicBlock *TrueSucc = BI->getSuccessor(0);
1722 BasicBlock *FalseSucc = BI->getSuccessor(1);
1723 if (JmpOnZero)
1724 std::swap(TrueSucc, FalseSucc);
1725
1726 ICmpInst::Predicate Pred = Cond->getPredicate();
1727 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
1728 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
1729 return Cond->getOperand(0);
1730
1731 return nullptr;
1732}
1733
1734namespace {
1735
1736class StrlenVerifier {
1737public:
1738 explicit StrlenVerifier(const Loop *CurLoop, ScalarEvolution *SE,
1739 const TargetLibraryInfo *TLI)
1740 : CurLoop(CurLoop), SE(SE), TLI(TLI) {}
1741
1742 bool isValidStrlenIdiom() {
1743 // Give up if the loop has multiple blocks, multiple backedges, or
1744 // multiple exit blocks
1745 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1 ||
1746 !CurLoop->getUniqueExitBlock())
1747 return false;
1748
1749 // It should have a preheader and a branch instruction.
1750 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1751 if (!Preheader)
1752 return false;
1753
1754 BranchInst *EntryBI = dyn_cast<BranchInst>(Preheader->getTerminator());
1755 if (!EntryBI)
1756 return false;
1757
1758 // The loop exit must be conditioned on an icmp with 0 the null terminator.
1759 // The icmp operand has to be a load on some SSA reg that increments
1760 // by 1 in the loop.
1761 BasicBlock *LoopBody = *CurLoop->block_begin();
1762
1763 // Skip if the body is too big as it most likely is not a strlen idiom.
1764 if (!LoopBody || LoopBody->size() >= 15)
1765 return false;
1766
1767 BranchInst *LoopTerm = dyn_cast<BranchInst>(LoopBody->getTerminator());
1768 Value *LoopCond = matchCondition(LoopTerm, LoopBody);
1769 if (!LoopCond)
1770 return false;
1771
1772 LoadInst *LoopLoad = dyn_cast<LoadInst>(LoopCond);
1773 if (!LoopLoad || LoopLoad->getPointerAddressSpace() != 0)
1774 return false;
1775
1776 OperandType = LoopLoad->getType();
1777 if (!OperandType || !OperandType->isIntegerTy())
1778 return false;
1779
1780 // See if the pointer expression is an AddRec with constant step a of form
1781 // ({n,+,a}) where a is the width of the char type.
1782 Value *IncPtr = LoopLoad->getPointerOperand();
1783 const SCEV *LoadEv = SE->getSCEV(IncPtr);
1784 const APInt *Step;
1785 if (!match(LoadEv,
1786 m_scev_AffineAddRec(m_SCEV(LoadBaseEv), m_scev_APInt(Step))))
1787 return false;
1788
1789 LLVM_DEBUG(dbgs() << "pointer load scev: " << *LoadEv << "\n");
1790
1791 unsigned StepSize = Step->getZExtValue();
1792
1793 // Verify that StepSize is consistent with platform char width.
1794 OpWidth = OperandType->getIntegerBitWidth();
1795 unsigned WcharSize = TLI->getWCharSize(*LoopLoad->getModule());
1796 if (OpWidth != StepSize * 8)
1797 return false;
1798 if (OpWidth != 8 && OpWidth != 16 && OpWidth != 32)
1799 return false;
1800 if (OpWidth >= 16)
1801 if (OpWidth != WcharSize * 8)
1802 return false;
1803
1804 // Scan every instruction in the loop to ensure there are no side effects.
1805 for (Instruction &I : *LoopBody)
1806 if (I.mayHaveSideEffects())
1807 return false;
1808
1809 BasicBlock *LoopExitBB = CurLoop->getExitBlock();
1810 if (!LoopExitBB)
1811 return false;
1812
1813 for (PHINode &PN : LoopExitBB->phis()) {
1814 if (!SE->isSCEVable(PN.getType()))
1815 return false;
1816
1817 const SCEV *Ev = SE->getSCEV(&PN);
1818 if (!Ev)
1819 return false;
1820
1821 LLVM_DEBUG(dbgs() << "loop exit phi scev: " << *Ev << "\n");
1822
1823 // Since we verified that the loop trip count will be a valid strlen
1824 // idiom, we can expand all lcssa phi with {n,+,1} as (n + strlen) and use
1825 // SCEVExpander materialize the loop output.
1826 const SCEVAddRecExpr *AddRecEv = dyn_cast<SCEVAddRecExpr>(Ev);
1827 if (!AddRecEv || !AddRecEv->isAffine())
1828 return false;
1829
1830 // We only want RecAddExpr with recurrence step that is constant. This
1831 // is good enough for all the idioms we want to recognize. Later we expand
1832 // and materialize the recurrence as {base,+,a} -> (base + a * strlen)
1833 if (!isa<SCEVConstant>(AddRecEv->getStepRecurrence(*SE)))
1834 return false;
1835 }
1836
1837 return true;
1838 }
1839
1840public:
1841 const Loop *CurLoop;
1842 ScalarEvolution *SE;
1843 const TargetLibraryInfo *TLI;
1844
1845 unsigned OpWidth;
1846 ConstantInt *StepSizeCI;
1847 const SCEV *LoadBaseEv;
1849};
1850
1851} // namespace
1852
1853/// The Strlen Idiom we are trying to detect has the following structure
1854///
1855/// preheader:
1856/// ...
1857/// br label %body, ...
1858///
1859/// body:
1860/// ... ; %0 is incremented by a gep
1861/// %1 = load i8, ptr %0, align 1
1862/// %2 = icmp eq i8 %1, 0
1863/// br i1 %2, label %exit, label %body
1864///
1865/// exit:
1866/// %lcssa = phi [%0, %body], ...
1867///
1868/// We expect the strlen idiom to have a load of a character type that
1869/// is compared against '\0', and such load pointer operand must have scev
1870/// expression of the form {%str,+,c} where c is a ConstantInt of the
1871/// appropiate character width for the idiom, and %str is the base of the string
1872/// And, that all lcssa phis have the form {...,+,n} where n is a constant,
1873///
1874/// When transforming the output of the strlen idiom, the lccsa phi are
1875/// expanded using SCEVExpander as {base scev,+,a} -> (base scev + a * strlen)
1876/// and all subsequent uses are replaced. For example,
1877///
1878/// \code{.c}
1879/// const char* base = str;
1880/// while (*str != '\0')
1881/// ++str;
1882/// size_t result = str - base;
1883/// \endcode
1884///
1885/// will be transformed as follows: The idiom will be replaced by a strlen
1886/// computation to compute the address of the null terminator of the string.
1887///
1888/// \code{.c}
1889/// const char* base = str;
1890/// const char* end = base + strlen(str);
1891/// size_t result = end - base;
1892/// \endcode
1893///
1894/// In the case we index by an induction variable, as long as the induction
1895/// variable has a constant int increment, we can replace all such indvars
1896/// with the closed form computation of strlen
1897///
1898/// \code{.c}
1899/// size_t i = 0;
1900/// while (str[i] != '\0')
1901/// ++i;
1902/// size_t result = i;
1903/// \endcode
1904///
1905/// Will be replaced by
1906///
1907/// \code{.c}
1908/// size_t i = 0 + strlen(str);
1909/// size_t result = i;
1910/// \endcode
1911///
1912bool LoopIdiomRecognize::recognizeAndInsertStrLen() {
1913 if (DisableLIRP::All)
1914 return false;
1915
1916 StrlenVerifier Verifier(CurLoop, SE, TLI);
1917
1918 if (!Verifier.isValidStrlenIdiom())
1919 return false;
1920
1921 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1922 BasicBlock *LoopBody = *CurLoop->block_begin();
1923 BasicBlock *LoopExitBB = CurLoop->getExitBlock();
1924 BranchInst *LoopTerm = dyn_cast<BranchInst>(LoopBody->getTerminator());
1925 assert(Preheader && LoopBody && LoopExitBB && LoopTerm &&
1926 "Should be verified to be valid by StrlenVerifier");
1927
1928 if (Verifier.OpWidth == 8) {
1930 return false;
1931 if (!isLibFuncEmittable(Preheader->getModule(), TLI, LibFunc_strlen))
1932 return false;
1933 } else {
1935 return false;
1936 if (!isLibFuncEmittable(Preheader->getModule(), TLI, LibFunc_wcslen))
1937 return false;
1938 }
1939
1940 IRBuilder<> Builder(Preheader->getTerminator());
1941 Builder.SetCurrentDebugLocation(CurLoop->getStartLoc());
1942 SCEVExpander Expander(*SE, Preheader->getModule()->getDataLayout(),
1943 "strlen_idiom");
1944 Value *MaterialzedBase = Expander.expandCodeFor(
1945 Verifier.LoadBaseEv, Verifier.LoadBaseEv->getType(),
1946 Builder.GetInsertPoint());
1947
1948 Value *StrLenFunc = nullptr;
1949 if (Verifier.OpWidth == 8) {
1950 StrLenFunc = emitStrLen(MaterialzedBase, Builder, *DL, TLI);
1951 } else {
1952 StrLenFunc = emitWcsLen(MaterialzedBase, Builder, *DL, TLI);
1953 }
1954 assert(StrLenFunc && "Failed to emit strlen function.");
1955
1956 const SCEV *StrlenEv = SE->getSCEV(StrLenFunc);
1958 for (PHINode &PN : LoopExitBB->phis()) {
1959 // We can now materialize the loop output as all phi have scev {base,+,a}.
1960 // We expand the phi as:
1961 // %strlen = call i64 @strlen(%str)
1962 // %phi.new = base expression + step * %strlen
1963 const SCEV *Ev = SE->getSCEV(&PN);
1964 const SCEVAddRecExpr *AddRecEv = dyn_cast<SCEVAddRecExpr>(Ev);
1965 const SCEVConstant *Step =
1967 const SCEV *Base = AddRecEv->getStart();
1968
1969 // It is safe to truncate to base since if base is narrower than size_t
1970 // the equivalent user code will have to truncate anyways.
1971 const SCEV *NewEv = SE->getAddExpr(
1973 StrlenEv, Base->getType())));
1974
1975 Value *MaterializedPHI = Expander.expandCodeFor(NewEv, NewEv->getType(),
1976 Builder.GetInsertPoint());
1977 Expander.clear();
1978 PN.replaceAllUsesWith(MaterializedPHI);
1979 Cleanup.push_back(&PN);
1980 }
1981
1982 // All LCSSA Loop Phi are dead, the left over dead loop body can be cleaned
1983 // up by later passes
1984 for (PHINode *PN : Cleanup)
1986
1987 // LoopDeletion only delete invariant loops with known trip-count. We can
1988 // update the condition so it will reliablely delete the invariant loop
1989 assert(LoopTerm->getNumSuccessors() == 2 &&
1990 (LoopTerm->getSuccessor(0) == LoopBody ||
1991 LoopTerm->getSuccessor(1) == LoopBody) &&
1992 "loop body must have a successor that is it self");
1993 ConstantInt *NewLoopCond = LoopTerm->getSuccessor(0) == LoopBody
1994 ? Builder.getFalse()
1995 : Builder.getTrue();
1996 LoopTerm->setCondition(NewLoopCond);
1997 SE->forgetLoop(CurLoop);
1998
1999 ++NumStrLen;
2000 LLVM_DEBUG(dbgs() << " Formed strlen idiom: " << *StrLenFunc << "\n");
2001 ORE.emit([&]() {
2002 return OptimizationRemark(DEBUG_TYPE, "recognizeAndInsertStrLen",
2003 CurLoop->getStartLoc(), Preheader)
2004 << "Transformed " << StrLenFunc->getName() << " loop idiom";
2005 });
2006
2007 return true;
2008}
2009
2010/// Check if the given conditional branch is based on an unsigned less-than
2011/// comparison between a variable and a constant, and if the comparison is false
2012/// the control yields to the loop entry. If the branch matches the behaviour,
2013/// the variable involved in the comparison is returned.
2015 APInt &Threshold) {
2016 if (!BI || !BI->isConditional())
2017 return nullptr;
2018
2020 if (!Cond)
2021 return nullptr;
2022
2023 ConstantInt *CmpConst = dyn_cast<ConstantInt>(Cond->getOperand(1));
2024 if (!CmpConst)
2025 return nullptr;
2026
2027 BasicBlock *FalseSucc = BI->getSuccessor(1);
2028 ICmpInst::Predicate Pred = Cond->getPredicate();
2029
2030 if (Pred == ICmpInst::ICMP_ULT && FalseSucc == LoopEntry) {
2031 Threshold = CmpConst->getValue();
2032 return Cond->getOperand(0);
2033 }
2034
2035 return nullptr;
2036}
2037
2038// Check if the recurrence variable `VarX` is in the right form to create
2039// the idiom. Returns the value coerced to a PHINode if so.
2041 BasicBlock *LoopEntry) {
2042 auto *PhiX = dyn_cast<PHINode>(VarX);
2043 if (PhiX && PhiX->getParent() == LoopEntry &&
2044 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
2045 return PhiX;
2046 return nullptr;
2047}
2048
2049/// Return true if the idiom is detected in the loop.
2050///
2051/// Additionally:
2052/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
2053/// or nullptr if there is no such.
2054/// 2) \p CntPhi is set to the corresponding phi node
2055/// or nullptr if there is no such.
2056/// 3) \p InitX is set to the value whose CTLZ could be used.
2057/// 4) \p DefX is set to the instruction calculating Loop exit condition.
2058/// 5) \p Threshold is set to the constant involved in the unsigned less-than
2059/// comparison.
2060///
2061/// The core idiom we are trying to detect is:
2062/// \code
2063/// if (x0 < 2)
2064/// goto loop-exit // the precondition of the loop
2065/// cnt0 = init-val
2066/// do {
2067/// x = phi (x0, x.next); //PhiX
2068/// cnt = phi (cnt0, cnt.next)
2069///
2070/// cnt.next = cnt + 1;
2071/// ...
2072/// x.next = x >> 1; // DefX
2073/// } while (x >= 4)
2074/// loop-exit:
2075/// \endcode
2077 Intrinsic::ID &IntrinID,
2078 Value *&InitX, Instruction *&CntInst,
2079 PHINode *&CntPhi, Instruction *&DefX,
2080 APInt &Threshold) {
2081 BasicBlock *LoopEntry;
2082
2083 DefX = nullptr;
2084 CntInst = nullptr;
2085 CntPhi = nullptr;
2086 LoopEntry = *(CurLoop->block_begin());
2087
2088 // step 1: Check if the loop-back branch is in desirable form.
2090 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry,
2091 Threshold))
2092 DefX = dyn_cast<Instruction>(T);
2093 else
2094 return false;
2095
2096 // step 2: Check the recurrence of variable X
2097 if (!DefX || !isa<PHINode>(DefX))
2098 return false;
2099
2100 PHINode *VarPhi = cast<PHINode>(DefX);
2101 int Idx = VarPhi->getBasicBlockIndex(LoopEntry);
2102 if (Idx == -1)
2103 return false;
2104
2105 DefX = dyn_cast<Instruction>(VarPhi->getIncomingValue(Idx));
2106 if (!DefX || DefX->getNumOperands() == 0 || DefX->getOperand(0) != VarPhi)
2107 return false;
2108
2109 // step 3: detect instructions corresponding to "x.next = x >> 1"
2110 if (DefX->getOpcode() != Instruction::LShr)
2111 return false;
2112
2113 IntrinID = Intrinsic::ctlz;
2115 if (!Shft || !Shft->isOne())
2116 return false;
2117
2118 InitX = VarPhi->getIncomingValueForBlock(CurLoop->getLoopPreheader());
2119
2120 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
2121 // or cnt.next = cnt + -1.
2122 // TODO: We can skip the step. If loop trip count is known (CTLZ),
2123 // then all uses of "cnt.next" could be optimized to the trip count
2124 // plus "cnt0". Currently it is not optimized.
2125 // This step could be used to detect POPCNT instruction:
2126 // cnt.next = cnt + (x.next & 1)
2127 for (Instruction &Inst :
2128 llvm::make_range(LoopEntry->getFirstNonPHIIt(), LoopEntry->end())) {
2129 if (Inst.getOpcode() != Instruction::Add)
2130 continue;
2131
2133 if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
2134 continue;
2135
2136 PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
2137 if (!Phi)
2138 continue;
2139
2140 CntInst = &Inst;
2141 CntPhi = Phi;
2142 break;
2143 }
2144 if (!CntInst)
2145 return false;
2146
2147 return true;
2148}
2149
2150/// Return true iff the idiom is detected in the loop.
2151///
2152/// Additionally:
2153/// 1) \p CntInst is set to the instruction counting the population bit.
2154/// 2) \p CntPhi is set to the corresponding phi node.
2155/// 3) \p Var is set to the value whose population bits are being counted.
2156///
2157/// The core idiom we are trying to detect is:
2158/// \code
2159/// if (x0 != 0)
2160/// goto loop-exit // the precondition of the loop
2161/// cnt0 = init-val;
2162/// do {
2163/// x1 = phi (x0, x2);
2164/// cnt1 = phi(cnt0, cnt2);
2165///
2166/// cnt2 = cnt1 + 1;
2167/// ...
2168/// x2 = x1 & (x1 - 1);
2169/// ...
2170/// } while(x != 0);
2171///
2172/// loop-exit:
2173/// \endcode
2174static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
2175 Instruction *&CntInst, PHINode *&CntPhi,
2176 Value *&Var) {
2177 // step 1: Check to see if the look-back branch match this pattern:
2178 // "if (a!=0) goto loop-entry".
2179 BasicBlock *LoopEntry;
2180 Instruction *DefX2, *CountInst;
2181 Value *VarX1, *VarX0;
2182 PHINode *PhiX, *CountPhi;
2183
2184 DefX2 = CountInst = nullptr;
2185 VarX1 = VarX0 = nullptr;
2186 PhiX = CountPhi = nullptr;
2187 LoopEntry = *(CurLoop->block_begin());
2188
2189 // step 1: Check if the loop-back branch is in desirable form.
2190 {
2191 if (Value *T = matchCondition(
2192 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
2193 DefX2 = dyn_cast<Instruction>(T);
2194 else
2195 return false;
2196 }
2197
2198 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
2199 {
2200 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
2201 return false;
2202
2203 BinaryOperator *SubOneOp;
2204
2205 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
2206 VarX1 = DefX2->getOperand(1);
2207 else {
2208 VarX1 = DefX2->getOperand(0);
2209 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
2210 }
2211 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
2212 return false;
2213
2214 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
2215 if (!Dec ||
2216 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
2217 (SubOneOp->getOpcode() == Instruction::Add &&
2218 Dec->isMinusOne()))) {
2219 return false;
2220 }
2221 }
2222
2223 // step 3: Check the recurrence of variable X
2224 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
2225 if (!PhiX)
2226 return false;
2227
2228 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
2229 {
2230 CountInst = nullptr;
2231 for (Instruction &Inst :
2232 llvm::make_range(LoopEntry->getFirstNonPHIIt(), LoopEntry->end())) {
2233 if (Inst.getOpcode() != Instruction::Add)
2234 continue;
2235
2237 if (!Inc || !Inc->isOne())
2238 continue;
2239
2240 PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
2241 if (!Phi)
2242 continue;
2243
2244 // Check if the result of the instruction is live of the loop.
2245 bool LiveOutLoop = false;
2246 for (User *U : Inst.users()) {
2247 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
2248 LiveOutLoop = true;
2249 break;
2250 }
2251 }
2252
2253 if (LiveOutLoop) {
2254 CountInst = &Inst;
2255 CountPhi = Phi;
2256 break;
2257 }
2258 }
2259
2260 if (!CountInst)
2261 return false;
2262 }
2263
2264 // step 5: check if the precondition is in this form:
2265 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
2266 {
2267 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
2268 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
2269 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
2270 return false;
2271
2272 CntInst = CountInst;
2273 CntPhi = CountPhi;
2274 Var = T;
2275 }
2276
2277 return true;
2278}
2279
2280/// Return true if the idiom is detected in the loop.
2281///
2282/// Additionally:
2283/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
2284/// or nullptr if there is no such.
2285/// 2) \p CntPhi is set to the corresponding phi node
2286/// or nullptr if there is no such.
2287/// 3) \p Var is set to the value whose CTLZ could be used.
2288/// 4) \p DefX is set to the instruction calculating Loop exit condition.
2289///
2290/// The core idiom we are trying to detect is:
2291/// \code
2292/// if (x0 == 0)
2293/// goto loop-exit // the precondition of the loop
2294/// cnt0 = init-val;
2295/// do {
2296/// x = phi (x0, x.next); //PhiX
2297/// cnt = phi(cnt0, cnt.next);
2298///
2299/// cnt.next = cnt + 1;
2300/// ...
2301/// x.next = x >> 1; // DefX
2302/// ...
2303/// } while(x.next != 0);
2304///
2305/// loop-exit:
2306/// \endcode
2307static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
2308 Intrinsic::ID &IntrinID, Value *&InitX,
2309 Instruction *&CntInst, PHINode *&CntPhi,
2310 Instruction *&DefX) {
2311 BasicBlock *LoopEntry;
2312 Value *VarX = nullptr;
2313
2314 DefX = nullptr;
2315 CntInst = nullptr;
2316 CntPhi = nullptr;
2317 LoopEntry = *(CurLoop->block_begin());
2318
2319 // step 1: Check if the loop-back branch is in desirable form.
2320 if (Value *T = matchCondition(
2321 dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
2322 DefX = dyn_cast<Instruction>(T);
2323 else
2324 return false;
2325
2326 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
2327 if (!DefX || !DefX->isShift())
2328 return false;
2329 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
2330 Intrinsic::ctlz;
2332 if (!Shft || !Shft->isOne())
2333 return false;
2334 VarX = DefX->getOperand(0);
2335
2336 // step 3: Check the recurrence of variable X
2337 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
2338 if (!PhiX)
2339 return false;
2340
2341 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
2342
2343 // Make sure the initial value can't be negative otherwise the ashr in the
2344 // loop might never reach zero which would make the loop infinite.
2345 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
2346 return false;
2347
2348 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
2349 // or cnt.next = cnt + -1.
2350 // TODO: We can skip the step. If loop trip count is known (CTLZ),
2351 // then all uses of "cnt.next" could be optimized to the trip count
2352 // plus "cnt0". Currently it is not optimized.
2353 // This step could be used to detect POPCNT instruction:
2354 // cnt.next = cnt + (x.next & 1)
2355 for (Instruction &Inst :
2356 llvm::make_range(LoopEntry->getFirstNonPHIIt(), LoopEntry->end())) {
2357 if (Inst.getOpcode() != Instruction::Add)
2358 continue;
2359
2361 if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
2362 continue;
2363
2364 PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
2365 if (!Phi)
2366 continue;
2367
2368 CntInst = &Inst;
2369 CntPhi = Phi;
2370 break;
2371 }
2372 if (!CntInst)
2373 return false;
2374
2375 return true;
2376}
2377
2378// Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
2379// profitable if we delete the loop.
2380bool LoopIdiomRecognize::isProfitableToInsertFFS(Intrinsic::ID IntrinID,
2381 Value *InitX, bool ZeroCheck,
2382 size_t CanonicalSize) {
2383 const Value *Args[] = {InitX,
2384 ConstantInt::getBool(InitX->getContext(), ZeroCheck)};
2385
2386 // @llvm.dbg doesn't count as they have no semantic effect.
2387 auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug();
2388 uint32_t HeaderSize =
2389 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());
2390
2391 IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args);
2392 InstructionCost Cost = TTI->getIntrinsicInstrCost(
2394 if (HeaderSize != CanonicalSize && Cost > TargetTransformInfo::TCC_Basic)
2395 return false;
2396
2397 return true;
2398}
2399
2400/// Convert CTLZ / CTTZ idiom loop into countable loop.
2401/// If CTLZ / CTTZ inserted as a new trip count returns true; otherwise,
2402/// returns false.
2403bool LoopIdiomRecognize::insertFFSIfProfitable(Intrinsic::ID IntrinID,
2404 Value *InitX, Instruction *DefX,
2405 PHINode *CntPhi,
2406 Instruction *CntInst) {
2407 bool IsCntPhiUsedOutsideLoop = false;
2408 for (User *U : CntPhi->users())
2409 if (!CurLoop->contains(cast<Instruction>(U))) {
2410 IsCntPhiUsedOutsideLoop = true;
2411 break;
2412 }
2413 bool IsCntInstUsedOutsideLoop = false;
2414 for (User *U : CntInst->users())
2415 if (!CurLoop->contains(cast<Instruction>(U))) {
2416 IsCntInstUsedOutsideLoop = true;
2417 break;
2418 }
2419 // If both CntInst and CntPhi are used outside the loop the profitability
2420 // is questionable.
2421 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
2422 return false;
2423
2424 // For some CPUs result of CTLZ(X) intrinsic is undefined
2425 // when X is 0. If we can not guarantee X != 0, we need to check this
2426 // when expand.
2427 bool ZeroCheck = false;
2428 // It is safe to assume Preheader exist as it was checked in
2429 // parent function RunOnLoop.
2430 BasicBlock *PH = CurLoop->getLoopPreheader();
2431
2432 // If we are using the count instruction outside the loop, make sure we
2433 // have a zero check as a precondition. Without the check the loop would run
2434 // one iteration for before any check of the input value. This means 0 and 1
2435 // would have identical behavior in the original loop and thus
2436 if (!IsCntPhiUsedOutsideLoop) {
2437 auto *PreCondBB = PH->getSinglePredecessor();
2438 if (!PreCondBB)
2439 return false;
2440 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
2441 if (!PreCondBI)
2442 return false;
2443 if (matchCondition(PreCondBI, PH) != InitX)
2444 return false;
2445 ZeroCheck = true;
2446 }
2447
2448 // FFS idiom loop has only 6 instructions:
2449 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
2450 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
2451 // %shr = ashr %n.addr.0, 1
2452 // %tobool = icmp eq %shr, 0
2453 // %inc = add nsw %i.0, 1
2454 // br i1 %tobool
2455 size_t IdiomCanonicalSize = 6;
2456 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
2457 return false;
2458
2459 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
2460 DefX->getDebugLoc(), ZeroCheck,
2461 IsCntPhiUsedOutsideLoop);
2462 return true;
2463}
2464
2465/// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
2466/// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
2467/// trip count returns true; otherwise, returns false.
2468bool LoopIdiomRecognize::recognizeAndInsertFFS() {
2469 // Give up if the loop has multiple blocks or multiple backedges.
2470 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
2471 return false;
2472
2473 Intrinsic::ID IntrinID;
2474 Value *InitX;
2475 Instruction *DefX = nullptr;
2476 PHINode *CntPhi = nullptr;
2477 Instruction *CntInst = nullptr;
2478
2479 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX, CntInst, CntPhi,
2480 DefX))
2481 return false;
2482
2483 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2484}
2485
2486bool LoopIdiomRecognize::recognizeShiftUntilLessThan() {
2487 // Give up if the loop has multiple blocks or multiple backedges.
2488 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
2489 return false;
2490
2491 Intrinsic::ID IntrinID;
2492 Value *InitX;
2493 Instruction *DefX = nullptr;
2494 PHINode *CntPhi = nullptr;
2495 Instruction *CntInst = nullptr;
2496
2497 APInt LoopThreshold;
2498 if (!detectShiftUntilLessThanIdiom(CurLoop, *DL, IntrinID, InitX, CntInst,
2499 CntPhi, DefX, LoopThreshold))
2500 return false;
2501
2502 if (LoopThreshold == 2) {
2503 // Treat as regular FFS.
2504 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2505 }
2506
2507 // Look for Floor Log2 Idiom.
2508 if (LoopThreshold != 4)
2509 return false;
2510
2511 // Abort if CntPhi is used outside of the loop.
2512 for (User *U : CntPhi->users())
2513 if (!CurLoop->contains(cast<Instruction>(U)))
2514 return false;
2515
2516 // It is safe to assume Preheader exist as it was checked in
2517 // parent function RunOnLoop.
2518 BasicBlock *PH = CurLoop->getLoopPreheader();
2519 auto *PreCondBB = PH->getSinglePredecessor();
2520 if (!PreCondBB)
2521 return false;
2522 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
2523 if (!PreCondBI)
2524 return false;
2525
2526 APInt PreLoopThreshold;
2527 if (matchShiftULTCondition(PreCondBI, PH, PreLoopThreshold) != InitX ||
2528 PreLoopThreshold != 2)
2529 return false;
2530
2531 bool ZeroCheck = true;
2532
2533 // the loop has only 6 instructions:
2534 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
2535 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
2536 // %shr = ashr %n.addr.0, 1
2537 // %tobool = icmp ult %n.addr.0, C
2538 // %inc = add nsw %i.0, 1
2539 // br i1 %tobool
2540 size_t IdiomCanonicalSize = 6;
2541 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
2542 return false;
2543
2544 // log2(x) = w − 1 − clz(x)
2545 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
2546 DefX->getDebugLoc(), ZeroCheck,
2547 /*IsCntPhiUsedOutsideLoop=*/false,
2548 /*InsertSub=*/true);
2549 return true;
2550}
2551
2552/// Recognizes a population count idiom in a non-countable loop.
2553///
2554/// If detected, transforms the relevant code to issue the popcount intrinsic
2555/// function call, and returns true; otherwise, returns false.
2556bool LoopIdiomRecognize::recognizePopcount() {
2557 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
2558 return false;
2559
2560 // Counting population are usually conducted by few arithmetic instructions.
2561 // Such instructions can be easily "absorbed" by vacant slots in a
2562 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
2563 // in a compact loop.
2564
2565 // Give up if the loop has multiple blocks or multiple backedges.
2566 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
2567 return false;
2568
2569 BasicBlock *LoopBody = *(CurLoop->block_begin());
2570 if (LoopBody->size() >= 20) {
2571 // The loop is too big, bail out.
2572 return false;
2573 }
2574
2575 // It should have a preheader containing nothing but an unconditional branch.
2576 BasicBlock *PH = CurLoop->getLoopPreheader();
2577 if (!PH || &PH->front() != PH->getTerminator())
2578 return false;
2579 auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
2580 if (!EntryBI || EntryBI->isConditional())
2581 return false;
2582
2583 // It should have a precondition block where the generated popcount intrinsic
2584 // function can be inserted.
2585 auto *PreCondBB = PH->getSinglePredecessor();
2586 if (!PreCondBB)
2587 return false;
2588 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
2589 if (!PreCondBI || PreCondBI->isUnconditional())
2590 return false;
2591
2592 Instruction *CntInst;
2593 PHINode *CntPhi;
2594 Value *Val;
2595 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
2596 return false;
2597
2598 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
2599 return true;
2600}
2601
2603 const DebugLoc &DL) {
2604 Value *Ops[] = {Val};
2605 Type *Tys[] = {Val->getType()};
2606
2607 CallInst *CI = IRBuilder.CreateIntrinsic(Intrinsic::ctpop, Tys, Ops);
2608 CI->setDebugLoc(DL);
2609
2610 return CI;
2611}
2612
2614 const DebugLoc &DL, bool ZeroCheck,
2615 Intrinsic::ID IID) {
2616 Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)};
2617 Type *Tys[] = {Val->getType()};
2618
2619 CallInst *CI = IRBuilder.CreateIntrinsic(IID, Tys, Ops);
2620 CI->setDebugLoc(DL);
2621
2622 return CI;
2623}
2624
2625/// Transform the following loop (Using CTLZ, CTTZ is similar):
2626/// loop:
2627/// CntPhi = PHI [Cnt0, CntInst]
2628/// PhiX = PHI [InitX, DefX]
2629/// CntInst = CntPhi + 1
2630/// DefX = PhiX >> 1
2631/// LOOP_BODY
2632/// Br: loop if (DefX != 0)
2633/// Use(CntPhi) or Use(CntInst)
2634///
2635/// Into:
2636/// If CntPhi used outside the loop:
2637/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
2638/// Count = CountPrev + 1
2639/// else
2640/// Count = BitWidth(InitX) - CTLZ(InitX)
2641/// loop:
2642/// CntPhi = PHI [Cnt0, CntInst]
2643/// PhiX = PHI [InitX, DefX]
2644/// PhiCount = PHI [Count, Dec]
2645/// CntInst = CntPhi + 1
2646/// DefX = PhiX >> 1
2647/// Dec = PhiCount - 1
2648/// LOOP_BODY
2649/// Br: loop if (Dec != 0)
2650/// Use(CountPrev + Cnt0) // Use(CntPhi)
2651/// or
2652/// Use(Count + Cnt0) // Use(CntInst)
2653///
2654/// If LOOP_BODY is empty the loop will be deleted.
2655/// If CntInst and DefX are not used in LOOP_BODY they will be removed.
2656void LoopIdiomRecognize::transformLoopToCountable(
2657 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
2658 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
2659 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop, bool InsertSub) {
2660 BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
2661
2662 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
2663 IRBuilder<> Builder(PreheaderBr);
2664 Builder.SetCurrentDebugLocation(DL);
2665
2666 // If there are no uses of CntPhi crate:
2667 // Count = BitWidth - CTLZ(InitX);
2668 // NewCount = Count;
2669 // If there are uses of CntPhi create:
2670 // NewCount = BitWidth - CTLZ(InitX >> 1);
2671 // Count = NewCount + 1;
2672 Value *InitXNext;
2673 if (IsCntPhiUsedOutsideLoop) {
2674 if (DefX->getOpcode() == Instruction::AShr)
2675 InitXNext = Builder.CreateAShr(InitX, 1);
2676 else if (DefX->getOpcode() == Instruction::LShr)
2677 InitXNext = Builder.CreateLShr(InitX, 1);
2678 else if (DefX->getOpcode() == Instruction::Shl) // cttz
2679 InitXNext = Builder.CreateShl(InitX, 1);
2680 else
2681 llvm_unreachable("Unexpected opcode!");
2682 } else
2683 InitXNext = InitX;
2684 Value *Count =
2685 createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
2686 Type *CountTy = Count->getType();
2687 Count = Builder.CreateSub(
2688 ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count);
2689 if (InsertSub)
2690 Count = Builder.CreateSub(Count, ConstantInt::get(CountTy, 1));
2691 Value *NewCount = Count;
2692 if (IsCntPhiUsedOutsideLoop)
2693 Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1));
2694
2695 NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType());
2696
2697 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
2698 if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) {
2699 // If the counter was being incremented in the loop, add NewCount to the
2700 // counter's initial value, but only if the initial value is not zero.
2701 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
2702 if (!InitConst || !InitConst->isZero())
2703 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
2704 } else {
2705 // If the count was being decremented in the loop, subtract NewCount from
2706 // the counter's initial value.
2707 NewCount = Builder.CreateSub(CntInitVal, NewCount);
2708 }
2709
2710 // Step 2: Insert new IV and loop condition:
2711 // loop:
2712 // ...
2713 // PhiCount = PHI [Count, Dec]
2714 // ...
2715 // Dec = PhiCount - 1
2716 // ...
2717 // Br: loop if (Dec != 0)
2718 BasicBlock *Body = *(CurLoop->block_begin());
2719 auto *LbBr = cast<BranchInst>(Body->getTerminator());
2720 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
2721
2722 PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi");
2723 TcPhi->insertBefore(Body->begin());
2724
2725 Builder.SetInsertPoint(LbCond);
2726 Instruction *TcDec = cast<Instruction>(Builder.CreateSub(
2727 TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true));
2728
2729 TcPhi->addIncoming(Count, Preheader);
2730 TcPhi->addIncoming(TcDec, Body);
2731
2732 CmpInst::Predicate Pred =
2733 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
2734 LbCond->setPredicate(Pred);
2735 LbCond->setOperand(0, TcDec);
2736 LbCond->setOperand(1, ConstantInt::get(CountTy, 0));
2737
2738 // Step 3: All the references to the original counter outside
2739 // the loop are replaced with the NewCount
2740 if (IsCntPhiUsedOutsideLoop)
2741 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
2742 else
2743 CntInst->replaceUsesOutsideBlock(NewCount, Body);
2744
2745 // step 4: Forget the "non-computable" trip-count SCEV associated with the
2746 // loop. The loop would otherwise not be deleted even if it becomes empty.
2747 SE->forgetLoop(CurLoop);
2748}
2749
2750void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
2751 Instruction *CntInst,
2752 PHINode *CntPhi, Value *Var) {
2753 BasicBlock *PreHead = CurLoop->getLoopPreheader();
2754 auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());
2755 const DebugLoc &DL = CntInst->getDebugLoc();
2756
2757 // Assuming before transformation, the loop is following:
2758 // if (x) // the precondition
2759 // do { cnt++; x &= x - 1; } while(x);
2760
2761 // Step 1: Insert the ctpop instruction at the end of the precondition block
2762 IRBuilder<> Builder(PreCondBr);
2763 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
2764 {
2765 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
2766 NewCount = PopCntZext =
2767 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
2768
2769 if (NewCount != PopCnt)
2770 (cast<Instruction>(NewCount))->setDebugLoc(DL);
2771
2772 // TripCnt is exactly the number of iterations the loop has
2773 TripCnt = NewCount;
2774
2775 // If the population counter's initial value is not zero, insert Add Inst.
2776 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
2777 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
2778 if (!InitConst || !InitConst->isZero()) {
2779 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
2780 (cast<Instruction>(NewCount))->setDebugLoc(DL);
2781 }
2782 }
2783
2784 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
2785 // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
2786 // function would be partial dead code, and downstream passes will drag
2787 // it back from the precondition block to the preheader.
2788 {
2789 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
2790
2791 Value *Opnd0 = PopCntZext;
2792 Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
2793 if (PreCond->getOperand(0) != Var)
2794 std::swap(Opnd0, Opnd1);
2795
2796 ICmpInst *NewPreCond = cast<ICmpInst>(
2797 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
2798 PreCondBr->setCondition(NewPreCond);
2799
2801 }
2802
2803 // Step 3: Note that the population count is exactly the trip count of the
2804 // loop in question, which enable us to convert the loop from noncountable
2805 // loop into a countable one. The benefit is twofold:
2806 //
2807 // - If the loop only counts population, the entire loop becomes dead after
2808 // the transformation. It is a lot easier to prove a countable loop dead
2809 // than to prove a noncountable one. (In some C dialects, an infinite loop
2810 // isn't dead even if it computes nothing useful. In general, DCE needs
2811 // to prove a noncountable loop finite before safely delete it.)
2812 //
2813 // - If the loop also performs something else, it remains alive.
2814 // Since it is transformed to countable form, it can be aggressively
2815 // optimized by some optimizations which are in general not applicable
2816 // to a noncountable loop.
2817 //
2818 // After this step, this loop (conceptually) would look like following:
2819 // newcnt = __builtin_ctpop(x);
2820 // t = newcnt;
2821 // if (x)
2822 // do { cnt++; x &= x-1; t--) } while (t > 0);
2823 BasicBlock *Body = *(CurLoop->block_begin());
2824 {
2825 auto *LbBr = cast<BranchInst>(Body->getTerminator());
2826 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
2827 Type *Ty = TripCnt->getType();
2828
2829 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi");
2830 TcPhi->insertBefore(Body->begin());
2831
2832 Builder.SetInsertPoint(LbCond);
2834 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
2835 "tcdec", false, true));
2836
2837 TcPhi->addIncoming(TripCnt, PreHead);
2838 TcPhi->addIncoming(TcDec, Body);
2839
2840 CmpInst::Predicate Pred =
2841 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
2842 LbCond->setPredicate(Pred);
2843 LbCond->setOperand(0, TcDec);
2844 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
2845 }
2846
2847 // Step 4: All the references to the original population counter outside
2848 // the loop are replaced with the NewCount -- the value returned from
2849 // __builtin_ctpop().
2850 CntInst->replaceUsesOutsideBlock(NewCount, Body);
2851
2852 // step 5: Forget the "non-computable" trip-count SCEV associated with the
2853 // loop. The loop would otherwise not be deleted even if it becomes empty.
2854 SE->forgetLoop(CurLoop);
2855}
2856
2857/// Match loop-invariant value.
2858template <typename SubPattern_t> struct match_LoopInvariant {
2859 SubPattern_t SubPattern;
2860 const Loop *L;
2861
2862 match_LoopInvariant(const SubPattern_t &SP, const Loop *L)
2863 : SubPattern(SP), L(L) {}
2864
2865 template <typename ITy> bool match(ITy *V) const {
2866 return L->isLoopInvariant(V) && SubPattern.match(V);
2867 }
2868};
2869
2870/// Matches if the value is loop-invariant.
2871template <typename Ty>
2872inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) {
2873 return match_LoopInvariant<Ty>(M, L);
2874}
2875
2876/// Return true if the idiom is detected in the loop.
2877///
2878/// The core idiom we are trying to detect is:
2879/// \code
2880/// entry:
2881/// <...>
2882/// %bitmask = shl i32 1, %bitpos
2883/// br label %loop
2884///
2885/// loop:
2886/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
2887/// %x.curr.bitmasked = and i32 %x.curr, %bitmask
2888/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
2889/// %x.next = shl i32 %x.curr, 1
2890/// <...>
2891/// br i1 %x.curr.isbitunset, label %loop, label %end
2892///
2893/// end:
2894/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2895/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
2896/// <...>
2897/// \endcode
2898static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX,
2899 Value *&BitMask, Value *&BitPos,
2900 Value *&CurrX, Instruction *&NextX) {
2902 " Performing shift-until-bittest idiom detection.\n");
2903
2904 // Give up if the loop has multiple blocks or multiple backedges.
2905 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
2906 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
2907 return false;
2908 }
2909
2910 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2911 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2912 assert(LoopPreheaderBB && "There is always a loop preheader.");
2913
2914 using namespace PatternMatch;
2915
2916 // Step 1: Check if the loop backedge is in desirable form.
2917
2918 CmpPredicate Pred;
2919 Value *CmpLHS, *CmpRHS;
2920 BasicBlock *TrueBB, *FalseBB;
2921 if (!match(LoopHeaderBB->getTerminator(),
2922 m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
2923 m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) {
2924 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
2925 return false;
2926 }
2927
2928 // Step 2: Check if the backedge's condition is in desirable form.
2929
2930 auto MatchVariableBitMask = [&]() {
2931 return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
2932 match(CmpLHS,
2933 m_c_And(m_Value(CurrX),
2935 m_Value(BitMask),
2936 m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)),
2937 CurLoop))));
2938 };
2939
2940 auto MatchDecomposableConstantBitMask = [&]() {
2941 auto Res = llvm::decomposeBitTestICmp(
2942 CmpLHS, CmpRHS, Pred, /*LookThroughTrunc=*/true,
2943 /*AllowNonZeroC=*/false, /*DecomposeAnd=*/true);
2944 if (Res && Res->Mask.isPowerOf2()) {
2945 assert(ICmpInst::isEquality(Res->Pred));
2946 Pred = Res->Pred;
2947 CurrX = Res->X;
2948 BitMask = ConstantInt::get(CurrX->getType(), Res->Mask);
2949 BitPos = ConstantInt::get(CurrX->getType(), Res->Mask.logBase2());
2950 return true;
2951 }
2952 return false;
2953 };
2954
2955 if (!MatchVariableBitMask() && !MatchDecomposableConstantBitMask()) {
2956 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n");
2957 return false;
2958 }
2959
2960 // Step 3: Check if the recurrence is in desirable form.
2961 auto *CurrXPN = dyn_cast<PHINode>(CurrX);
2962 if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {
2963 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
2964 return false;
2965 }
2966
2967 BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);
2968 NextX =
2969 dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB));
2970
2971 assert(CurLoop->isLoopInvariant(BaseX) &&
2972 "Expected BaseX to be available in the preheader!");
2973
2974 if (!NextX || !match(NextX, m_Shl(m_Specific(CurrX), m_One()))) {
2975 // FIXME: support right-shift?
2976 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
2977 return false;
2978 }
2979
2980 // Step 4: Check if the backedge's destinations are in desirable form.
2981
2983 "Should only get equality predicates here.");
2984
2985 // cmp-br is commutative, so canonicalize to a single variant.
2986 if (Pred != ICmpInst::Predicate::ICMP_EQ) {
2987 Pred = ICmpInst::getInversePredicate(Pred);
2988 std::swap(TrueBB, FalseBB);
2989 }
2990
2991 // We expect to exit loop when comparison yields false,
2992 // so when it yields true we should branch back to loop header.
2993 if (TrueBB != LoopHeaderBB) {
2994 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
2995 return false;
2996 }
2997
2998 // Okay, idiom checks out.
2999 return true;
3000}
3001
3002/// Look for the following loop:
3003/// \code
3004/// entry:
3005/// <...>
3006/// %bitmask = shl i32 1, %bitpos
3007/// br label %loop
3008///
3009/// loop:
3010/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
3011/// %x.curr.bitmasked = and i32 %x.curr, %bitmask
3012/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
3013/// %x.next = shl i32 %x.curr, 1
3014/// <...>
3015/// br i1 %x.curr.isbitunset, label %loop, label %end
3016///
3017/// end:
3018/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
3019/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
3020/// <...>
3021/// \endcode
3022///
3023/// And transform it into:
3024/// \code
3025/// entry:
3026/// %bitmask = shl i32 1, %bitpos
3027/// %lowbitmask = add i32 %bitmask, -1
3028/// %mask = or i32 %lowbitmask, %bitmask
3029/// %x.masked = and i32 %x, %mask
3030/// %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked,
3031/// i1 true)
3032/// %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros
3033/// %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -1
3034/// %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos
3035/// %tripcount = add i32 %backedgetakencount, 1
3036/// %x.curr = shl i32 %x, %backedgetakencount
3037/// %x.next = shl i32 %x, %tripcount
3038/// br label %loop
3039///
3040/// loop:
3041/// %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ]
3042/// %loop.iv.next = add nuw i32 %loop.iv, 1
3043/// %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount
3044/// <...>
3045/// br i1 %loop.ivcheck, label %end, label %loop
3046///
3047/// end:
3048/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
3049/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
3050/// <...>
3051/// \endcode
3052bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {
3053 bool MadeChange = false;
3054
3055 Value *X, *BitMask, *BitPos, *XCurr;
3056 Instruction *XNext;
3057 if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr,
3058 XNext)) {
3060 " shift-until-bittest idiom detection failed.\n");
3061 return MadeChange;
3062 }
3063 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n");
3064
3065 // Ok, it is the idiom we were looking for, we *could* transform this loop,
3066 // but is it profitable to transform?
3067
3068 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3069 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3070 assert(LoopPreheaderBB && "There is always a loop preheader.");
3071
3072 BasicBlock *SuccessorBB = CurLoop->getExitBlock();
3073 assert(SuccessorBB && "There is only a single successor.");
3074
3075 IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
3076 Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc());
3077
3078 Intrinsic::ID IntrID = Intrinsic::ctlz;
3079 Type *Ty = X->getType();
3080 unsigned Bitwidth = Ty->getScalarSizeInBits();
3081
3084
3085 // The rewrite is considered to be unprofitable iff and only iff the
3086 // intrinsic/shift we'll use are not cheap. Note that we are okay with *just*
3087 // making the loop countable, even if nothing else changes.
3089 IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getTrue()});
3090 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
3093 " Intrinsic is too costly, not beneficial\n");
3094 return MadeChange;
3095 }
3096 if (TTI->getArithmeticInstrCost(Instruction::Shl, Ty, CostKind) >
3098 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n");
3099 return MadeChange;
3100 }
3101
3102 // Ok, transform appears worthwhile.
3103 MadeChange = true;
3104
3105 if (!isGuaranteedNotToBeUndefOrPoison(BitPos)) {
3106 // BitMask may be computed from BitPos, Freeze BitPos so we can increase
3107 // it's use count.
3108 std::optional<BasicBlock::iterator> InsertPt = std::nullopt;
3109 if (auto *BitPosI = dyn_cast<Instruction>(BitPos))
3110 InsertPt = BitPosI->getInsertionPointAfterDef();
3111 else
3112 InsertPt = DT->getRoot()->getFirstNonPHIOrDbgOrAlloca();
3113 if (!InsertPt)
3114 return false;
3115 FreezeInst *BitPosFrozen =
3116 new FreezeInst(BitPos, BitPos->getName() + ".fr", *InsertPt);
3117 BitPos->replaceUsesWithIf(BitPosFrozen, [BitPosFrozen](Use &U) {
3118 return U.getUser() != BitPosFrozen;
3119 });
3120 BitPos = BitPosFrozen;
3121 }
3122
3123 // Step 1: Compute the loop trip count.
3124
3125 Value *LowBitMask = Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty),
3126 BitPos->getName() + ".lowbitmask");
3127 Value *Mask =
3128 Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask");
3129 Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked");
3130 CallInst *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(
3131 IntrID, Ty, {XMasked, /*is_zero_poison=*/Builder.getTrue()},
3132 /*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros");
3133 Value *XMaskedNumActiveBits = Builder.CreateSub(
3134 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros,
3135 XMasked->getName() + ".numactivebits", /*HasNUW=*/true,
3136 /*HasNSW=*/Bitwidth != 2);
3137 Value *XMaskedLeadingOnePos =
3138 Builder.CreateAdd(XMaskedNumActiveBits, Constant::getAllOnesValue(Ty),
3139 XMasked->getName() + ".leadingonepos", /*HasNUW=*/false,
3140 /*HasNSW=*/Bitwidth > 2);
3141
3142 Value *LoopBackedgeTakenCount = Builder.CreateSub(
3143 BitPos, XMaskedLeadingOnePos, CurLoop->getName() + ".backedgetakencount",
3144 /*HasNUW=*/true, /*HasNSW=*/true);
3145 // We know loop's backedge-taken count, but what's loop's trip count?
3146 // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
3147 Value *LoopTripCount =
3148 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
3149 CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
3150 /*HasNSW=*/Bitwidth != 2);
3151
3152 // Step 2: Compute the recurrence's final value without a loop.
3153
3154 // NewX is always safe to compute, because `LoopBackedgeTakenCount`
3155 // will always be smaller than `bitwidth(X)`, i.e. we never get poison.
3156 Value *NewX = Builder.CreateShl(X, LoopBackedgeTakenCount);
3157 NewX->takeName(XCurr);
3158 if (auto *I = dyn_cast<Instruction>(NewX))
3159 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
3160
3161 Value *NewXNext;
3162 // Rewriting XNext is more complicated, however, because `X << LoopTripCount`
3163 // will be poison iff `LoopTripCount == bitwidth(X)` (which will happen
3164 // iff `BitPos` is `bitwidth(x) - 1` and `X` is `1`). So unless we know
3165 // that isn't the case, we'll need to emit an alternative, safe IR.
3166 if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() ||
3170 Ty->getScalarSizeInBits() - 1))))
3171 NewXNext = Builder.CreateShl(X, LoopTripCount);
3172 else {
3173 // Otherwise, just additionally shift by one. It's the smallest solution,
3174 // alternatively, we could check that NewX is INT_MIN (or BitPos is )
3175 // and select 0 instead.
3176 NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));
3177 }
3178
3179 NewXNext->takeName(XNext);
3180 if (auto *I = dyn_cast<Instruction>(NewXNext))
3181 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
3182
3183 // Step 3: Adjust the successor basic block to recieve the computed
3184 // recurrence's final value instead of the recurrence itself.
3185
3186 XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB);
3187 XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB);
3188
3189 // Step 4: Rewrite the loop into a countable form, with canonical IV.
3190
3191 // The new canonical induction variable.
3192 Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->begin());
3193 auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
3194
3195 // The induction itself.
3196 // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
3197 Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
3198 auto *IVNext =
3199 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
3200 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
3201
3202 // The loop trip count check.
3203 auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,
3204 CurLoop->getName() + ".ivcheck");
3205 Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);
3206 LoopHeaderBB->getTerminator()->eraseFromParent();
3207
3208 // Populate the IV PHI.
3209 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
3210 IV->addIncoming(IVNext, LoopHeaderBB);
3211
3212 // Step 5: Forget the "non-computable" trip-count SCEV associated with the
3213 // loop. The loop would otherwise not be deleted even if it becomes empty.
3214
3215 SE->forgetLoop(CurLoop);
3216
3217 // Other passes will take care of actually deleting the loop if possible.
3218
3219 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n");
3220
3221 ++NumShiftUntilBitTest;
3222 return MadeChange;
3223}
3224
3225/// Return true if the idiom is detected in the loop.
3226///
3227/// The core idiom we are trying to detect is:
3228/// \code
3229/// entry:
3230/// <...>
3231/// %start = <...>
3232/// %extraoffset = <...>
3233/// <...>
3234/// br label %for.cond
3235///
3236/// loop:
3237/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
3238/// %nbits = add nsw i8 %iv, %extraoffset
3239/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
3240/// %val.shifted.iszero = icmp eq i8 %val.shifted, 0
3241/// %iv.next = add i8 %iv, 1
3242/// <...>
3243/// br i1 %val.shifted.iszero, label %end, label %loop
3244///
3245/// end:
3246/// %iv.res = phi i8 [ %iv, %loop ] <...>
3247/// %nbits.res = phi i8 [ %nbits, %loop ] <...>
3248/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
3249/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
3250/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
3251/// <...>
3252/// \endcode
3254 Instruction *&ValShiftedIsZero,
3255 Intrinsic::ID &IntrinID, Instruction *&IV,
3256 Value *&Start, Value *&Val,
3257 const SCEV *&ExtraOffsetExpr,
3258 bool &InvertedCond) {
3260 " Performing shift-until-zero idiom detection.\n");
3261
3262 // Give up if the loop has multiple blocks or multiple backedges.
3263 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
3264 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
3265 return false;
3266 }
3267
3268 Instruction *ValShifted, *NBits, *IVNext;
3269 Value *ExtraOffset;
3270
3271 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3272 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3273 assert(LoopPreheaderBB && "There is always a loop preheader.");
3274
3275 using namespace PatternMatch;
3276
3277 // Step 1: Check if the loop backedge, condition is in desirable form.
3278
3279 CmpPredicate Pred;
3280 BasicBlock *TrueBB, *FalseBB;
3281 if (!match(LoopHeaderBB->getTerminator(),
3282 m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB),
3283 m_BasicBlock(FalseBB))) ||
3284 !match(ValShiftedIsZero,
3285 m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) ||
3286 !ICmpInst::isEquality(Pred)) {
3287 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
3288 return false;
3289 }
3290
3291 // Step 2: Check if the comparison's operand is in desirable form.
3292 // FIXME: Val could be a one-input PHI node, which we should look past.
3293 if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop),
3294 m_Instruction(NBits)))) {
3295 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n");
3296 return false;
3297 }
3298 IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz
3299 : Intrinsic::ctlz;
3300
3301 // Step 3: Check if the shift amount is in desirable form.
3302
3303 if (match(NBits, m_c_Add(m_Instruction(IV),
3304 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
3305 (NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap()))
3306 ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset));
3307 else if (match(NBits,
3309 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
3310 NBits->hasNoSignedWrap())
3311 ExtraOffsetExpr = SE->getSCEV(ExtraOffset);
3312 else {
3313 IV = NBits;
3314 ExtraOffsetExpr = SE->getZero(NBits->getType());
3315 }
3316
3317 // Step 4: Check if the recurrence is in desirable form.
3318 auto *IVPN = dyn_cast<PHINode>(IV);
3319 if (!IVPN || IVPN->getParent() != LoopHeaderBB) {
3320 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
3321 return false;
3322 }
3323
3324 Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);
3325 IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB));
3326
3327 if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) {
3328 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
3329 return false;
3330 }
3331
3332 // Step 4: Check if the backedge's destinations are in desirable form.
3333
3335 "Should only get equality predicates here.");
3336
3337 // cmp-br is commutative, so canonicalize to a single variant.
3338 InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ;
3339 if (InvertedCond) {
3340 Pred = ICmpInst::getInversePredicate(Pred);
3341 std::swap(TrueBB, FalseBB);
3342 }
3343
3344 // We expect to exit loop when comparison yields true,
3345 // so when it yields false we should branch back to loop header.
3346 if (FalseBB != LoopHeaderBB) {
3347 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
3348 return false;
3349 }
3350
3351 // The new, countable, loop will certainly only run a known number of
3352 // iterations, It won't be infinite. But the old loop might be infinite
3353 // under certain conditions. For logical shifts, the value will become zero
3354 // after at most bitwidth(%Val) loop iterations. However, for arithmetic
3355 // right-shift, iff the sign bit was set, the value will never become zero,
3356 // and the loop may never finish.
3357 if (ValShifted->getOpcode() == Instruction::AShr &&
3358 !isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) {
3359 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n");
3360 return false;
3361 }
3362
3363 // Okay, idiom checks out.
3364 return true;
3365}
3366
3367/// Look for the following loop:
3368/// \code
3369/// entry:
3370/// <...>
3371/// %start = <...>
3372/// %extraoffset = <...>
3373/// <...>
3374/// br label %for.cond
3375///
3376/// loop:
3377/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
3378/// %nbits = add nsw i8 %iv, %extraoffset
3379/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
3380/// %val.shifted.iszero = icmp eq i8 %val.shifted, 0
3381/// %iv.next = add i8 %iv, 1
3382/// <...>
3383/// br i1 %val.shifted.iszero, label %end, label %loop
3384///
3385/// end:
3386/// %iv.res = phi i8 [ %iv, %loop ] <...>
3387/// %nbits.res = phi i8 [ %nbits, %loop ] <...>
3388/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
3389/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
3390/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
3391/// <...>
3392/// \endcode
3393///
3394/// And transform it into:
3395/// \code
3396/// entry:
3397/// <...>
3398/// %start = <...>
3399/// %extraoffset = <...>
3400/// <...>
3401/// %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0)
3402/// %val.numactivebits = sub i8 8, %val.numleadingzeros
3403/// %extraoffset.neg = sub i8 0, %extraoffset
3404/// %tmp = add i8 %val.numactivebits, %extraoffset.neg
3405/// %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start)
3406/// %loop.tripcount = sub i8 %iv.final, %start
3407/// br label %loop
3408///
3409/// loop:
3410/// %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ]
3411/// %loop.iv.next = add i8 %loop.iv, 1
3412/// %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount
3413/// %iv = add i8 %loop.iv, %start
3414/// <...>
3415/// br i1 %loop.ivcheck, label %end, label %loop
3416///
3417/// end:
3418/// %iv.res = phi i8 [ %iv.final, %loop ] <...>
3419/// <...>
3420/// \endcode
3421bool LoopIdiomRecognize::recognizeShiftUntilZero() {
3422 bool MadeChange = false;
3423
3424 Instruction *ValShiftedIsZero;
3425 Intrinsic::ID IntrID;
3426 Instruction *IV;
3427 Value *Start, *Val;
3428 const SCEV *ExtraOffsetExpr;
3429 bool InvertedCond;
3430 if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV,
3431 Start, Val, ExtraOffsetExpr, InvertedCond)) {
3433 " shift-until-zero idiom detection failed.\n");
3434 return MadeChange;
3435 }
3436 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n");
3437
3438 // Ok, it is the idiom we were looking for, we *could* transform this loop,
3439 // but is it profitable to transform?
3440
3441 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3442 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3443 assert(LoopPreheaderBB && "There is always a loop preheader.");
3444
3445 BasicBlock *SuccessorBB = CurLoop->getExitBlock();
3446 assert(SuccessorBB && "There is only a single successor.");
3447
3448 IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
3449 Builder.SetCurrentDebugLocation(IV->getDebugLoc());
3450
3451 Type *Ty = Val->getType();
3452 unsigned Bitwidth = Ty->getScalarSizeInBits();
3453
3456
3457 // The rewrite is considered to be unprofitable iff and only iff the
3458 // intrinsic we'll use are not cheap. Note that we are okay with *just*
3459 // making the loop countable, even if nothing else changes.
3461 IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getFalse()});
3462 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
3465 " Intrinsic is too costly, not beneficial\n");
3466 return MadeChange;
3467 }
3468
3469 // Ok, transform appears worthwhile.
3470 MadeChange = true;
3471
3472 bool OffsetIsZero = ExtraOffsetExpr->isZero();
3473
3474 // Step 1: Compute the loop's final IV value / trip count.
3475
3476 CallInst *ValNumLeadingZeros = Builder.CreateIntrinsic(
3477 IntrID, Ty, {Val, /*is_zero_poison=*/Builder.getFalse()},
3478 /*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros");
3479 Value *ValNumActiveBits = Builder.CreateSub(
3480 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros,
3481 Val->getName() + ".numactivebits", /*HasNUW=*/true,
3482 /*HasNSW=*/Bitwidth != 2);
3483
3484 SCEVExpander Expander(*SE, *DL, "loop-idiom");
3485 Expander.setInsertPoint(&*Builder.GetInsertPoint());
3486 Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);
3487
3488 Value *ValNumActiveBitsOffset = Builder.CreateAdd(
3489 ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset",
3490 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true);
3491 Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},
3492 {ValNumActiveBitsOffset, Start},
3493 /*FMFSource=*/nullptr, "iv.final");
3494
3495 auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub(
3496 IVFinal, Start, CurLoop->getName() + ".backedgetakencount",
3497 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true));
3498 // FIXME: or when the offset was `add nuw`
3499
3500 // We know loop's backedge-taken count, but what's loop's trip count?
3501 Value *LoopTripCount =
3502 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
3503 CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
3504 /*HasNSW=*/Bitwidth != 2);
3505
3506 // Step 2: Adjust the successor basic block to recieve the original
3507 // induction variable's final value instead of the orig. IV itself.
3508
3509 IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);
3510
3511 // Step 3: Rewrite the loop into a countable form, with canonical IV.
3512
3513 // The new canonical induction variable.
3514 Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->begin());
3515 auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
3516
3517 // The induction itself.
3518 Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->getFirstNonPHIIt());
3519 auto *CIVNext =
3520 Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next",
3521 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
3522
3523 // The loop trip count check.
3524 auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,
3525 CurLoop->getName() + ".ivcheck");
3526 auto *NewIVCheck = CIVCheck;
3527 if (InvertedCond) {
3528 NewIVCheck = Builder.CreateNot(CIVCheck);
3529 NewIVCheck->takeName(ValShiftedIsZero);
3530 }
3531
3532 // The original IV, but rebased to be an offset to the CIV.
3533 auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false,
3534 /*HasNSW=*/true); // FIXME: what about NUW?
3535 IVDePHId->takeName(IV);
3536
3537 // The loop terminator.
3538 Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
3539 Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);
3540 LoopHeaderBB->getTerminator()->eraseFromParent();
3541
3542 // Populate the IV PHI.
3543 CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
3544 CIV->addIncoming(CIVNext, LoopHeaderBB);
3545
3546 // Step 4: Forget the "non-computable" trip-count SCEV associated with the
3547 // loop. The loop would otherwise not be deleted even if it becomes empty.
3548
3549 SE->forgetLoop(CurLoop);
3550
3551 // Step 5: Try to cleanup the loop's body somewhat.
3552 IV->replaceAllUsesWith(IVDePHId);
3553 IV->eraseFromParent();
3554
3555 ValShiftedIsZero->replaceAllUsesWith(NewIVCheck);
3556 ValShiftedIsZero->eraseFromParent();
3557
3558 // Other passes will take care of actually deleting the loop if possible.
3559
3560 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n");
3561
3562 ++NumShiftUntilZero;
3563 return MadeChange;
3564}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
DXIL Resource Access
This file defines the DenseMap class.
#define DEBUG_TYPE
static const HTTPClientCleanup Cleanup
static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, const SCEV *BECount, unsigned StoreSize, AliasAnalysis &AA, SmallPtrSetImpl< Instruction * > &Ignored)
mayLoopAccessLocation - Return true if the specified loop might access the specified pointer location...
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static Value * matchCondition(BranchInst *BI, BasicBlock *LoopEntry, bool JmpOnZero=false)
Check if the given conditional branch is based on the comparison between a variable and zero,...
static PHINode * getRecurrenceVar(Value *VarX, Instruction *DefX, BasicBlock *LoopEntry)
static cl::opt< bool, true > DisableLIRPMemset("disable-" DEBUG_TYPE "-memset", cl::desc("Proceed with loop idiom recognize pass, but do " "not convert loop(s) to memset."), cl::location(DisableLIRP::Memset), cl::init(false), cl::ReallyHidden)
static cl::opt< bool > ForceMemsetPatternIntrinsic("loop-idiom-force-memset-pattern-intrinsic", cl::desc("Use memset.pattern intrinsic whenever possible"), cl::init(false), cl::Hidden)
static CallInst * createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL, bool ZeroCheck, Intrinsic::ID IID)
static cl::opt< bool, true > EnableLIRPWcslen("disable-loop-idiom-wcslen", cl::desc("Proceed with loop idiom recognize pass, " "enable conversion of loop(s) to wcslen."), cl::location(DisableLIRP::Wcslen), cl::init(false), cl::ReallyHidden)
static bool detectShiftUntilLessThanIdiom(Loop *CurLoop, const DataLayout &DL, Intrinsic::ID &IntrinID, Value *&InitX, Instruction *&CntInst, PHINode *&CntPhi, Instruction *&DefX, APInt &Threshold)
Return true if the idiom is detected in the loop.
static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX, Value *&BitMask, Value *&BitPos, Value *&CurrX, Instruction *&NextX)
Return true if the idiom is detected in the loop.
static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, Instruction *&CntInst, PHINode *&CntPhi, Value *&Var)
Return true iff the idiom is detected in the loop.
static Constant * getMemSetPatternValue(Value *V, const DataLayout *DL)
getMemSetPatternValue - If a strided store of the specified value is safe to turn into a memset....
static cl::opt< bool, true > DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy", cl::desc("Proceed with loop idiom recognize pass, but do " "not convert loop(s) to memcpy."), cl::location(DisableLIRP::Memcpy), cl::init(false), cl::ReallyHidden)
static CallInst * createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL)
static const SCEV * getNumBytes(const SCEV *BECount, Type *IntPtr, const SCEV *StoreSizeSCEV, Loop *CurLoop, const DataLayout *DL, ScalarEvolution *SE)
Compute the number of bytes as a SCEV from the backedge taken count.
static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL, Intrinsic::ID &IntrinID, Value *&InitX, Instruction *&CntInst, PHINode *&CntPhi, Instruction *&DefX)
Return true if the idiom is detected in the loop.
static cl::opt< bool, true > DisableLIRPStrlen("disable-loop-idiom-strlen", cl::desc("Proceed with loop idiom recognize pass, but do " "not convert loop(s) to strlen."), cl::location(DisableLIRP::Strlen), cl::init(false), cl::ReallyHidden)
static const SCEV * getStartForNegStride(const SCEV *Start, const SCEV *BECount, Type *IntPtr, const SCEV *StoreSizeSCEV, ScalarEvolution *SE)
static APInt getStoreStride(const SCEVAddRecExpr *StoreEv)
static Value * matchShiftULTCondition(BranchInst *BI, BasicBlock *LoopEntry, APInt &Threshold)
Check if the given conditional branch is based on an unsigned less-than comparison between a variable...
match_LoopInvariant< Ty > m_LoopInvariant(const Ty &M, const Loop *L)
Matches if the value is loop-invariant.
static cl::opt< bool, true > DisableLIRPAll("disable-" DEBUG_TYPE "-all", cl::desc("Options to disable Loop Idiom Recognize Pass."), cl::location(DisableLIRP::All), cl::init(false), cl::ReallyHidden)
static void deleteDeadInstruction(Instruction *I)
static cl::opt< bool, true > DisableLIRPHashRecognize("disable-" DEBUG_TYPE "-hashrecognize", cl::desc("Proceed with loop idiom recognize pass, " "but do not optimize CRC loops."), cl::location(DisableLIRP::HashRecognize), cl::init(false), cl::ReallyHidden)
static cl::opt< bool > UseLIRCodeSizeHeurs("use-lir-code-size-heurs", cl::desc("Use loop idiom recognition code size heuristics when compiling " "with -Os/-Oz"), cl::init(true), cl::Hidden)
#define I(x, y, z)
Definition MD5.cpp:58
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
This file implements a map that provides insertion order iteration.
This file provides utility analysis objects describing memory locations.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define T
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
if(PassOpts->AAPipeline)
const SmallVectorImpl< MachineOperand > & Cond
static bool isSimple(Instruction *I)
verify safepoint Safepoint IR Verifier
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:167
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
Definition APInt.h:1552
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1540
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1488
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1562
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:459
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:528
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug(bool SkipPseudoOp=true) const
Return a const iterator range over the instructions in the block, skipping any debug instructions.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:482
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI const_iterator getFirstNonPHIOrDbgOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a debug intrinsic,...
size_t size() const
Definition BasicBlock.h:480
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
BinaryOps getOpcode() const
Definition InstrTypes.h:374
Conditional or Unconditional Branch instruction.
void setCondition(Value *V)
bool isConditional() const
unsigned getNumSuccessors() const
BasicBlock * getSuccessor(unsigned i) const
Value * getCondition() const
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
This class represents a function call, abstracting a target machine's calling convention.
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:770
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:678
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:708
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:701
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:703
@ ICMP_NE
not equal
Definition InstrTypes.h:700
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:791
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:767
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:226
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:220
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:214
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:163
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:154
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
A debug info location.
Definition DebugLoc.h:124
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class represents a freeze function that returns random concrete value if an operand is either a ...
PointerType * getType() const
Global values are always pointers.
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
static CRCTable genSarwateTable(const APInt &GenPoly, bool ByteOrderSwapped)
Generate a lookup table of 256 entries by interleaving the generating polynomial.
This instruction compares its operands according to the predicate given to the constructor.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition IRBuilder.h:497
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1551
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2780
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
bool isVolatile() const
Return true if this is a load from a volatile memory location.
bool isUnordered() const
Align getAlign() const
Return the alignment of the access that is being performed.
static LocationSize precise(uint64_t Value)
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
BlockT * getHeader() const
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
block_iterator block_begin() const
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V, bool HasCoroSuspendInst=false) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:61
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:644
ICmpInst * getLatchCmpInst() const
Get the latch condition instruction.
Definition LoopInfo.cpp:187
StringRef getName() const
Definition LoopInfo.h:390
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Definition LoopInfo.cpp:163
This class wraps the llvm.memcpy intrinsic.
Value * getLength() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
MaybeAlign getDestAlign() const
bool isForceInlined() const
bool isVolatile() const
Value * getValue() const
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
MaybeAlign getSourceAlign() const
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it,...
Representation for a specific memory location.
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:936
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition Module.h:278
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This node represents a polynomial recurrence on the trip count of the specified loop.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
Helper to remove instructions inserted during SCEV expansion, unless they are marked as used.
This class uses information about analyze scalars to rewrite expressions in canonical form.
const SCEV * getOperand(unsigned i) const
This class represents an analyzed expression in the program.
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
A vector that has set insertion semantics.
Definition SetVector.h:59
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:279
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:168
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
void computeLoopSafetyInfo(const Loop *CurLoop) override
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
bool anyBlockMayThrow() const override
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Align getAlign() const
Value * getValueOperand()
Value * getPointerOperand()
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Provides information about what library functions are available for the current target.
unsigned getWCharSize(const Module &M) const
Returns the size of the wchar_t type in bytes or 0 if the size is unknown.
bool has(LibFunc F) const
Tests whether a library function is available.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Basic
The cost of a typical 'add' instruction.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:231
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:255
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:301
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:237
Value * getOperand(unsigned i) const
Definition User.h:232
unsigned getNumOperands() const
Definition User.h:254
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI void replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:554
LLVM_ABI void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
Definition Value.cpp:599
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.cpp:1101
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
Value handle that is nullable, but tries to track the Value.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
const ParentTy * getParent() const
Definition ilist_node.h:34
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ HeaderSize
Definition BTF.h:61
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
OperandType
Operands are tagged with one of the values of this enum.
Definition MCInstrDesc.h:59
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
bool match(Val *V, const Pattern &P)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
class_match< const SCEVConstant > m_SCEVConstant()
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVAffineAddRec_match< Op0_t, Op1_t, class_match< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
bool match(const SCEV *S, const Pattern &P)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
class_match< const SCEV > m_SCEV()
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
constexpr double e
Definition MathExtras.h:47
DiagnosticInfoOptimizationBase::Argument NV
DiagnosticInfoOptimizationBase::setExtraArgs setExtraArgs
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:533
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
LLVM_ABI bool isLibFuncEmittable(const Module *M, const TargetLibraryInfo *TLI, LibFunc TheLibFunc)
Check whether the library function is available on target and also that it in the current Module is a...
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:1970
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
LLVM_ABI Value * emitStrLen(Value *Ptr, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the strlen function to the builder, for the specified pointer.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
TargetTransformInfo TTI
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:84
LLVM_ABI bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
LLVM_ABI Value * emitWcsLen(Value *Ptr, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the wcslen function to the builder, for the specified pointer.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:641
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
std::optional< DecomposedBitTest > decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate Pred, bool LookThroughTrunc=true, bool AllowNonZeroC=false, bool DecomposeAnd=false)
Decompose an icmp into the form ((X & Mask) pred C) if possible.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:853
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:760
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
AAMDNodes extendTo(ssize_t Len) const
Create a new AAMDNode that describes this AAMDNode after extending it to apply to a series of bytes o...
Definition Metadata.h:833
static bool Wcslen
When true, Wcslen is disabled.
static bool HashRecognize
When true, HashRecognize is disabled.
static bool Strlen
When true, Strlen is disabled.
static bool Memset
When true, Memset is disabled.
static bool All
When true, the entire pass is disabled.
static bool Memcpy
When true, Memcpy is disabled.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:117
The structure that is returned when a polynomial algorithm was recognized by the analysis.
Match loop-invariant value.
match_LoopInvariant(const SubPattern_t &SP, const Loop *L)