LLVM 24.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 "ScalarOptions.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/ArrayRef.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/MapVector.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SetVector.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/StringRef.h"
59#include "llvm/IR/BasicBlock.h"
60#include "llvm/IR/Constant.h"
61#include "llvm/IR/Constants.h"
62#include "llvm/IR/DataLayout.h"
63#include "llvm/IR/DebugLoc.h"
65#include "llvm/IR/Dominators.h"
66#include "llvm/IR/GlobalValue.h"
68#include "llvm/IR/IRBuilder.h"
69#include "llvm/IR/InstrTypes.h"
70#include "llvm/IR/Instruction.h"
73#include "llvm/IR/Intrinsics.h"
74#include "llvm/IR/LLVMContext.h"
75#include "llvm/IR/Module.h"
76#include "llvm/IR/PassManager.h"
79#include "llvm/IR/Type.h"
80#include "llvm/IR/User.h"
81#include "llvm/IR/Value.h"
82#include "llvm/IR/ValueHandle.h"
85#include "llvm/Support/Debug.h"
92#include <algorithm>
93#include <cassert>
94#include <cstdint>
95#include <utility>
96
97using namespace llvm;
98using namespace SCEVPatternMatch;
99
100#define DEBUG_TYPE "loop-idiom"
101
102STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
103STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
104STATISTIC(NumMemMove, "Number of memmove's formed from loop load+stores");
105STATISTIC(NumStrLen, "Number of strlen's and wcslen's formed from loop loads");
107 NumShiftUntilBitTest,
108 "Number of uncountable loops recognized as 'shift until bitttest' idiom");
109STATISTIC(NumShiftUntilZero,
110 "Number of uncountable loops recognized as 'shift until zero' idiom");
111
112namespace llvm {
115 DisableLIRPAll("disable-" DEBUG_TYPE "-all",
116 cl::desc("Options to disable Loop Idiom Recognize Pass."),
119
122 DisableLIRPMemset("disable-" DEBUG_TYPE "-memset",
123 cl::desc("Proceed with loop idiom recognize pass, but do "
124 "not convert loop(s) to memset."),
127
130 DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy",
131 cl::desc("Proceed with loop idiom recognize pass, but do "
132 "not convert loop(s) to memcpy."),
135
138 DisableLIRPStrlen("disable-loop-idiom-strlen",
139 cl::desc("Proceed with loop idiom recognize pass, but do "
140 "not convert loop(s) to strlen."),
143
146 EnableLIRPWcslen("disable-loop-idiom-wcslen",
147 cl::desc("Proceed with loop idiom recognize pass, "
148 "enable conversion of loop(s) to wcslen."),
151
154 DisableLIRPHashRecognize("disable-" DEBUG_TYPE "-hashrecognize",
155 cl::desc("Proceed with loop idiom recognize pass, "
156 "but do not do hash-recognize analysis."),
158 cl::init(false), cl::ReallyHidden);
159
160} // namespace llvm
161
162namespace {
163
164class LoopIdiomRecognize {
165 const ScalarOptions &Opts;
166 Loop *CurLoop = nullptr;
168 DominatorTree *DT;
169 LoopInfo *LI;
170 ScalarEvolution *SE;
173 const DataLayout *DL;
175 bool ApplyCodeSizeHeuristics;
176 std::unique_ptr<MemorySSAUpdater> MSSAU;
177
178public:
179 explicit LoopIdiomRecognize(const ScalarOptions &Opts, AliasAnalysis *AA,
180 DominatorTree *DT, LoopInfo *LI,
182 const TargetTransformInfo *TTI, MemorySSA *MSSA,
183 const DataLayout *DL,
185 : Opts(Opts), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL),
186 ORE(ORE) {
187 if (MSSA)
188 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
189 }
190
191 bool runOnLoop(Loop *L);
192
193private:
194 using StoreList = SmallVector<StoreInst *, 8>;
195 using StoreListMap = MapVector<Value *, StoreList>;
196
197 StoreListMap StoreRefsForMemset;
198 StoreListMap StoreRefsForMemsetPattern;
199 StoreList StoreRefsForMemcpy;
200 bool HasMemset;
201 bool HasMemsetPattern;
202 bool HasMemcpy;
203
204 /// Return code for isLegalStore()
205 enum LegalStoreKind {
206 None = 0,
207 Memset,
208 MemsetPattern,
209 Memcpy,
210 UnorderedAtomicMemcpy,
211 DontUse // Dummy retval never to be used. Allows catching errors in retval
212 // handling.
213 };
214
215 /// \name Countable Loop Idiom Handling
216 /// @{
217
218 bool runOnCountableLoop();
219 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
220 SmallVectorImpl<BasicBlock *> &ExitBlocks);
221
222 void collectStores(BasicBlock *BB);
223 LegalStoreKind isLegalStore(StoreInst *SI);
224 enum class ForMemset { No, Yes };
225 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
226 ForMemset For);
227
228 template <typename MemInst>
229 bool processLoopMemIntrinsic(
230 BasicBlock *BB,
231 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
232 const SCEV *BECount);
233 bool processLoopMemCpy(MemCpyInst *MCI, const SCEV *BECount);
234 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
235
236 bool processLoopStridedStore(Value *DestPtr, const SCEV *StoreSizeSCEV,
237 MaybeAlign StoreAlignment, Value *StoredVal,
238 Instruction *TheStore,
239 SmallPtrSetImpl<Instruction *> &Stores,
240 const SCEVAddRecExpr *Ev, const SCEV *BECount,
241 bool IsNegStride, bool IsLoopMemset = false);
242 bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
243 bool processLoopStoreOfLoopLoad(Value *DestPtr, Value *SourcePtr,
244 const SCEV *StoreSize, MaybeAlign StoreAlign,
245 MaybeAlign LoadAlign, Instruction *TheStore,
246 Instruction *TheLoad,
247 const SCEVAddRecExpr *StoreEv,
248 const SCEVAddRecExpr *LoadEv,
249 const SCEV *BECount);
250 bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
251 bool IsLoopMemset = false);
252 bool optimizeCRCLoop(const PolynomialInfo &Info);
253 void optimizeCRCLoopUsingClmul(const PolynomialInfo &Info);
254 void optimizeCRCLoopUsingTableLookup(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 const ScalarOptions &Opts = getScalarOptions(L);
301 LoopIdiomRecognize LIR(Opts, &AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI,
302 AR.MSSA, DL, ORE);
303 if (!LIR.runOnLoop(&L))
304 return PreservedAnalyses::all();
305
307 if (AR.MSSA)
308 PA.preserve<MemorySSAAnalysis>();
309 return PA;
310}
311
313 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
314 I->eraseFromParent();
315}
316
317//===----------------------------------------------------------------------===//
318//
319// Implementation of LoopIdiomRecognize
320//
321//===----------------------------------------------------------------------===//
322
323bool LoopIdiomRecognize::runOnLoop(Loop *L) {
324 CurLoop = L;
325 // If the loop could not be converted to canonical form, it must have an
326 // indirectbr in it, just give up.
327 if (!L->getLoopPreheader())
328 return false;
329
330 // Disable loop idiom recognition if the function's name is a common idiom.
331 StringRef Name = L->getHeader()->getParent()->getName();
332 if (Name == "memset" || Name == "memcpy" || Name == "strlen" ||
333 Name == "wcslen")
334 return false;
335
336 // Determine if code size heuristics need to be applied.
337 ApplyCodeSizeHeuristics =
338 L->getHeader()->getParent()->hasOptSize() && Opts.use_lir_code_size_heurs;
339
340 HasMemset = TLI->has(LibFunc_memset);
341 // TODO: Unconditionally enable use of the memset pattern intrinsic (or at
342 // least, opt-in via target hook) once we are confident it will never result
343 // in worse codegen than without. For now, use it only when the target
344 // supports memset_pattern16 libcall (or unless this is overridden by
345 // command line option).
346 HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
347 HasMemcpy = TLI->has(LibFunc_memcpy);
348
349 if (HasMemset || HasMemsetPattern ||
350 Opts.loop_idiom_force_memset_pattern_intrinsic || HasMemcpy ||
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(CurLoop);
380 if (SafetyInfo.anyBlockMayThrow())
381 return false;
382
383 bool MadeChange = false;
384
385 // Scan all the blocks in the loop that are not in subloops.
386 for (auto *BB : CurLoop->getBlocks()) {
387 // Ignore blocks in subloops.
388 if (LI->getLoopFor(BB) != CurLoop)
389 continue;
390
391 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
392 }
393
394 // Attempt to optimize a CRC loop if one is detected by HashRecognize.
396 Opts.loop_idiom_crc_strategy != CRCStrategyKind::Disable)
397 if (auto Res = HashRecognize(*CurLoop, *SE).getResult())
398 MadeChange |= optimizeCRCLoop(*Res);
399
400 return MadeChange;
401}
402
403static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
404 const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
405 return ConstStride->getAPInt();
406}
407
408/// getMemSetPatternValue - If a strided store of the specified value is safe to
409/// turn into a memset.patternn intrinsic, return the Constant that should
410/// be passed in. Otherwise, return null.
411///
412/// TODO this function could allow more constants than it does today (e.g.
413/// those over 16 bytes) now it has transitioned to being used for the
414/// memset.pattern intrinsic rather than directly the memset_pattern16
415/// libcall.
417 // If the value isn't a constant, we can't promote it to being in a constant
418 // array. We could theoretically do a store to an alloca or something, but
419 // that doesn't seem worthwhile.
421 if (!C || isa<ConstantExpr>(C))
422 return nullptr;
423
424 // Only handle simple values that are a power of two bytes in size.
425 uint64_t Size = DL->getTypeSizeInBits(V->getType());
426 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
427 return nullptr;
428
429 // Don't care enough about darwin/ppc to implement this.
430 if (DL->isBigEndian())
431 return nullptr;
432
433 // Convert to size in bytes.
434 Size /= 8;
435
436 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
437 // if the top and bottom are the same (e.g. for vectors and large integers).
438 if (Size > 16)
439 return nullptr;
440
441 // For now, don't handle types that aren't int, floats, or pointers.
442 Type *CTy = C->getType();
443 if (!CTy->isIntOrPtrTy() && !CTy->isFloatingPointTy())
444 return nullptr;
445
446 return C;
447}
448
449LoopIdiomRecognize::LegalStoreKind
450LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
451 // Don't touch volatile stores.
452 if (SI->isVolatile())
453 return LegalStoreKind::None;
454 // We only want simple or unordered-atomic stores.
455 if (!SI->isUnordered())
456 return LegalStoreKind::None;
457
458 // Avoid merging nontemporal stores.
459 if (SI->getMetadata(LLVMContext::MD_nontemporal))
460 return LegalStoreKind::None;
461
462 Value *StoredVal = SI->getValueOperand();
463 Value *StorePtr = SI->getPointerOperand();
464
465 if (DL->hasUnstableRepresentation(StoredVal->getType()))
466 return LegalStoreKind::None;
467
468 // Transformations could invalidate the external-state pointers
469 // memcpy - LangRef specifies that a valid memcpy must preserve external
470 // state, so no transformations are blocked by it.
471 // memset - We assume that a memset of 0 has an equivalent external state
472 // effect as a null pointer store. This is currently not explicitly
473 // specified, but is true of the one exemplar we have (CHERI
474 // capabilities). All other memset formations are not safe.
475 bool MustPreserveExternalState = DL->hasExternalState(StoredVal->getType()) &&
476 !isa<ConstantPointerNull>(StoredVal);
477
478 // Reject stores that are so large that they overflow an unsigned.
479 // When storing out scalable vectors we bail out for now, since the code
480 // below currently only works for constant strides.
481 TypeSize SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
482 if (SizeInBits.isScalable() || (SizeInBits.getFixedValue() & 7) ||
483 (SizeInBits.getFixedValue() >> 32) != 0)
484 return LegalStoreKind::None;
485
486 // See if the pointer expression is an AddRec like {base,+,1} on the current
487 // loop, which indicates a strided store. If we have something else, it's a
488 // random store we can't handle.
489 const SCEV *StoreEv = SE->getSCEV(StorePtr);
490 const SCEVConstant *Stride;
491 if (!match(StoreEv, m_scev_AffineAddRec(m_SCEV(), m_SCEVConstant(Stride),
492 m_SpecificLoop(CurLoop))))
493 return LegalStoreKind::None;
494
495 // See if the store can be turned into a memset.
496
497 // If the stored value is a byte-wise value (like i32 -1), then it may be
498 // turned into a memset of i8 -1, assuming that all the consecutive bytes
499 // are stored. A store of i32 0x01020304 can never be turned into a memset,
500 // but it can be turned into memset_pattern if the target supports it.
501 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
502
503 // Note: memset and memset_pattern on unordered-atomic is yet not supported
504 bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
505
506 // If we're allowed to form a memset, and the stored value would be
507 // acceptable for memset, use it.
508 if (!MustPreserveExternalState && !UnorderedAtomic && HasMemset &&
509 SplatValue && !DisableLIRP::Memset &&
510 // Verify that the stored value is loop invariant. If not, we can't
511 // promote the memset.
512 CurLoop->isLoopInvariant(SplatValue)) {
513 // It looks like we can use SplatValue.
514 return LegalStoreKind::Memset;
515 }
516 if (!MustPreserveExternalState && !UnorderedAtomic &&
517 (HasMemsetPattern || Opts.loop_idiom_force_memset_pattern_intrinsic) &&
519 // Don't create memset_pattern16s with address spaces.
520 StorePtr->getType()->getPointerAddressSpace() == 0 &&
521 getMemSetPatternValue(StoredVal, DL)) {
522 // It looks like we can use PatternValue!
523 return LegalStoreKind::MemsetPattern;
524 }
525
526 // Otherwise, see if the store can be turned into a memcpy.
527 if (HasMemcpy && !DisableLIRP::Memcpy) {
528 // Check to see if the stride matches the size of the store. If so, then we
529 // know that every byte is touched in the loop.
530 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
531 APInt StrideAP = Stride->getAPInt();
532 if (StoreSize != StrideAP && StoreSize != -StrideAP)
533 return LegalStoreKind::None;
534
535 // The store must be feeding a non-volatile load.
536 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
537
538 // Only allow non-volatile loads
539 if (!LI || LI->isVolatile())
540 return LegalStoreKind::None;
541 // Only allow simple or unordered-atomic loads
542 if (!LI->isUnordered())
543 return LegalStoreKind::None;
544
545 // See if the pointer expression is an AddRec like {base,+,1} on the current
546 // loop, which indicates a strided load. If we have something else, it's a
547 // random load we can't handle.
548 const SCEV *LoadEv = SE->getSCEV(LI->getPointerOperand());
549
550 // The store and load must share the same stride.
551 if (!match(LoadEv, m_scev_AffineAddRec(m_SCEV(), m_scev_Specific(Stride),
552 m_SpecificLoop(CurLoop))))
553 return LegalStoreKind::None;
554
555 // Success. This store can be converted into a memcpy.
556 UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
557 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
558 : LegalStoreKind::Memcpy;
559 }
560 // This store can't be transformed into a memset/memcpy.
561 return LegalStoreKind::None;
562}
563
564void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
565 StoreRefsForMemset.clear();
566 StoreRefsForMemsetPattern.clear();
567 StoreRefsForMemcpy.clear();
568 for (Instruction &I : *BB) {
570 if (!SI)
571 continue;
572
573 // Make sure this is a strided store with a constant stride.
574 switch (isLegalStore(SI)) {
575 case LegalStoreKind::None:
576 // Nothing to do
577 break;
578 case LegalStoreKind::Memset: {
579 // Find the base pointer.
580 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
581 StoreRefsForMemset[Ptr].push_back(SI);
582 } break;
583 case LegalStoreKind::MemsetPattern: {
584 // Find the base pointer.
585 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
586 StoreRefsForMemsetPattern[Ptr].push_back(SI);
587 } break;
588 case LegalStoreKind::Memcpy:
589 case LegalStoreKind::UnorderedAtomicMemcpy:
590 StoreRefsForMemcpy.push_back(SI);
591 break;
592 default:
593 assert(false && "unhandled return value");
594 break;
595 }
596 }
597}
598
599/// runOnLoopBlock - Process the specified block, which lives in a counted loop
600/// with the specified backedge count. This block is known to be in the current
601/// loop and not in any subloops.
602bool LoopIdiomRecognize::runOnLoopBlock(
603 BasicBlock *BB, const SCEV *BECount,
604 SmallVectorImpl<BasicBlock *> &ExitBlocks) {
605 // We can only promote stores in this block if they are unconditionally
606 // executed in the loop. For a block to be unconditionally executed, it has
607 // to dominate all the exit blocks of the loop. Verify this now.
608 for (BasicBlock *ExitBlock : ExitBlocks)
609 if (!DT->dominates(BB, ExitBlock))
610 return false;
611
612 bool MadeChange = false;
613 // Look for store instructions, which may be optimized to memset/memcpy.
614 collectStores(BB);
615
616 // Look for a single store or sets of stores with a common base, which can be
617 // optimized into a memset (memset_pattern). The latter most commonly happens
618 // with structs and handunrolled loops.
619 for (auto &SL : StoreRefsForMemset)
620 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
621
622 for (auto &SL : StoreRefsForMemsetPattern)
623 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
624
625 // Optimize the store into a memcpy, if it feeds an similarly strided load.
626 for (auto &SI : StoreRefsForMemcpy)
627 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
628
629 MadeChange |= processLoopMemIntrinsic<MemCpyInst>(
630 BB, &LoopIdiomRecognize::processLoopMemCpy, BECount);
631 MadeChange |= processLoopMemIntrinsic<MemSetInst>(
632 BB, &LoopIdiomRecognize::processLoopMemSet, BECount);
633
634 return MadeChange;
635}
636
637/// See if this store(s) can be promoted to a memset.
638bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
639 const SCEV *BECount, ForMemset For) {
640 // Try to find consecutive stores that can be transformed into memsets.
641 SetVector<StoreInst *> Heads, Tails;
643
644 // Do a quadratic search on all of the given stores and find
645 // all of the pairs of stores that follow each other.
646 SmallVector<unsigned, 16> IndexQueue;
647 for (unsigned i = 0, e = SL.size(); i < e; ++i) {
648 assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
649
650 Value *FirstStoredVal = SL[i]->getValueOperand();
651 Value *FirstStorePtr = SL[i]->getPointerOperand();
652 const SCEVAddRecExpr *FirstStoreEv =
653 cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
654 APInt FirstStride = getStoreStride(FirstStoreEv);
655 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
656
657 // See if we can optimize just this store in isolation.
658 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
659 Heads.insert(SL[i]);
660 continue;
661 }
662
663 Value *FirstSplatValue = nullptr;
664 Constant *FirstPatternValue = nullptr;
665
666 if (For == ForMemset::Yes) {
667 FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL);
668 if (isa<UndefValue>(FirstSplatValue))
669 continue;
670 } else {
671 FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
672 if (isa<UndefValue>(FirstPatternValue))
673 continue;
674 }
675
676 assert((FirstSplatValue || FirstPatternValue) &&
677 "Expected either splat value or pattern value.");
678
679 IndexQueue.clear();
680 // If a store has multiple consecutive store candidates, search Stores
681 // array according to the sequence: from i+1 to e, then from i-1 to 0.
682 // This is because usually pairing with immediate succeeding or preceding
683 // candidate create the best chance to find memset opportunity.
684 unsigned j = 0;
685 for (j = i + 1; j < e; ++j)
686 IndexQueue.push_back(j);
687 for (j = i; j > 0; --j)
688 IndexQueue.push_back(j - 1);
689
690 for (auto &k : IndexQueue) {
691 assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
692 Value *SecondStorePtr = SL[k]->getPointerOperand();
693 const SCEVAddRecExpr *SecondStoreEv =
694 cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
695 APInt SecondStride = getStoreStride(SecondStoreEv);
696
697 if (FirstStride != SecondStride)
698 continue;
699
700 Value *SecondStoredVal = SL[k]->getValueOperand();
701 Value *SecondSplatValue = nullptr;
702 Constant *SecondPatternValue = nullptr;
703
704 if (For == ForMemset::Yes)
705 SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL);
706 else
707 SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
708
709 assert((SecondSplatValue || SecondPatternValue) &&
710 "Expected either splat value or pattern value.");
711
712 if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
713 if (For == ForMemset::Yes) {
714 if (FirstSplatValue != SecondSplatValue)
715 continue;
716 } else {
717 if (FirstPatternValue != SecondPatternValue)
718 continue;
719 }
720 Tails.insert(SL[k]);
721 Heads.insert(SL[i]);
722 ConsecutiveChain[SL[i]] = SL[k];
723 break;
724 }
725 }
726 }
727
728 // We may run into multiple chains that merge into a single chain. We mark the
729 // stores that we transformed so that we don't visit the same store twice.
730 SmallPtrSet<Value *, 16> TransformedStores;
731 bool Changed = false;
732
733 // For stores that start but don't end a link in the chain:
734 for (StoreInst *I : Heads) {
735 if (Tails.count(I))
736 continue;
737
738 // We found a store instr that starts a chain. Now follow the chain and try
739 // to transform it.
740 SmallPtrSet<Instruction *, 8> AdjacentStores;
741 StoreInst *HeadStore = I;
742 unsigned StoreSize = 0;
743
744 // Collect the chain into a list.
745 while (Tails.count(I) || Heads.count(I)) {
746 if (TransformedStores.count(I))
747 break;
748 AdjacentStores.insert(I);
749
750 StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
751 // Move to the next value in the chain.
752 I = ConsecutiveChain[I];
753 }
754
755 Value *StoredVal = HeadStore->getValueOperand();
756 Value *StorePtr = HeadStore->getPointerOperand();
757 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
758 APInt Stride = getStoreStride(StoreEv);
759
760 // Check to see if the stride matches the size of the stores. If so, then
761 // we know that every byte is touched in the loop.
762 if (StoreSize != Stride && StoreSize != -Stride)
763 continue;
764
765 bool IsNegStride = StoreSize == -Stride;
766
767 Type *IntIdxTy = DL->getIndexType(StorePtr->getType());
768 const SCEV *StoreSizeSCEV = SE->getConstant(IntIdxTy, StoreSize);
769 if (processLoopStridedStore(StorePtr, StoreSizeSCEV,
770 MaybeAlign(HeadStore->getAlign()), StoredVal,
771 HeadStore, AdjacentStores, StoreEv, BECount,
772 IsNegStride)) {
773 TransformedStores.insert_range(AdjacentStores);
774 Changed = true;
775 }
776 }
777
778 return Changed;
779}
780
781/// processLoopMemIntrinsic - Template function for calling different processor
782/// functions based on mem intrinsic type.
783template <typename MemInst>
784bool LoopIdiomRecognize::processLoopMemIntrinsic(
785 BasicBlock *BB,
786 bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
787 const SCEV *BECount) {
788 bool MadeChange = false;
789 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
790 Instruction *Inst = &*I++;
791 // Look for memory instructions, which may be optimized to a larger one.
792 if (MemInst *MI = dyn_cast<MemInst>(Inst)) {
793 WeakTrackingVH InstPtr(&*I);
794 if (!(this->*Processor)(MI, BECount))
795 continue;
796 MadeChange = true;
797
798 // If processing the instruction invalidated our iterator, start over from
799 // the top of the block.
800 if (!InstPtr)
801 I = BB->begin();
802 }
803 }
804 return MadeChange;
805}
806
807/// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy
808bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI,
809 const SCEV *BECount) {
810 // We can only handle non-volatile memcpys with a constant size.
811 if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength()))
812 return false;
813
814 // If we're not allowed to hack on memcpy, we fail. We don't mess with the
815 // inlined version as generating a larger inline mempcy could affect code
816 // size.
817 if (!HasMemcpy || MCI->isForceInlined() || DisableLIRP::Memcpy)
818 return false;
819
820 Value *Dest = MCI->getDest();
821 Value *Source = MCI->getSource();
822 if (!Dest || !Source)
823 return false;
824
825 // See if the load and store pointer expressions are AddRec like {base,+,1} on
826 // the current loop, which indicates a strided load and store. If we have
827 // something else, it's a random load or store we can't handle.
828 const SCEV *StoreEv = SE->getSCEV(Dest);
829 const SCEV *LoadEv = SE->getSCEV(Source);
830 const APInt *StoreStrideValue, *LoadStrideValue;
831 if (!match(StoreEv,
832 m_scev_AffineAddRec(m_SCEV(), m_scev_APInt(StoreStrideValue),
833 m_SpecificLoop(CurLoop))) ||
834 !match(LoadEv,
835 m_scev_AffineAddRec(m_SCEV(), m_scev_APInt(LoadStrideValue),
836 m_SpecificLoop(CurLoop))))
837 return false;
838
839 // Reject memcpys that are so large that they overflow an unsigned.
840 uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue();
841 if ((SizeInBytes >> 32) != 0)
842 return false;
843
844 // Huge stride value - give up
845 if (StoreStrideValue->getBitWidth() > 64 ||
846 LoadStrideValue->getBitWidth() > 64)
847 return false;
848
849 if (SizeInBytes != *StoreStrideValue && SizeInBytes != -*StoreStrideValue) {
850 ORE.emit([&]() {
851 return OptimizationRemarkMissed(DEBUG_TYPE, "SizeStrideUnequal", MCI)
852 << ore::NV("Inst", "memcpy") << " in "
853 << ore::NV("Function", MCI->getFunction())
854 << " function will not be hoisted: "
855 << ore::NV("Reason", "memcpy size is not equal to stride");
856 });
857 return false;
858 }
859
860 int64_t StoreStrideInt = StoreStrideValue->getSExtValue();
861 int64_t LoadStrideInt = LoadStrideValue->getSExtValue();
862 // Check if the load stride matches the store stride.
863 if (StoreStrideInt != LoadStrideInt)
864 return false;
865
866 return processLoopStoreOfLoopLoad(
867 Dest, Source, SE->getConstant(Dest->getType(), SizeInBytes),
868 MCI->getDestAlign(), MCI->getSourceAlign(), MCI, MCI,
869 cast<SCEVAddRecExpr>(StoreEv), cast<SCEVAddRecExpr>(LoadEv), BECount);
870}
871
872/// processLoopMemSet - See if this memset can be promoted to a large memset.
873bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
874 const SCEV *BECount) {
875 // We can only handle non-volatile memsets.
876 if (MSI->isVolatile())
877 return false;
878
879 // If we're not allowed to hack on memset, we fail. We don't mess with the
880 // inlined version as generating a larger memset could affect code size.
881 if (!HasMemset || MSI->isForceInlined() || DisableLIRP::Memset)
882 return false;
883
884 Value *Pointer = MSI->getDest();
885
886 // See if the pointer expression is an AddRec like {base,+,1} on the current
887 // loop, which indicates a strided store. If we have something else, it's a
888 // random store we can't handle.
889 const SCEV *Ev = SE->getSCEV(Pointer);
890 const SCEV *PointerStrideSCEV;
891 if (!match(Ev, m_scev_AffineAddRec(m_SCEV(), m_SCEV(PointerStrideSCEV),
892 m_SpecificLoop(CurLoop)))) {
893 LLVM_DEBUG(dbgs() << " Pointer is not affine, abort\n");
894 return false;
895 }
896
897 SCEVUse MemsetSizeSCEV = SE->getSCEV(MSI->getLength());
898
899 bool IsNegStride = false;
900 const bool IsConstantSize = isa<ConstantInt>(MSI->getLength());
901
902 if (IsConstantSize) {
903 // Memset size is constant.
904 // Check if the pointer stride matches the memset size. If so, then
905 // we know that every byte is touched in the loop.
906 LLVM_DEBUG(dbgs() << " memset size is constant\n");
907 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
908 const APInt *Stride;
909 if (!match(PointerStrideSCEV, m_scev_APInt(Stride)))
910 return false;
911
912 if (SizeInBytes != *Stride && SizeInBytes != -*Stride)
913 return false;
914
915 IsNegStride = SizeInBytes == -*Stride;
916 } else {
917 // Memset size is non-constant.
918 // Check if the pointer stride matches the memset size.
919 // To be conservative, the pass would not promote pointers that aren't in
920 // address space zero. Also, the pass only handles memset length and stride
921 // that are invariant for the top level loop.
922 LLVM_DEBUG(dbgs() << " memset size is non-constant\n");
923 if (Pointer->getType()->getPointerAddressSpace() != 0) {
924 LLVM_DEBUG(dbgs() << " pointer is not in address space zero, "
925 << "abort\n");
926 return false;
927 }
928 if (!SE->isLoopInvariant(MemsetSizeSCEV, CurLoop)) {
929 LLVM_DEBUG(dbgs() << " memset size is not a loop-invariant, "
930 << "abort\n");
931 return false;
932 }
933
934 // Compare positive direction PointerStrideSCEV with MemsetSizeSCEV
935 IsNegStride = PointerStrideSCEV->isNonConstantNegative();
936 SCEVUse PositiveStrideSCEV =
937 IsNegStride ? SCEVUse(SE->getNegativeSCEV(PointerStrideSCEV))
938 : SCEVUse(PointerStrideSCEV);
939 LLVM_DEBUG(dbgs() << " MemsetSizeSCEV: " << *MemsetSizeSCEV << "\n"
940 << " PositiveStrideSCEV: " << *PositiveStrideSCEV
941 << "\n");
942
943 if (PositiveStrideSCEV != MemsetSizeSCEV) {
944 // If an expression is covered by the loop guard, compare again and
945 // proceed with optimization if equal.
946 const SCEV *FoldedPositiveStride =
947 SE->applyLoopGuards(PositiveStrideSCEV, CurLoop);
948 const SCEV *FoldedMemsetSize =
949 SE->applyLoopGuards(MemsetSizeSCEV, CurLoop);
950
951 LLVM_DEBUG(dbgs() << " Try to fold SCEV based on loop guard\n"
952 << " FoldedMemsetSize: " << *FoldedMemsetSize << "\n"
953 << " FoldedPositiveStride: " << *FoldedPositiveStride
954 << "\n");
955
956 if (FoldedPositiveStride != FoldedMemsetSize) {
957 LLVM_DEBUG(dbgs() << " SCEV don't match, abort\n");
958 return false;
959 }
960 }
961 }
962
963 // Verify that the memset value is loop invariant. If not, we can't promote
964 // the memset.
965 Value *SplatValue = MSI->getValue();
966 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
967 return false;
968
970 MSIs.insert(MSI);
971 return processLoopStridedStore(Pointer, SE->getSCEV(MSI->getLength()),
972 MSI->getDestAlign(), SplatValue, MSI, MSIs,
973 cast<SCEVAddRecExpr>(Ev), BECount, IsNegStride,
974 /*IsLoopMemset=*/true);
975}
976
977/// Return true if \p I is a (simple, loop-invariant-valued) store of the same
978/// bytewise value \p SplatByte.
979static bool isSameByteValueStore(Instruction &I, Value *SplatByte, Loop *L,
980 const DataLayout &DL) {
981 assert(SplatByte && "expected a bytewise splat value to match against");
982 auto *SI = dyn_cast<StoreInst>(&I);
983 if (!SI || !SI->isSimple() || !L->isLoopInvariant(SI->getValueOperand()))
984 return false;
985 return isBytewiseValue(SI->getValueOperand(), DL) == SplatByte;
986}
987
988/// mayLoopAccessLocation - Return true if the specified loop might access the
989/// specified pointer location, which is a loop-strided access. The 'Access'
990/// argument specifies what the verboten forms of access are (read or write).
991///
992/// When the access size cannot be bounded, fall back to allow stores writing
993/// the same byte value \p SplatByte.
995 const SCEV *BECount,
996 const SCEV *StoreSizeSCEV, AliasAnalysis &AA,
997 SmallPtrSetImpl<Instruction *> &IgnoredInsts,
998 Value *SplatByte = nullptr,
999 const DataLayout *DL = nullptr) {
1000 // Get the location that may be stored across the loop. Since the access is
1001 // strided positively through memory, we say that the modified location starts
1002 // at the pointer and has infinite size.
1004
1005 // If the loop iterates a fixed number of times, we can refine the access size
1006 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
1007 const APInt *BECst, *ConstSize;
1008 if (match(BECount, m_scev_APInt(BECst)) &&
1009 match(StoreSizeSCEV, m_scev_APInt(ConstSize))) {
1010 std::optional<uint64_t> BEInt = BECst->tryZExtValue();
1011 std::optional<uint64_t> SizeInt = ConstSize->tryZExtValue();
1012 // FIXME: Should this check for overflow?
1013 if (BEInt && SizeInt)
1014 AccessSize = LocationSize::precise((*BEInt + 1) * *SizeInt);
1015 }
1016
1017 // TODO: For this to be really effective, we have to dive into the pointer
1018 // operand in the store. Store to &A[i] of 100 will always return may alias
1019 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
1020 // which will then no-alias a store to &A[100].
1021 MemoryLocation StoreLoc(Ptr, AccessSize);
1022
1023 // Only consult the same-byte-value fallback when the access size stayed
1024 // infinite (non-constant trip count); with a precise size AA is accurate.
1025 bool TrySameByteValue = !AccessSize.isPrecise() && SplatByte && DL;
1026
1027 for (BasicBlock *B : L->blocks())
1028 for (Instruction &I : *B)
1029 if (!IgnoredInsts.contains(&I) &&
1030 isModOrRefSet(AA.getModRefInfo(&I, StoreLoc) & Access)) {
1031 if (TrySameByteValue && isSameByteValueStore(I, SplatByte, L, *DL))
1032 continue;
1033 return true;
1034 }
1035 return false;
1036}
1037
1038// If we have a negative stride, Start refers to the end of the memory location
1039// we're trying to memset. Therefore, we need to recompute the base pointer,
1040// which is just Start - BECount*Size.
1041static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
1042 Type *IntPtr, const SCEV *StoreSizeSCEV,
1043 ScalarEvolution *SE) {
1044 const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
1045 if (!StoreSizeSCEV->isOne()) {
1046 // index = back edge count * store size
1047 Index = SE->getMulExpr(Index,
1048 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
1050 }
1051 // base pointer = start - index * store size
1052 return SE->getMinusSCEV(Start, Index);
1053}
1054
1055/// Compute the number of bytes as a SCEV from the backedge taken count.
1056///
1057/// This also maps the SCEV into the provided type and tries to handle the
1058/// computation in a way that will fold cleanly.
1059static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
1060 const SCEV *StoreSizeSCEV, Loop *CurLoop,
1061 const DataLayout *DL, ScalarEvolution *SE) {
1062 const SCEV *TripCountSCEV =
1063 SE->getTripCountFromExitCount(BECount, IntPtr, CurLoop);
1064 return SE->getMulExpr(TripCountSCEV,
1065 SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
1067}
1068
1069/// Add a range to the length (or, for memset.pattern, the count) of a newly
1070/// formed memset/memset.pattern/memmove/memcpy intrinsic, with an upper bound
1071/// derived from the loop's constant max backedge-taken count (BTC). Only small
1072/// bounds are worth recording, e.g. to expand the call inline instead of
1073/// calling the library function, so bail if the bound exceeds a cap.
1074static void addRangeAttrFromTripCount(CallInst *NewCall, uint64_t ElemsPerIter,
1075 Loop *L, ScalarEvolution *SE) {
1076 Use *LenUse;
1077 if (auto *MSP = dyn_cast<MemSetPatternInst>(NewCall))
1078 LenUse = &MSP->getLengthUse();
1079 else if (auto *MI = dyn_cast<AnyMemIntrinsic>(NewCall))
1080 LenUse = &MI->getLengthUse();
1081 else
1082 llvm_unreachable("Expected a memset.pattern or a memory intrinsic");
1083
1084 // Bail if already a constant (range would be a constant too).
1085 if (isa<Constant>(LenUse->get()))
1086 return;
1087
1088 // Cap all contributing parts at 64k (large upper bounds are not useful).
1089 constexpr uint64_t MaxBoundedLen = 1 << 16;
1090
1091 if (ElemsPerIter > MaxBoundedLen)
1092 return;
1093 const APInt *MaxBTC;
1095 return;
1096 if (MaxBTC->uge(MaxBoundedLen))
1097 return;
1098
1099 // The length is in [0, (MaxBTC + 1) * ElemsPerIter]. Both factors are capped,
1100 // so this can't overflow.
1101 uint64_t MaxLen = (MaxBTC->getZExtValue() + 1) * ElemsPerIter;
1102 if (MaxLen > MaxBoundedLen)
1103 return;
1104
1105 // ConstantRange's upper end is exclusive, so the range ends at MaxLen + 1,
1106 // which must fit in the length's type.
1107 uint64_t RangeEnd = MaxLen + 1;
1108 unsigned BW = LenUse->get()->getType()->getIntegerBitWidth();
1109 if (RangeEnd > maxUIntN(BW))
1110 return;
1111
1112 NewCall->addParamAttr(
1113 LenUse->getOperandNo(),
1114 Attribute::get(NewCall->getContext(), Attribute::Range,
1115 ConstantRange(APInt::getZero(BW), APInt(BW, RangeEnd))));
1116}
1117
1118/// processLoopStridedStore - We see a strided store of some value. If we can
1119/// transform this into a memset or memset_pattern in the loop preheader, do so.
1120bool LoopIdiomRecognize::processLoopStridedStore(
1121 Value *DestPtr, const SCEV *StoreSizeSCEV, MaybeAlign StoreAlignment,
1122 Value *StoredVal, Instruction *TheStore,
1124 const SCEV *BECount, bool IsNegStride, bool IsLoopMemset) {
1125 // We currently don't convert inline intrinsics into larger ones, to avoid
1126 // code size increase. `processLoopMemSet` checks that the intrinsic is not
1127 // inline before calling this function.
1128 assert((isa<StoreInst>(TheStore) ||
1129 !cast<MemIntrinsic>(TheStore)->isForceInlined()) &&
1130 "inline mem intrinsics should be filtered out by callers");
1131
1132 Module *M = TheStore->getModule();
1133
1134 // The trip count of the loop and the base pointer of the addrec SCEV is
1135 // guaranteed to be loop invariant, which means that it should dominate the
1136 // header. This allows us to insert code for it in the preheader.
1137 unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
1138 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1139 IRBuilder<> Builder(Preheader->getTerminator());
1140 SCEVExpander Expander(*SE, "loop-idiom");
1141 SCEVExpanderCleaner ExpCleaner(Expander);
1142
1143 Type *DestInt8PtrTy = Builder.getPtrTy(DestAS);
1144 Type *IntIdxTy = DL->getIndexType(DestPtr->getType());
1145
1146 bool Changed = false;
1147 const SCEV *Start = Ev->getStart();
1148 // Handle negative strided loops.
1149 if (IsNegStride)
1150 Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSizeSCEV, SE);
1151
1152 // TODO: ideally we should still be able to generate memset if SCEV expander
1153 // is taught to generate the dependencies at the latest point.
1154 if (!Expander.isSafeToExpand(Start))
1155 return Changed;
1156
1157 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
1158 // this into a memset in the loop preheader now if we want. However, this
1159 // would be unsafe to do if there is anything else in the loop that may read
1160 // or write to the aliased location. Check for any overlap by generating the
1161 // base pointer and checking the region.
1162 Value *BasePtr =
1163 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
1164
1165 // From here on out, conservatively report to the pass manager that we've
1166 // changed the IR, even if we later clean up these added instructions. There
1167 // may be structural differences e.g. in the order of use lists not accounted
1168 // for in just a textual dump of the IR. This is written as a variable, even
1169 // though statically all the places this dominates could be replaced with
1170 // 'true', with the hope that anyone trying to be clever / "more precise" with
1171 // the return value will read this comment, and leave them alone.
1172 Changed = true;
1173
1174 Value *SplatValue = isBytewiseValue(StoredVal, *DL);
1175 if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1176 StoreSizeSCEV, *AA, Stores, SplatValue, DL))
1177 return Changed;
1178
1179 if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
1180 return Changed;
1181
1182 // Okay, everything looks good, insert the memset.
1183 Constant *PatternValue = nullptr;
1184 if (!SplatValue)
1185 PatternValue = getMemSetPatternValue(StoredVal, DL);
1186
1187 // MemsetArg is the number of bytes for the memset libcall, and the number
1188 // of pattern repetitions if the memset.pattern intrinsic is being used.
1189 Value *MemsetArg;
1190 std::optional<int64_t> BytesWritten;
1191 uint64_t PatternRepsPerTrip = 0;
1192
1193 if (PatternValue &&
1194 (HasMemsetPattern || Opts.loop_idiom_force_memset_pattern_intrinsic)) {
1195 const SCEV *TripCountS =
1196 SE->getTripCountFromExitCount(BECount, IntIdxTy, CurLoop);
1197 if (!Expander.isSafeToExpand(TripCountS))
1198 return Changed;
1199 const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1200 if (!ConstStoreSize)
1201 return Changed;
1202 Value *TripCount = Expander.expandCodeFor(TripCountS, IntIdxTy,
1203 Preheader->getTerminator());
1204 PatternRepsPerTrip = (ConstStoreSize->getValue()->getZExtValue() * 8) /
1205 DL->getTypeSizeInBits(PatternValue->getType());
1206 // If ConstStoreSize is not equal to the width of PatternValue, then
1207 // MemsetArg is TripCount * (ConstStoreSize/PatternValueWidth). Else
1208 // MemSetArg is just TripCount.
1209 MemsetArg =
1210 PatternRepsPerTrip == 1
1211 ? TripCount
1212 : Builder.CreateMul(TripCount,
1213 Builder.getIntN(IntIdxTy->getIntegerBitWidth(),
1214 PatternRepsPerTrip));
1215 if (auto *CI = dyn_cast<ConstantInt>(TripCount))
1216 BytesWritten =
1217 CI->getZExtValue() * ConstStoreSize->getValue()->getZExtValue();
1218
1219 } else {
1220 const SCEV *NumBytesS =
1221 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
1222
1223 // TODO: ideally we should still be able to generate memset if SCEV expander
1224 // is taught to generate the dependencies at the latest point.
1225 if (!Expander.isSafeToExpand(NumBytesS))
1226 return Changed;
1227 MemsetArg =
1228 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1229 if (auto *CI = dyn_cast<ConstantInt>(MemsetArg))
1230 BytesWritten = CI->getZExtValue();
1231 }
1232 assert(MemsetArg && "MemsetArg should have been set");
1233
1234 AAMDNodes AATags = TheStore->getAAMetadata();
1235 for (Instruction *Store : Stores)
1236 AATags = AATags.merge(Store->getAAMetadata());
1237 if (BytesWritten)
1238 AATags = AATags.extendTo(BytesWritten.value());
1239 else
1240 AATags = AATags.extendTo(-1);
1241
1242 CallInst *NewCall;
1243 if (SplatValue) {
1244 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, MemsetArg,
1245 MaybeAlign(StoreAlignment),
1246 /*isVolatile=*/false, AATags);
1247 if (auto *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV)) {
1249 NewCall, ConstStoreSize->getValue()->getZExtValue(), CurLoop, SE);
1250 }
1251 } else if (Opts.loop_idiom_force_memset_pattern_intrinsic ||
1252 isLibFuncEmittable(M, TLI, LibFunc_memset_pattern16)) {
1253 assert(isa<SCEVConstant>(StoreSizeSCEV) && "Expected constant store size");
1254
1255 NewCall = Builder.CreateIntrinsicWithoutFolding(
1256 Intrinsic::experimental_memset_pattern,
1257 {DestInt8PtrTy, PatternValue->getType(), IntIdxTy},
1258 {BasePtr, PatternValue, MemsetArg,
1259 ConstantInt::getFalse(M->getContext())});
1260 if (StoreAlignment)
1261 cast<MemSetPatternInst>(NewCall)->setDestAlignment(*StoreAlignment);
1262 NewCall->setAAMetadata(AATags);
1263 assert(PatternRepsPerTrip != 0 && "PatternRepsPerTrip must be set");
1264 addRangeAttrFromTripCount(NewCall, PatternRepsPerTrip, CurLoop, SE);
1265 } else {
1266 // Neither a memset, nor memset_pattern16
1267 return Changed;
1268 }
1269
1270 NewCall->setDebugLoc(TheStore->getDebugLoc());
1271
1272 if (MSSAU) {
1273 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1274 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1275 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1276 }
1277
1278 LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
1279 << " from store to: " << *Ev << " at: " << *TheStore
1280 << "\n");
1281
1282 ORE.emit([&]() {
1283 OptimizationRemark R(DEBUG_TYPE, "ProcessLoopStridedStore",
1284 NewCall->getDebugLoc(), Preheader);
1285 R << "Transformed loop-strided store in "
1286 << ore::NV("Function", TheStore->getFunction())
1287 << " function into a call to "
1288 << ore::NV("NewFunction", NewCall->getCalledFunction())
1289 << "() intrinsic";
1290 if (!Stores.empty())
1291 R << ore::setExtraArgs();
1292 for (auto *I : Stores) {
1293 R << ore::NV("FromBlock", I->getParent()->getName())
1294 << ore::NV("ToBlock", Preheader->getName());
1295 }
1296 return R;
1297 });
1298
1299 // Okay, the memset has been formed. Zap the original store and anything that
1300 // feeds into it.
1301 for (auto *I : Stores) {
1302 if (MSSAU)
1303 MSSAU->removeMemoryAccess(I, true);
1305 }
1306 if (MSSAU && VerifyMemorySSA)
1307 MSSAU->getMemorySSA()->verifyMemorySSA();
1308 ++NumMemSet;
1309 ExpCleaner.markResultUsed();
1310 return true;
1311}
1312
1313/// If the stored value is a strided load in the same loop with the same stride
1314/// this may be transformable into a memcpy. This kicks in for stuff like
1315/// for (i) A[i] = B[i];
1316bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
1317 const SCEV *BECount) {
1318 assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
1319
1320 Value *StorePtr = SI->getPointerOperand();
1321 const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1322 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
1323
1324 // The store must be feeding a non-volatile load.
1325 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1326 assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
1327
1328 // See if the pointer expression is an AddRec like {base,+,1} on the current
1329 // loop, which indicates a strided load. If we have something else, it's a
1330 // random load we can't handle.
1331 Value *LoadPtr = LI->getPointerOperand();
1332 const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1333
1334 const SCEV *StoreSizeSCEV = SE->getConstant(StorePtr->getType(), StoreSize);
1335 return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSizeSCEV,
1336 SI->getAlign(), LI->getAlign(), SI, LI,
1337 StoreEv, LoadEv, BECount);
1338}
1339
1340namespace {
1341class MemmoveVerifier {
1342public:
1343 explicit MemmoveVerifier(const SCEV &LoadStart, const SCEV &StoreStart,
1344 ScalarEvolution &SE)
1345 : DL(SE.getDataLayout()),
1346 Off(dyn_cast<SCEVConstant>(SE.getMinusSCEV(&StoreStart, &LoadStart))),
1347 BasePtr(dyn_cast<SCEVUnknown>(SE.getPointerBase(&StoreStart))),
1348 IsSameObject(Off != nullptr) {}
1349
1350 bool loadAndStoreMayFormMemmove(unsigned StoreSize, bool IsNegStride,
1351 const Instruction &TheLoad,
1352 bool IsMemCpy) const {
1353 // The store must be at a constant offset from the load, and there must be
1354 // an underlying pointer.
1355 if (!Off || !BasePtr)
1356 return false;
1357 const APInt &OffVal = Off->getAPInt();
1358 // If null is defined then the base pointer can't be null
1359 auto *NullBase = dyn_cast<ConstantPointerNull>(BasePtr->getValue());
1360 if (NullBase && NullPointerIsDefined(
1361 TheLoad.getParent()->getParent(),
1362 NullBase->getPointerType()->getPointerAddressSpace()))
1363 return false;
1364 int64_t LoadSize;
1365 if (IsMemCpy) {
1366 // memcpy is equivalent to a sequence of byte loads and stores
1367 LoadSize = 1;
1368 } else {
1369 LoadSize = DL.getTypeSizeInBits(TheLoad.getType()).getFixedValue() / 8;
1370 if (LoadSize != StoreSize)
1371 return false;
1372 }
1373 // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr
1374 // for negative stride. LoadBasePtr shouldn't overlap with StoreBasePtr.
1375 if (IsNegStride ? OffVal.slt(LoadSize) : OffVal.sgt(-LoadSize))
1376 return false;
1377 return true;
1378 }
1379
1380private:
1381 const DataLayout &DL;
1382 const SCEVConstant *Off;
1383 const SCEVUnknown *BasePtr;
1384
1385public:
1386 const bool IsSameObject;
1387};
1388} // namespace
1389
1390bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
1391 Value *DestPtr, Value *SourcePtr, const SCEV *StoreSizeSCEV,
1392 MaybeAlign StoreAlign, MaybeAlign LoadAlign, Instruction *TheStore,
1393 Instruction *TheLoad, const SCEVAddRecExpr *StoreEv,
1394 const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
1395 // We currently don't convert inline intrinsics into larger ones, to avoid
1396 // code size increase. `processLoopMemCpy` checks that the intrinsic is not
1397 // inline before calling this function.
1398 assert((isa<StoreInst>(TheStore) ||
1399 !cast<MemIntrinsic>(TheStore)->isForceInlined()) &&
1400 "inline mem intrinsics should be filtered out by callers");
1401
1402 // The trip count of the loop and the base pointer of the addrec SCEV is
1403 // guaranteed to be loop invariant, which means that it should dominate the
1404 // header. This allows us to insert code for it in the preheader.
1405 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1406 IRBuilder<> Builder(Preheader->getTerminator());
1407 SCEVExpander Expander(*SE, "loop-idiom");
1408
1409 SCEVExpanderCleaner ExpCleaner(Expander);
1410
1411 bool Changed = false;
1412 const SCEV *StrStart = StoreEv->getStart();
1413 unsigned StrAS = DestPtr->getType()->getPointerAddressSpace();
1414 Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS));
1415
1416 APInt Stride = getStoreStride(StoreEv);
1417 const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1418
1419 // TODO: Deal with non-constant size; Currently expect constant store size
1420 assert(ConstStoreSize && "store size is expected to be a constant");
1421
1422 int64_t StoreSize = ConstStoreSize->getValue()->getZExtValue();
1423 bool IsNegStride = StoreSize == -Stride;
1424
1425 // Handle negative strided loops.
1426 if (IsNegStride)
1427 StrStart =
1428 getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1429
1430 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
1431 // this into a memcpy in the loop preheader now if we want. However, this
1432 // would be unsafe to do if there is anything else in the loop that may read
1433 // or write the memory region we're storing to. This includes the load that
1434 // feeds the stores. Check for an alias by generating the base address and
1435 // checking everything.
1436 Value *StoreBasePtr = Expander.expandCodeFor(
1437 StrStart, Builder.getPtrTy(StrAS), Preheader->getTerminator());
1438
1439 // From here on out, conservatively report to the pass manager that we've
1440 // changed the IR, even if we later clean up these added instructions. There
1441 // may be structural differences e.g. in the order of use lists not accounted
1442 // for in just a textual dump of the IR. This is written as a variable, even
1443 // though statically all the places this dominates could be replaced with
1444 // 'true', with the hope that anyone trying to be clever / "more precise" with
1445 // the return value will read this comment, and leave them alone.
1446 Changed = true;
1447
1448 SmallPtrSet<Instruction *, 2> IgnoredInsts;
1449 IgnoredInsts.insert(TheStore);
1450
1451 bool IsMemCpy = isa<MemCpyInst>(TheStore);
1452 const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store";
1453
1454 bool LoopAccessStore =
1455 mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1456 StoreSizeSCEV, *AA, IgnoredInsts);
1457 if (LoopAccessStore) {
1458 // For memmove case it's not enough to guarantee that loop doesn't access
1459 // TheStore and TheLoad. Additionally we need to make sure that TheStore is
1460 // the only user of TheLoad.
1461 if (!TheLoad->hasOneUse())
1462 return Changed;
1463 IgnoredInsts.insert(TheLoad);
1464 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
1465 BECount, StoreSizeSCEV, *AA, IgnoredInsts)) {
1466 ORE.emit([&]() {
1467 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessStore",
1468 TheStore)
1469 << ore::NV("Inst", InstRemark) << " in "
1470 << ore::NV("Function", TheStore->getFunction())
1471 << " function will not be hoisted: "
1472 << ore::NV("Reason", "The loop may access store location");
1473 });
1474 return Changed;
1475 }
1476 IgnoredInsts.erase(TheLoad);
1477 }
1478
1479 const SCEV *LdStart = LoadEv->getStart();
1480 unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace();
1481
1482 // Handle negative strided loops.
1483 if (IsNegStride)
1484 LdStart =
1485 getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1486
1487 // For a memcpy, we have to make sure that the input array is not being
1488 // mutated by the loop.
1489 Value *LoadBasePtr = Expander.expandCodeFor(LdStart, Builder.getPtrTy(LdAS),
1490 Preheader->getTerminator());
1491
1492 // If the store is a memcpy instruction, we must check if it will write to
1493 // the load memory locations. So remove it from the ignored stores.
1494 MemmoveVerifier Verifier(*LdStart, *StrStart, *SE);
1495 if (IsMemCpy && !Verifier.IsSameObject)
1496 IgnoredInsts.erase(TheStore);
1497 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1498 StoreSizeSCEV, *AA, IgnoredInsts)) {
1499 ORE.emit([&]() {
1500 return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessLoad", TheLoad)
1501 << ore::NV("Inst", InstRemark) << " in "
1502 << ore::NV("Function", TheStore->getFunction())
1503 << " function will not be hoisted: "
1504 << ore::NV("Reason", "The loop may access load location");
1505 });
1506 return Changed;
1507 }
1508
1509 bool IsAtomic = TheStore->isAtomic() || TheLoad->isAtomic();
1510 bool UseMemMove = IsMemCpy ? Verifier.IsSameObject : LoopAccessStore;
1511
1512 if (IsAtomic) {
1513 // For now don't support unordered atomic memmove.
1514 if (UseMemMove)
1515 return Changed;
1516
1517 // We cannot allow unaligned ops for unordered load/store, so reject
1518 // anything where the alignment isn't at least the element size.
1519 assert((StoreAlign && LoadAlign) &&
1520 "Expect unordered load/store to have align.");
1521 if (*StoreAlign < StoreSize || *LoadAlign < StoreSize)
1522 return Changed;
1523
1524 // If the element.atomic memcpy is not lowered into explicit
1525 // loads/stores later, then it will be lowered into an element-size
1526 // specific lib call. If the lib call doesn't exist for our store size, then
1527 // we shouldn't generate the memcpy.
1528 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1529 return Changed;
1530 }
1531
1532 if (UseMemMove)
1533 if (!Verifier.loadAndStoreMayFormMemmove(StoreSize, IsNegStride, *TheLoad,
1534 IsMemCpy))
1535 return Changed;
1536
1537 if (avoidLIRForMultiBlockLoop())
1538 return Changed;
1539
1540 // Okay, everything is safe, we can transform this!
1541
1542 const SCEV *NumBytesS =
1543 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
1544
1545 Value *NumBytes =
1546 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1547
1548 AAMDNodes AATags = TheLoad->getAAMetadata();
1549 AAMDNodes StoreAATags = TheStore->getAAMetadata();
1550 AATags = AATags.merge(StoreAATags);
1551 if (auto CI = dyn_cast<ConstantInt>(NumBytes))
1552 AATags = AATags.extendTo(CI->getZExtValue());
1553 else
1554 AATags = AATags.extendTo(-1);
1555
1556 CallInst *NewCall = nullptr;
1557 // Check whether to generate an unordered atomic memcpy:
1558 // If the load or store are atomic, then they must necessarily be unordered
1559 // by previous checks.
1560 if (!IsAtomic) {
1561 if (UseMemMove)
1562 NewCall = Builder.CreateMemMove(StoreBasePtr, StoreAlign, LoadBasePtr,
1563 LoadAlign, NumBytes,
1564 /*isVolatile=*/false, AATags);
1565 else
1566 NewCall =
1567 Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign,
1568 NumBytes, /*isVolatile=*/false, AATags);
1569 } else {
1570 // Create the call.
1571 // Note that unordered atomic loads/stores are *required* by the spec to
1572 // have an alignment but non-atomic loads/stores may not.
1573 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1574 StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, StoreSize,
1575 AATags);
1576 }
1577 addRangeAttrFromTripCount(NewCall, StoreSize, CurLoop, SE);
1578 NewCall->setDebugLoc(TheStore->getDebugLoc());
1579
1580 if (MSSAU) {
1581 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1582 NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1583 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1584 }
1585
1586 LLVM_DEBUG(dbgs() << " Formed new call: " << *NewCall << "\n"
1587 << " from load ptr=" << *LoadEv << " at: " << *TheLoad
1588 << "\n"
1589 << " from store ptr=" << *StoreEv << " at: " << *TheStore
1590 << "\n");
1591
1592 ORE.emit([&]() {
1593 return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad",
1594 NewCall->getDebugLoc(), Preheader)
1595 << "Formed a call to "
1596 << ore::NV("NewFunction", NewCall->getCalledFunction())
1597 << "() intrinsic from " << ore::NV("Inst", InstRemark)
1598 << " instruction in " << ore::NV("Function", TheStore->getFunction())
1599 << " function"
1601 << ore::NV("FromBlock", TheStore->getParent()->getName())
1602 << ore::NV("ToBlock", Preheader->getName());
1603 });
1604
1605 // Okay, a new call to memcpy/memmove has been formed. Zap the original store
1606 // and anything that feeds into it.
1607 if (MSSAU)
1608 MSSAU->removeMemoryAccess(TheStore, true);
1609 deleteDeadInstruction(TheStore);
1610 if (MSSAU && VerifyMemorySSA)
1611 MSSAU->getMemorySSA()->verifyMemorySSA();
1612 if (UseMemMove)
1613 ++NumMemMove;
1614 else
1615 ++NumMemCpy;
1616 ExpCleaner.markResultUsed();
1617 return true;
1618}
1619
1620// When compiling for codesize we avoid idiom recognition for a multi-block loop
1621// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1622//
1623bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1624 bool IsLoopMemset) {
1625 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1626 if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) {
1627 LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1628 << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1629 << " avoided: multi-block top-level loop\n");
1630 return true;
1631 }
1632 }
1633
1634 return false;
1635}
1636
1637bool LoopIdiomRecognize::optimizeCRCLoop(const PolynomialInfo &Info) {
1638 // FIXME: Hexagon has a special HexagonLoopIdiom that optimizes CRC using
1639 // carry-less multiplication instructions, which is more efficient than our
1640 // Sarwate table-lookup optimization. Hence, until we're able to emit
1641 // target-specific instructions for Hexagon, subsuming HexagonLoopIdiom,
1642 // disable the optimization for Hexagon.
1643 Module &M = *CurLoop->getHeader()->getModule();
1644 Triple TT(M.getTargetTriple());
1645 if (TT.getArch() == Triple::hexagon)
1646 return false;
1647
1648 LLVMContext &Ctx = Info.LHS->getContext();
1649 Type *CRCTy = Info.LHS->getType();
1650 unsigned CRCBW = CRCTy->getIntegerBitWidth();
1651
1652 // CRC computation is mostly serial, so latency works best for comparison.
1655
1656 InstructionCost XorCost =
1657 TTI->getArithmeticInstrCost(Instruction::Xor, CRCTy, CostKind);
1658 InstructionCost ShiftCost =
1659 TTI->getArithmeticInstrCost(Instruction::LShr, CRCTy, CostKind);
1660 InstructionCost AndCost =
1661 TTI->getArithmeticInstrCost(Instruction::And, CRCTy, CostKind);
1662 InstructionCost SelectCost =
1663 TTI->getCmpSelInstrCost(Instruction::Select, CRCTy, Type::getInt1Ty(Ctx),
1664 CmpInst::BAD_ICMP_PREDICATE, CostKind);
1665 InstructionCost LoadCost =
1666 TTI->getMemoryOpCost(Instruction::Load, CRCTy, DL->getABITypeAlign(CRCTy),
1667 DL->getDefaultGlobalsAddressSpace(), CostKind);
1668 auto ClmulCost = [&](unsigned BW) {
1669 auto *Ty = IntegerType::get(Ctx, BW);
1670 IntrinsicCostAttributes Attrs(Intrinsic::clmul, Ty, {Ty, Ty});
1671 return TTI->getIntrinsicInstrCost(Attrs, CostKind);
1672 };
1673
1674 // Estimate the cost of the original, unoptimized loop.
1675 InstructionCost OrigLoopCost =
1676 (2 * ShiftCost + 2 * XorCost + AndCost + SelectCost) * Info.TripCount;
1677
1678 // Estimate the cost of the Sarwate lookup table optimization strategy.
1679 // As mentioned previously, a byte-multiple trip count is required.
1680 InstructionCost TableStrategyCost =
1681 Info.TripCount % 8 != 0
1683 : (LoadCost + XorCost + 2 * ShiftCost) * (Info.TripCount / 8);
1684
1685 // Estimate the cost of the carry-less multiplication optimization strategy.
1686 InstructionCost ClmulStrategyCost = ClmulCost(2 * Info.TripCount) +
1687 ClmulCost(CRCBW + Info.TripCount) +
1688 2 * XorCost + 2 * ShiftCost + AndCost;
1689
1690 ORE.emit([&]() {
1691 return OptimizationRemarkAnalysis(DEBUG_TYPE, "CRCLoopCosts",
1692 CurLoop->getStartLoc(),
1693 CurLoop->getHeader())
1694 << "CRC loop costs: original="
1695 << ore::NV("OrigLoopCost", OrigLoopCost)
1696 << ", table=" << ore::NV("TableStrategyCost", TableStrategyCost)
1697 << ", clmul=" << ore::NV("ClmulStrategyCost", ClmulStrategyCost);
1698 });
1699
1700 auto ReportMissed = [&](StringRef Reason) {
1701 ORE.emit([&]() {
1702 return OptimizationRemarkMissed(DEBUG_TYPE, "CRCLoopMissed",
1703 CurLoop->getStartLoc(),
1704 CurLoop->getHeader())
1705 << "CRC loop not optimized: " << Reason;
1706 });
1707 };
1708 auto ReportOptimized = [&](StringRef Strategy, StringRef Reason) {
1709 ORE.emit([&]() {
1710 return OptimizationRemark(DEBUG_TYPE, "CRCLoopOptimized",
1711 CurLoop->getStartLoc(), CurLoop->getHeader())
1712 << "CRC loop optimized using " << ore::NV("Strategy", Strategy)
1713 << ": " << Reason;
1714 });
1715 };
1716
1717 switch (Opts.loop_idiom_crc_strategy) {
1718 default:
1719 ReportMissed("disabled by user");
1720 return false;
1722 // The table strategy is not possible in its current form without a byte-
1723 // multiple trip count.
1724 if (Info.TripCount % 8 == 0) {
1725 optimizeCRCLoopUsingTableLookup(Info);
1726 ReportOptimized("table", "forced by user");
1727 return true;
1728 }
1729 ReportMissed("table strategy forced, but not possible");
1730 return false;
1732 optimizeCRCLoopUsingClmul(Info);
1733 ReportOptimized("clmul", "forced by user");
1734 return true;
1736 // When using the auto strategy, bail if we are optimizing for size since
1737 // there's usually not a clear size benefit.
1738 // TODO: The clmul optimization is around the same size in many cases, so it
1739 // could be worth it to take advantage of that fact, especially if it would
1740 // be much faster than the original loop.
1741 if (ApplyCodeSizeHeuristics) {
1742 ReportMissed("optimizing for size");
1743 return false;
1744 }
1745
1746 // Only apply an optimization if there's a clear benefit to doing so.
1747 if (std::min(TableStrategyCost, ClmulStrategyCost) >= OrigLoopCost) {
1748 ReportMissed("no profitable strategy");
1749 return false;
1750 }
1751
1752 if (TableStrategyCost <= ClmulStrategyCost) {
1753 optimizeCRCLoopUsingTableLookup(Info);
1754 ReportOptimized("table", "most profitable strategy");
1755 } else {
1756 optimizeCRCLoopUsingClmul(Info);
1757 ReportOptimized("clmul", "most profitable strategy");
1758 }
1759 return true;
1760 }
1761}
1762
1763// The algorithm used in this optimization is a Polynomial (GF(2)) Barrett
1764// Reduction based on Intel's "Fast CRC Computation for Generic Polynomials
1765// Using PCLMULQDQ Instruction" white paper (December 2009).
1766void LoopIdiomRecognize::optimizeCRCLoopUsingClmul(const PolynomialInfo &Info) {
1767 // TODO: If clmul exists on the target but not for the required width, it
1768 // might be possible to split into multiple iterations of reduction.
1769 Type *CRCTy = Info.LHS->getType();
1770 LLVMContext &Ctx = CRCTy->getContext();
1771 unsigned CRCBW = CRCTy->getIntegerBitWidth();
1772 // The loop's TripCount determines how many bits of the data are processed,
1773 // regardless of whether the actual data bit width matches (if auxiliary data
1774 // is even used at all).
1775 unsigned TC = Info.TripCount;
1776 // Based on the clmul inputs, the first clmul needs 2*TC bits, and the second
1777 // needs CRCBW+TC bits. However, only the low TC bits of the first clmul are
1778 // used in little-endian, so a clmul in TC bits suffices in that case.
1779 IntegerType *ClmulMuTy =
1780 IntegerType::get(Ctx, Info.IsBigEndian ? 2 * TC : TC);
1781 IntegerType *ClmulGPTy = IntegerType::get(Ctx, CRCBW + TC);
1782
1783 // First, generate the constants required for GF(2) Barrett reduction.
1784 auto [Mu, FullGenPoly] = HashRecognize::genBarrettConstants(Info);
1785 Value *MuConst =
1786 ConstantInt::get(Ctx, Mu.zextOrTrunc(ClmulMuTy->getBitWidth()));
1787 Value *GenPolyConst =
1788 ConstantInt::get(Ctx, FullGenPoly.zext(ClmulGPTy->getBitWidth()));
1789
1790 IRBuilder<> Builder(CurLoop->getLoopPreheader()->getTerminator());
1791
1792 // If a shift needs to occur in the setup for the first clmul with MuConst, it
1793 // will be by abs(TC - CRCBW). To ensure that the shift can work without
1794 // losing information or creating poison, give it CRCBW + TC bits.
1795 bool SetupShiftNeeded = Info.IsBigEndian && TC != CRCBW;
1796 auto *SetupTy = IntegerType::get(Ctx, SetupShiftNeeded ? CRCBW + TC : TC);
1797
1798 // Based on the Intel white paper, in our case, we have
1799 // R(x) = (LHS*x^TC) xor (LHSAux ? getTCBits(LHSAux)*x^CRCBW : 0)
1800 // since the CRC loop multiplies LHS by x each iteration, and the x^CRCBW term
1801 // of getTCBits(LHSAux) is XORed in for the significant bit check.
1802 // Rather than compute the full R(x), we can split it in two: a quotient for
1803 // step 1 (floor(R(x)/x^CRCBW)) and a remainder for step 3 (R(x) mod x^CRCBW).
1804 //
1805 // ClmulMuInput is an evolving variable that will eventually become the part
1806 // used in step 1, which can be simplified to
1807 // (LHS*x^(TC-CRCBW)) xor (LHSAux ? getTCBits(LHSAux) : 0).
1808 // Thanks to restrictions imposed by HashRecognize for big-endian CRC loops,
1809 // getTCBits(LHSAux) = LHSAux*x^(TC-CRCBW), so this can be further simplified
1810 // to (LHS xor (LHSAux ? LHSAux : 0))*x^(TC-CRCBW).
1811 Value *ClmulMuInput =
1812 Builder.CreateZExtOrTrunc(Info.LHS, SetupTy, "crc.cast");
1813
1814 // If auxiliary data is present, XOR it in with the CRC.
1815 if (Value *Data = Info.LHSAux) {
1816 // This is usually a zext, but DataBW may exceed CRCBW+TC if both CRCBW and
1817 // TC are small enough.
1818 Data = Builder.CreateZExtOrTrunc(Data, SetupTy, "data.cast");
1819
1820 ClmulMuInput = Builder.CreateXor(ClmulMuInput, Data, "xor.crc.data");
1821 }
1822
1823 // Align the current CRC with TripCount (multiply or divide by x^(TC-CRCBW)).
1824 if (SetupShiftNeeded) {
1825 ClmulMuInput =
1826 TC > CRCBW
1827 ? Builder.CreateShl(ClmulMuInput, TC - CRCBW, "crc.align.tc")
1828 : Builder.CreateLShr(ClmulMuInput, CRCBW - TC, "crc.align.tc");
1829 }
1830
1831 // Zero out any bits above (TC-1) for calculation since the original loop
1832 // doesn't use them in the significant bit checks.
1833 if (SetupTy->getBitWidth() > TC) {
1834 auto *Mask =
1835 ConstantInt::get(Ctx, APInt::getLowBitsSet(SetupTy->getBitWidth(), TC));
1836 ClmulMuInput = Builder.CreateAnd(ClmulMuInput, Mask, "crc.tcbits");
1837 }
1838
1839 // Step 1: T1(x) = floor(R(x)/x^CRCBW) * mu
1840 // Input is TC bits and mu is TC+1 bits, so result will be 2*TC bits.
1841 ClmulMuInput =
1842 Builder.CreateZExtOrTrunc(ClmulMuInput, ClmulMuTy, "tcbits.cast");
1843 Value *ClmulMu = Builder.CreateBinaryIntrinsic(
1844 Intrinsic::clmul, ClmulMuInput, MuConst, /*FMFSource=*/{}, "clmul.mu");
1845
1846 // Calculate floor(T1(x)/x^TC) for step 2.
1847 Value *ClmulGPInput =
1848 Info.IsBigEndian ? Builder.CreateLShr(ClmulMu, TC, "quot.lshr") : ClmulMu;
1849
1850 // Step 2: T2(x) = floor(T1(x)/x^TC) * P(x)
1851 // Input is TC bits and P(x) is CRCBW+1 bits, so result will be CRCBW+TC bits.
1852 ClmulGPInput =
1853 Builder.CreateZExtOrTrunc(ClmulGPInput, ClmulGPTy, "quot.cast");
1854 Value *ClmulGP = Builder.CreateBinaryIntrinsic(Intrinsic::clmul, ClmulGPInput,
1855 GenPolyConst,
1856 /*FMFSource=*/{}, "clmul.gp");
1857
1858 // Calculate the least significant part of R(x) for step 3 as specified above.
1859 // R(x) mod x^CRCBW = LHS*x^TC mod x^CRCBW, though the (mod x^CRCBW) is
1860 // handled later on when truncating back to CRCBW for ComputedValue.
1861 Value *CRCNext = Builder.CreateZExt(Info.LHS, ClmulGPTy, "crc.recast");
1862 if (Info.IsBigEndian)
1863 CRCNext = Builder.CreateShl(CRCNext, TC, "crc.shl");
1864
1865 // Step 3: C(x) = (R(x) xor T2(x)) mod x^CRCBW
1866 CRCNext = Builder.CreateXor(CRCNext, ClmulGP, "xor.crc.mult");
1867 if (!Info.IsBigEndian)
1868 CRCNext = Builder.CreateLShr(CRCNext, TC, "crc.lshr");
1869
1870 // Bring the result back down the the CRC bit width.
1871 CRCNext = Builder.CreateTrunc(CRCNext, CRCTy, "crc.next");
1872
1873 // Replace the result of the loop with the new computed CRC value.
1874 Info.ComputedValue->replaceUsesOutsideBlock(CRCNext, CurLoop->getLoopLatch());
1875
1876 // Finally, clean up the loop as much as possible so it can be trivially
1877 // deleted.
1878 {
1879 for (PHINode &PN : make_early_inc_range(CurLoop->getHeader()->phis())) {
1880 PN.replaceAllUsesWith(PoisonValue::get(PN.getType()));
1882 }
1883 // Replace the exit condition with constant true/false to always cause a
1884 // branch to the exit block.
1886 auto *BrInst = cast<CondBrInst>(CurLoop->getLoopLatch()->getTerminator());
1887 BrInst->setCondition(ConstantInt::getBool(
1888 Ctx, BrInst->getSuccessor(0) == CurLoop->getExitBlock()));
1889 SE->forgetLoop(CurLoop);
1890 }
1891}
1892
1893void LoopIdiomRecognize::optimizeCRCLoopUsingTableLookup(
1894 const PolynomialInfo &Info) {
1895 assert(Info.TripCount % 8 == 0 && "A byte-multiple trip count is required");
1896
1897 // First, create a new GlobalVariable corresponding to the
1898 // Sarwate-lookup-table.
1899 Type *CRCTy = Info.LHS->getType();
1900 unsigned CRCBW = CRCTy->getIntegerBitWidth();
1901 std::array<Constant *, 256> CRCConstants;
1903 CRCConstants.begin(),
1904 [CRCTy](const APInt &E) { return ConstantInt::get(CRCTy, E); });
1905 Constant *ConstArray =
1906 ConstantArray::get(ArrayType::get(CRCTy, 256), CRCConstants);
1908 *CurLoop->getHeader()->getModule(), ConstArray->getType(), true,
1909 GlobalValue::PrivateLinkage, ConstArray, ".crctable");
1910
1913
1914 // Next, mark all PHIs for removal except IV.
1915 {
1916 for (PHINode &PN : CurLoop->getHeader()->phis()) {
1917 if (&PN == IV)
1918 continue;
1919 PN.replaceAllUsesWith(PoisonValue::get(PN.getType()));
1920 Cleanup.push_back(&PN);
1921 }
1922 }
1923
1924 // Next, fix up the trip count.
1925 {
1926 unsigned NewBTC = (Info.TripCount / 8) - 1;
1927 BasicBlock *LoopBlk = CurLoop->getLoopLatch();
1928 CondBrInst *BrInst = cast<CondBrInst>(LoopBlk->getTerminator());
1929 CmpPredicate ExitPred = BrInst->getSuccessor(0) == LoopBlk
1932 Instruction *ExitCond = CurLoop->getLatchCmpInst();
1933 Value *ExitLimit = ConstantInt::get(IV->getType(), NewBTC);
1934 IRBuilder<> Builder(ExitCond);
1935 Value *NewExitCond =
1936 Builder.CreateICmp(ExitPred, IV, ExitLimit, "exit.cond");
1937 ExitCond->replaceAllUsesWith(NewExitCond);
1938 deleteDeadInstruction(ExitCond);
1939 }
1940
1941 // Finally, fill the loop with the Sarwate-table-lookup logic, and replace all
1942 // uses of ComputedValue.
1943 //
1944 // Little-endian:
1945 // crc = (crc >> 8) ^ tbl[(iv'th byte of data) ^ (bottom byte of crc)]
1946 // Big-Endian:
1947 // crc = (crc << 8) ^ tbl[(iv'th byte of data) ^ (top byte of crc)]
1948 {
1949 auto LoByte = [](IRBuilderBase &Builder, Value *Op, const Twine &Name) {
1950 return Builder.CreateZExtOrTrunc(
1951 Op, IntegerType::getInt8Ty(Op->getContext()), Name);
1952 };
1953 auto HiIdx = [LoByte, CRCBW](IRBuilderBase &Builder, Value *Op,
1954 const Twine &Name) {
1955 // Shift the top bits of Op to the bottom byte by using the CRC bitwidth
1956 // as a reference.
1957 if (CRCBW != 8) {
1958 Op = CRCBW > 8 ? Builder.CreateLShr(Op, CRCBW - 8, Name)
1959 : Builder.CreateShl(Op, 8 - CRCBW, Name);
1960 }
1961 return LoByte(Builder, Op, Name + ".lo.byte");
1962 };
1963
1964 IRBuilder<> Builder(CurLoop->getHeader()->getFirstNonPHIIt());
1965 Builder.disableGEPCanonicalization();
1966
1967 // Create the CRC PHI, and initialize its incoming value to the initial
1968 // value of CRC.
1969 PHINode *CRCPhi = Builder.CreatePHI(CRCTy, 2, "crc");
1970 CRCPhi->addIncoming(Info.LHS, CurLoop->getLoopPreheader());
1971
1972 // CRC is now an evolving variable, initialized to the PHI.
1973 Value *CRC = CRCPhi;
1974
1975 // TableIndexer = ((top|bottom) byte of CRC). It is XOR'ed with (iv'th byte
1976 // of LHSAux), if LHSAux is non-nullptr.
1977 Value *Indexer = CRC;
1978 if (Value *Data = Info.LHSAux) {
1979 Type *DataTy = Data->getType();
1980
1981 // To index into the (iv'th byte of LHSAux), we multiply iv by 8, and we
1982 // shift right by that amount, and take the lo-byte (in the little-endian
1983 // case), or shift left by that amount, and take the hi-idx (in the
1984 // big-endian case).
1985 Value *IVBits = Builder.CreateZExtOrTrunc(
1986 Builder.CreateShl(IV, 3, "iv.bits"), DataTy, "iv.indexer");
1987 Value *DataIndexer =
1988 Info.IsBigEndian ? Builder.CreateShl(Data, IVBits, "data.indexer")
1989 : Builder.CreateLShr(Data, IVBits, "data.indexer");
1990 Indexer = Builder.CreateXor(
1991 DataIndexer,
1992 Builder.CreateZExtOrTrunc(Indexer, DataTy, "crc.indexer.cast"),
1993 "crc.data.indexer");
1994 }
1995
1996 Indexer = Info.IsBigEndian ? HiIdx(Builder, Indexer, "indexer.hi")
1997 : LoByte(Builder, Indexer, "indexer.lo");
1998
1999 // Always index into a GEP using the index type.
2000 Indexer = Builder.CreateZExt(
2001 Indexer, SE->getDataLayout().getIndexType(GV->getType()),
2002 "indexer.ext");
2003
2004 // CRCTableLd = CRCTable[(iv'th byte of data) ^ (top|bottom) byte of CRC].
2005 Value *CRCTableGEP =
2006 Builder.CreateInBoundsGEP(CRCTy, GV, Indexer, "tbl.ptradd");
2007 Instruction *CRCTableLd = Builder.CreateLoad(CRCTy, CRCTableGEP, "tbl.ld");
2008
2009 // Update MemorySSA since we just created a new load instruction.
2010 if (MSSAU) {
2011 auto *NewMemAcc = MSSAU->createMemoryAccessInBB(
2012 CRCTableLd, /*Definition=*/nullptr, CRCTableLd->getParent(),
2014 MSSAU->insertUse(cast<MemoryUse>(NewMemAcc), /*RenameUses=*/true);
2015 }
2016
2017 // CRCNext = (CRC (<<|>>) 8) ^ CRCTableLd, or simply CRCTableLd in case of
2018 // CRC-8.
2019 Value *CRCNext = CRCTableLd;
2020 if (CRCBW > 8) {
2021 Value *CRCShift = Info.IsBigEndian
2022 ? Builder.CreateShl(CRC, 8, "crc.be.shift")
2023 : Builder.CreateLShr(CRC, 8, "crc.le.shift");
2024 CRCNext = Builder.CreateXor(CRCShift, CRCTableLd, "crc.next");
2025 }
2026
2027 // Connect the back-edge for the loop, and RAUW the ComputedValue.
2028 CRCPhi->addIncoming(CRCNext, CurLoop->getLoopLatch());
2029 Info.ComputedValue->replaceUsesOutsideBlock(CRCNext,
2030 CurLoop->getLoopLatch());
2031 }
2032
2033 // Cleanup.
2034 {
2035 for (PHINode *PN : Cleanup)
2037 SE->forgetLoop(CurLoop);
2038 if (MSSAU && VerifyMemorySSA)
2039 MSSAU->getMemorySSA()->verifyMemorySSA();
2040 }
2041}
2042
2043bool LoopIdiomRecognize::runOnNoncountableLoop() {
2044 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
2045 << CurLoop->getHeader()->getParent()->getName()
2046 << "] Noncountable Loop %"
2047 << CurLoop->getHeader()->getName() << "\n");
2048
2049 return recognizePopcount() || recognizeAndInsertFFS() ||
2050 recognizeShiftUntilBitTest() || recognizeShiftUntilZero() ||
2051 recognizeShiftUntilLessThan() || recognizeAndInsertStrLen();
2052}
2053
2054/// Check if the given conditional branch is based on the comparison between
2055/// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
2056/// true), the control yields to the loop entry. If the branch matches the
2057/// behavior, the variable involved in the comparison is returned. This function
2058/// will be called to see if the precondition and postcondition of the loop are
2059/// in desirable form.
2061 bool JmpOnZero = false) {
2063 if (!Cond)
2064 return nullptr;
2065
2066 auto *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
2067 if (!CmpZero || !CmpZero->isZero())
2068 return nullptr;
2069
2070 BasicBlock *TrueSucc = BI->getSuccessor(0);
2071 BasicBlock *FalseSucc = BI->getSuccessor(1);
2072 if (JmpOnZero)
2073 std::swap(TrueSucc, FalseSucc);
2074
2075 ICmpInst::Predicate Pred = Cond->getPredicate();
2076 if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
2077 (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
2078 return Cond->getOperand(0);
2079
2080 return nullptr;
2081}
2082
2083namespace {
2084
2085class StrlenVerifier {
2086public:
2087 explicit StrlenVerifier(const Loop *CurLoop, ScalarEvolution *SE)
2088 : CurLoop(CurLoop), SE(SE) {}
2089
2090 bool isValidStrlenIdiom() {
2091 // Give up if the loop has multiple blocks, multiple backedges, or
2092 // multiple exit blocks
2093 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1 ||
2094 !CurLoop->getUniqueExitBlock())
2095 return false;
2096
2097 // It should have a preheader and a branch instruction.
2098 BasicBlock *Preheader = CurLoop->getLoopPreheader();
2099 if (!Preheader ||
2101 return false;
2102
2103 // The loop exit must be conditioned on an icmp with 0 the null terminator.
2104 // The icmp operand has to be a load on some SSA reg that increments
2105 // by 1 in the loop.
2106 BasicBlock *LoopBody = *CurLoop->block_begin();
2107
2108 // Skip if the body is too big as it most likely is not a strlen idiom.
2109 if (!LoopBody || LoopBody->size() >= 15)
2110 return false;
2111
2112 CondBrInst *LoopTerm = dyn_cast<CondBrInst>(LoopBody->getTerminator());
2113 if (!LoopTerm)
2114 return false;
2115 Value *LoopCond = matchCondition(LoopTerm, LoopBody);
2116 if (!LoopCond)
2117 return false;
2118
2119 LoadInst *LoopLoad = dyn_cast<LoadInst>(LoopCond);
2120 if (!LoopLoad || LoopLoad->getPointerAddressSpace() != 0)
2121 return false;
2122
2123 OperandType = LoopLoad->getType();
2124 if (!OperandType || !OperandType->isIntegerTy())
2125 return false;
2126
2127 // See if the pointer expression is an AddRec with constant step a of form
2128 // ({n,+,a}) where a is the width of the char type.
2129 Value *IncPtr = LoopLoad->getPointerOperand();
2130 const SCEV *LoadEv = SE->getSCEV(IncPtr);
2131 const APInt *Step;
2132 if (!match(LoadEv,
2133 m_scev_AffineAddRec(m_SCEV(LoadBaseEv), m_scev_APInt(Step))))
2134 return false;
2135
2136 LLVM_DEBUG(dbgs() << "pointer load scev: " << *LoadEv << "\n");
2137
2138 uint64_t StepSize = Step->getZExtValue();
2139
2140 // Verify that StepSize is consistent with platform char width.
2141 OpWidth = OperandType->getIntegerBitWidth();
2142 unsigned WcharSize = LoopLoad->getModule()->getWCharSize();
2143 if (OpWidth != 8 && OpWidth != 16 && OpWidth != 32)
2144 return false;
2145 if (StepSize != OpWidth / 8)
2146 return false;
2147 if (OpWidth >= 16) {
2148 if (OpWidth != WcharSize * 8)
2149 return false;
2150
2151 // Don't call `wcslen` if the base pointer isn't known to be aligned.
2152 const DataLayout &DL = LoopLoad->getDataLayout();
2153 Align OperandAlign = DL.getABITypeAlign(OperandType);
2154 if (LoopLoad->getAlign() < OperandAlign) {
2155 // For null pointers the load base number of trailing zeros may be
2156 // larger than what `Align` allows. So take log2 of operand alignment
2157 // instead and compare trailing zeros instead of alignments.
2158 if (SE->getMinTrailingZeros(LoadBaseEv) < Log2(OperandAlign))
2159 return false;
2160 }
2161 }
2162
2163 // Scan every instruction in the loop to ensure there are no side effects.
2164 for (Instruction &I : *LoopBody)
2165 if (I.mayHaveSideEffects())
2166 return false;
2167
2168 BasicBlock *LoopExitBB = CurLoop->getExitBlock();
2169 if (!LoopExitBB)
2170 return false;
2171
2172 for (PHINode &PN : LoopExitBB->phis()) {
2173 if (!SE->isSCEVable(PN.getType()))
2174 return false;
2175
2176 const SCEV *Ev = SE->getSCEV(&PN);
2177 if (!Ev)
2178 return false;
2179
2180 LLVM_DEBUG(dbgs() << "loop exit phi scev: " << *Ev << "\n");
2181
2182 // Since we verified that the loop trip count will be a valid strlen
2183 // idiom, we can expand all lcssa phi with {n,+,1} as (n + strlen) and use
2184 // SCEVExpander materialize the loop output.
2185 const SCEVAddRecExpr *AddRecEv = dyn_cast<SCEVAddRecExpr>(Ev);
2186 if (!AddRecEv || !AddRecEv->isAffine())
2187 return false;
2188
2189 // We only want RecAddExpr with recurrence step that is constant. This
2190 // is good enough for all the idioms we want to recognize. Later we expand
2191 // and materialize the recurrence as {base,+,a} -> (base + a * strlen)
2192 if (!isa<SCEVConstant>(AddRecEv->getStepRecurrence(*SE)))
2193 return false;
2194 }
2195
2196 return true;
2197 }
2198
2199public:
2200 const Loop *CurLoop;
2201 ScalarEvolution *SE;
2202
2203 unsigned OpWidth;
2204 ConstantInt *StepSizeCI;
2205 const SCEV *LoadBaseEv;
2207};
2208
2209} // namespace
2210
2211/// The Strlen Idiom we are trying to detect has the following structure
2212///
2213/// preheader:
2214/// ...
2215/// br label %body, ...
2216///
2217/// body:
2218/// ... ; %0 is incremented by a gep
2219/// %1 = load i8, ptr %0, align 1
2220/// %2 = icmp eq i8 %1, 0
2221/// br i1 %2, label %exit, label %body
2222///
2223/// exit:
2224/// %lcssa = phi [%0, %body], ...
2225///
2226/// We expect the strlen idiom to have a load of a character type that
2227/// is compared against '\0', and such load pointer operand must have scev
2228/// expression of the form {%str,+,c} where c is a ConstantInt of the
2229/// appropiate character width for the idiom, and %str is the base of the string
2230/// And, that all lcssa phis have the form {...,+,n} where n is a constant,
2231///
2232/// When transforming the output of the strlen idiom, the lccsa phi are
2233/// expanded using SCEVExpander as {base scev,+,a} -> (base scev + a * strlen)
2234/// and all subsequent uses are replaced. For example,
2235///
2236/// \code{.c}
2237/// const char* base = str;
2238/// while (*str != '\0')
2239/// ++str;
2240/// size_t result = str - base;
2241/// \endcode
2242///
2243/// will be transformed as follows: The idiom will be replaced by a strlen
2244/// computation to compute the address of the null terminator of the string.
2245///
2246/// \code{.c}
2247/// const char* base = str;
2248/// const char* end = base + strlen(str);
2249/// size_t result = end - base;
2250/// \endcode
2251///
2252/// In the case we index by an induction variable, as long as the induction
2253/// variable has a constant int increment, we can replace all such indvars
2254/// with the closed form computation of strlen
2255///
2256/// \code{.c}
2257/// size_t i = 0;
2258/// while (str[i] != '\0')
2259/// ++i;
2260/// size_t result = i;
2261/// \endcode
2262///
2263/// Will be replaced by
2264///
2265/// \code{.c}
2266/// size_t i = 0 + strlen(str);
2267/// size_t result = i;
2268/// \endcode
2269///
2270bool LoopIdiomRecognize::recognizeAndInsertStrLen() {
2271 if (DisableLIRP::All)
2272 return false;
2273
2274 StrlenVerifier Verifier(CurLoop, SE);
2275
2276 if (!Verifier.isValidStrlenIdiom())
2277 return false;
2278
2279 BasicBlock *Preheader = CurLoop->getLoopPreheader();
2280 BasicBlock *LoopBody = *CurLoop->block_begin();
2281 BasicBlock *LoopExitBB = CurLoop->getExitBlock();
2282 CondBrInst *LoopTerm = cast<CondBrInst>(LoopBody->getTerminator());
2283 assert(Preheader && LoopBody && LoopExitBB &&
2284 "Should be verified to be valid by StrlenVerifier");
2285
2286 if (Verifier.OpWidth == 8) {
2288 return false;
2289 if (!isLibFuncEmittable(Preheader->getModule(), TLI, LibFunc_strlen))
2290 return false;
2291 } else {
2293 return false;
2294 if (!isLibFuncEmittable(Preheader->getModule(), TLI, LibFunc_wcslen))
2295 return false;
2296 }
2297
2298 IRBuilder<> Builder(Preheader->getTerminator());
2299 Builder.SetCurrentDebugLocation(CurLoop->getStartLoc());
2300 SCEVExpander Expander(*SE, "strlen_idiom");
2301 Value *MaterialzedBase = Expander.expandCodeFor(
2302 Verifier.LoadBaseEv, Verifier.LoadBaseEv->getType(),
2303 Builder.GetInsertPoint());
2304
2305 Value *StrLenFunc = nullptr;
2306 if (Verifier.OpWidth == 8) {
2307 StrLenFunc = emitStrLen(MaterialzedBase, Builder, *DL, TLI);
2308 } else {
2309 StrLenFunc = emitWcsLen(MaterialzedBase, Builder, *DL, TLI);
2310 }
2311 assert(StrLenFunc && "Failed to emit strlen function.");
2312
2313 const SCEV *StrlenEv = SE->getSCEV(StrLenFunc);
2315 for (PHINode &PN : LoopExitBB->phis()) {
2316 // We can now materialize the loop output as all phi have scev {base,+,a}.
2317 // We expand the phi as:
2318 // %strlen = call i64 @strlen(%str)
2319 // %phi.new = base expression + step * %strlen
2320 const SCEV *Ev = SE->getSCEV(&PN);
2321 const SCEVAddRecExpr *AddRecEv = dyn_cast<SCEVAddRecExpr>(Ev);
2322 const SCEVConstant *Step =
2324 const SCEV *Base = AddRecEv->getStart();
2325
2326 // It is safe to truncate to base since if base is narrower than size_t
2327 // the equivalent user code will have to truncate anyways.
2328 const SCEV *NewEv = SE->getAddExpr(
2330 StrlenEv, Base->getType())));
2331
2332 Value *MaterializedPHI = Expander.expandCodeFor(NewEv, NewEv->getType(),
2333 Builder.GetInsertPoint());
2334 Expander.clear();
2335 PN.replaceAllUsesWith(MaterializedPHI);
2336 Cleanup.push_back(&PN);
2337 }
2338
2339 // All LCSSA Loop Phi are dead, the left over dead loop body can be cleaned
2340 // up by later passes
2341 for (PHINode *PN : Cleanup)
2343
2344 // LoopDeletion only delete invariant loops with known trip-count. We can
2345 // update the condition so it will reliablely delete the invariant loop
2346 assert((LoopTerm->getSuccessor(0) == LoopBody ||
2347 LoopTerm->getSuccessor(1) == LoopBody) &&
2348 "loop body must have a successor that is it self");
2349 ConstantInt *NewLoopCond = LoopTerm->getSuccessor(0) == LoopBody
2350 ? Builder.getFalse()
2351 : Builder.getTrue();
2352 LoopTerm->setCondition(NewLoopCond);
2353 SE->forgetLoop(CurLoop);
2354
2355 ++NumStrLen;
2356 LLVM_DEBUG(dbgs() << " Formed strlen idiom: " << *StrLenFunc << "\n");
2357 ORE.emit([&]() {
2358 return OptimizationRemark(DEBUG_TYPE, "recognizeAndInsertStrLen",
2359 CurLoop->getStartLoc(), Preheader)
2360 << "Transformed " << StrLenFunc->getName() << " loop idiom";
2361 });
2362
2363 return true;
2364}
2365
2366/// Check if the given conditional branch is based on an unsigned less-than
2367/// comparison between a variable and a constant, and if the comparison is false
2368/// the control yields to the loop entry. If the branch matches the behaviour,
2369/// the variable involved in the comparison is returned.
2371 APInt &Threshold) {
2373 if (!Cond)
2374 return nullptr;
2375
2376 ConstantInt *CmpConst = dyn_cast<ConstantInt>(Cond->getOperand(1));
2377 if (!CmpConst)
2378 return nullptr;
2379
2380 BasicBlock *FalseSucc = BI->getSuccessor(1);
2381 ICmpInst::Predicate Pred = Cond->getPredicate();
2382
2383 if (Pred == ICmpInst::ICMP_ULT && FalseSucc == LoopEntry) {
2384 Threshold = CmpConst->getValue();
2385 return Cond->getOperand(0);
2386 }
2387
2388 return nullptr;
2389}
2390
2391// Check if the recurrence variable `VarX` is in the right form to create
2392// the idiom. Returns the value coerced to a PHINode if so.
2394 BasicBlock *LoopEntry) {
2395 auto *PhiX = dyn_cast<PHINode>(VarX);
2396 if (PhiX && PhiX->getParent() == LoopEntry &&
2397 (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
2398 return PhiX;
2399 return nullptr;
2400}
2401
2402/// Return true if the idiom is detected in the loop.
2403///
2404/// Additionally:
2405/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
2406/// or nullptr if there is no such.
2407/// 2) \p CntPhi is set to the corresponding phi node
2408/// or nullptr if there is no such.
2409/// 3) \p InitX is set to the value whose CTLZ could be used.
2410/// 4) \p DefX is set to the instruction calculating Loop exit condition.
2411/// 5) \p Threshold is set to the constant involved in the unsigned less-than
2412/// comparison.
2413///
2414/// The core idiom we are trying to detect is:
2415/// \code
2416/// if (x0 < 2)
2417/// goto loop-exit // the precondition of the loop
2418/// cnt0 = init-val
2419/// do {
2420/// x = phi (x0, x.next); //PhiX
2421/// cnt = phi (cnt0, cnt.next)
2422///
2423/// cnt.next = cnt + 1;
2424/// ...
2425/// x.next = x >> 1; // DefX
2426/// } while (x >= 4)
2427/// loop-exit:
2428/// \endcode
2430 Intrinsic::ID &IntrinID,
2431 Value *&InitX, Instruction *&CntInst,
2432 PHINode *&CntPhi, Instruction *&DefX,
2433 APInt &Threshold) {
2434 BasicBlock *LoopEntry;
2435
2436 DefX = nullptr;
2437 CntInst = nullptr;
2438 CntPhi = nullptr;
2439 LoopEntry = *(CurLoop->block_begin());
2440
2441 // step 1: Check if the loop-back branch is in desirable form.
2442 auto *EntryBI = dyn_cast<CondBrInst>(LoopEntry->getTerminator());
2443 if (!EntryBI)
2444 return false;
2445 if (Value *T = matchShiftULTCondition(EntryBI, LoopEntry, Threshold))
2446 DefX = dyn_cast<Instruction>(T);
2447 else
2448 return false;
2449
2450 // step 2: Check the recurrence of variable X
2451 if (!DefX || !isa<PHINode>(DefX))
2452 return false;
2453
2454 PHINode *VarPhi = cast<PHINode>(DefX);
2455 int Idx = VarPhi->getBasicBlockIndex(LoopEntry);
2456 if (Idx == -1)
2457 return false;
2458
2459 DefX = dyn_cast<Instruction>(VarPhi->getIncomingValue(Idx));
2460 if (!DefX || DefX->getNumOperands() == 0 || DefX->getOperand(0) != VarPhi)
2461 return false;
2462
2463 // step 3: detect instructions corresponding to "x.next = x >> 1"
2464 if (DefX->getOpcode() != Instruction::LShr)
2465 return false;
2466
2467 IntrinID = Intrinsic::ctlz;
2469 if (!Shft || !Shft->isOne())
2470 return false;
2471
2472 InitX = VarPhi->getIncomingValueForBlock(CurLoop->getLoopPreheader());
2473
2474 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
2475 // or cnt.next = cnt + -1.
2476 // TODO: We can skip the step. If loop trip count is known (CTLZ),
2477 // then all uses of "cnt.next" could be optimized to the trip count
2478 // plus "cnt0". Currently it is not optimized.
2479 // This step could be used to detect POPCNT instruction:
2480 // cnt.next = cnt + (x.next & 1)
2481 for (Instruction &Inst :
2482 llvm::make_range(LoopEntry->getFirstNonPHIIt(), LoopEntry->end())) {
2483 if (Inst.getOpcode() != Instruction::Add)
2484 continue;
2485
2487 if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
2488 continue;
2489
2490 PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
2491 if (!Phi)
2492 continue;
2493
2494 CntInst = &Inst;
2495 CntPhi = Phi;
2496 break;
2497 }
2498 if (!CntInst)
2499 return false;
2500
2501 return true;
2502}
2503
2504/// Return true iff the idiom is detected in the loop.
2505///
2506/// Additionally:
2507/// 1) \p CntInst is set to the instruction counting the population bit.
2508/// 2) \p CntPhi is set to the corresponding phi node.
2509/// 3) \p Var is set to the value whose population bits are being counted.
2510///
2511/// The core idiom we are trying to detect is:
2512/// \code
2513/// if (x0 != 0)
2514/// goto loop-exit // the precondition of the loop
2515/// cnt0 = init-val;
2516/// do {
2517/// x1 = phi (x0, x2);
2518/// cnt1 = phi(cnt0, cnt2);
2519///
2520/// cnt2 = cnt1 + 1;
2521/// ...
2522/// x2 = x1 & (x1 - 1);
2523/// ...
2524/// } while(x != 0);
2525///
2526/// loop-exit:
2527/// \endcode
2528static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
2529 Instruction *&CntInst, PHINode *&CntPhi,
2530 Value *&Var) {
2531 // step 1: Check to see if the look-back branch match this pattern:
2532 // "if (a!=0) goto loop-entry".
2533 BasicBlock *LoopEntry;
2534 Instruction *DefX2, *CountInst;
2535 Value *VarX1, *VarX0;
2536 PHINode *PhiX, *CountPhi;
2537
2538 DefX2 = CountInst = nullptr;
2539 VarX1 = VarX0 = nullptr;
2540 PhiX = CountPhi = nullptr;
2541 LoopEntry = *(CurLoop->block_begin());
2542
2543 // step 1: Check if the loop-back branch is in desirable form.
2544 {
2545 auto *LoopTerm = dyn_cast<CondBrInst>(LoopEntry->getTerminator());
2546 if (!LoopTerm)
2547 return false;
2548 DefX2 = dyn_cast_or_null<Instruction>(matchCondition(LoopTerm, LoopEntry));
2549 }
2550
2551 // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
2552 {
2553 if (!DefX2 || DefX2->getOpcode() != Instruction::And)
2554 return false;
2555
2556 BinaryOperator *SubOneOp;
2557
2558 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
2559 VarX1 = DefX2->getOperand(1);
2560 else {
2561 VarX1 = DefX2->getOperand(0);
2562 SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
2563 }
2564 if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
2565 return false;
2566
2567 ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
2568 if (!Dec ||
2569 !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
2570 (SubOneOp->getOpcode() == Instruction::Add &&
2571 Dec->isMinusOne()))) {
2572 return false;
2573 }
2574 }
2575
2576 // step 3: Check the recurrence of variable X
2577 PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
2578 if (!PhiX)
2579 return false;
2580
2581 // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
2582 {
2583 CountInst = nullptr;
2584 for (Instruction &Inst :
2585 llvm::make_range(LoopEntry->getFirstNonPHIIt(), LoopEntry->end())) {
2586 if (Inst.getOpcode() != Instruction::Add)
2587 continue;
2588
2590 if (!Inc || !Inc->isOne())
2591 continue;
2592
2593 PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
2594 if (!Phi)
2595 continue;
2596
2597 // Check if the result of the instruction is live of the loop.
2598 bool LiveOutLoop = false;
2599 for (User *U : Inst.users()) {
2600 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
2601 LiveOutLoop = true;
2602 break;
2603 }
2604 }
2605
2606 if (LiveOutLoop) {
2607 CountInst = &Inst;
2608 CountPhi = Phi;
2609 break;
2610 }
2611 }
2612
2613 if (!CountInst)
2614 return false;
2615 }
2616
2617 // step 5: check if the precondition is in this form:
2618 // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
2619 {
2620 auto *PreCondBr = dyn_cast<CondBrInst>(PreCondBB->getTerminator());
2621 if (!PreCondBr)
2622 return false;
2623 Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
2624 if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
2625 return false;
2626
2627 CntInst = CountInst;
2628 CntPhi = CountPhi;
2629 Var = T;
2630 }
2631
2632 return true;
2633}
2634
2635/// Return true if the idiom is detected in the loop.
2636///
2637/// Additionally:
2638/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
2639/// or nullptr if there is no such.
2640/// 2) \p CntPhi is set to the corresponding phi node
2641/// or nullptr if there is no such.
2642/// 3) \p Var is set to the value whose CTLZ could be used.
2643/// 4) \p DefX is set to the instruction calculating Loop exit condition.
2644///
2645/// The core idiom we are trying to detect is:
2646/// \code
2647/// if (x0 == 0)
2648/// goto loop-exit // the precondition of the loop
2649/// cnt0 = init-val;
2650/// do {
2651/// x = phi (x0, x.next); //PhiX
2652/// cnt = phi(cnt0, cnt.next);
2653///
2654/// cnt.next = cnt + 1;
2655/// ...
2656/// x.next = x >> 1; // DefX
2657/// ...
2658/// } while(x.next != 0);
2659///
2660/// loop-exit:
2661/// \endcode
2662static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
2663 Intrinsic::ID &IntrinID, Value *&InitX,
2664 Instruction *&CntInst, PHINode *&CntPhi,
2665 Instruction *&DefX) {
2666 BasicBlock *LoopEntry;
2667 Value *VarX = nullptr;
2668
2669 DefX = nullptr;
2670 CntInst = nullptr;
2671 CntPhi = nullptr;
2672 LoopEntry = *(CurLoop->block_begin());
2673
2674 // step 1: Check if the loop-back branch is in desirable form.
2675 auto *LoopTerm = dyn_cast<CondBrInst>(LoopEntry->getTerminator());
2676 if (!LoopTerm)
2677 return false;
2678 DefX = dyn_cast_or_null<Instruction>(matchCondition(LoopTerm, LoopEntry));
2679
2680 // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
2681 if (!DefX || !DefX->isShift())
2682 return false;
2683 IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
2684 Intrinsic::ctlz;
2686 if (!Shft || !Shft->isOne())
2687 return false;
2688 VarX = DefX->getOperand(0);
2689
2690 // step 3: Check the recurrence of variable X
2691 PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
2692 if (!PhiX)
2693 return false;
2694
2695 InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
2696
2697 // Make sure the initial value can't be negative otherwise the ashr in the
2698 // loop might never reach zero which would make the loop infinite.
2699 if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
2700 return false;
2701
2702 // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
2703 // or cnt.next = cnt + -1.
2704 // TODO: We can skip the step. If loop trip count is known (CTLZ),
2705 // then all uses of "cnt.next" could be optimized to the trip count
2706 // plus "cnt0". Currently it is not optimized.
2707 // This step could be used to detect POPCNT instruction:
2708 // cnt.next = cnt + (x.next & 1)
2709 for (Instruction &Inst :
2710 llvm::make_range(LoopEntry->getFirstNonPHIIt(), LoopEntry->end())) {
2711 if (Inst.getOpcode() != Instruction::Add)
2712 continue;
2713
2715 if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
2716 continue;
2717
2718 PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
2719 if (!Phi)
2720 continue;
2721
2722 CntInst = &Inst;
2723 CntPhi = Phi;
2724 break;
2725 }
2726 if (!CntInst)
2727 return false;
2728
2729 return true;
2730}
2731
2732// Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
2733// profitable if we delete the loop.
2734bool LoopIdiomRecognize::isProfitableToInsertFFS(Intrinsic::ID IntrinID,
2735 Value *InitX, bool ZeroCheck,
2736 size_t CanonicalSize) {
2737 const Value *Args[] = {InitX,
2738 ConstantInt::getBool(InitX->getContext(), ZeroCheck)};
2739
2740 uint32_t HeaderSize = CurLoop->getHeader()->size();
2741
2742 IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args);
2743 InstructionCost Cost = TTI->getIntrinsicInstrCost(
2745 if (HeaderSize != CanonicalSize && Cost > TargetTransformInfo::TCC_Basic)
2746 return false;
2747
2748 return true;
2749}
2750
2751/// Convert CTLZ / CTTZ idiom loop into countable loop.
2752/// If CTLZ / CTTZ inserted as a new trip count returns true; otherwise,
2753/// returns false.
2754bool LoopIdiomRecognize::insertFFSIfProfitable(Intrinsic::ID IntrinID,
2755 Value *InitX, Instruction *DefX,
2756 PHINode *CntPhi,
2757 Instruction *CntInst) {
2758 bool IsCntPhiUsedOutsideLoop = false;
2759 for (User *U : CntPhi->users())
2760 if (!CurLoop->contains(cast<Instruction>(U))) {
2761 IsCntPhiUsedOutsideLoop = true;
2762 break;
2763 }
2764 bool IsCntInstUsedOutsideLoop = false;
2765 for (User *U : CntInst->users())
2766 if (!CurLoop->contains(cast<Instruction>(U))) {
2767 IsCntInstUsedOutsideLoop = true;
2768 break;
2769 }
2770 // If both CntInst and CntPhi are used outside the loop the profitability
2771 // is questionable.
2772 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
2773 return false;
2774
2775 // For some CPUs result of CTLZ(X) intrinsic is undefined
2776 // when X is 0. If we can not guarantee X != 0, we need to check this
2777 // when expand.
2778 bool ZeroCheck = false;
2779 // It is safe to assume Preheader exist as it was checked in
2780 // parent function RunOnLoop.
2781 BasicBlock *PH = CurLoop->getLoopPreheader();
2782
2783 // If we are using the count instruction outside the loop, make sure we
2784 // have a zero check as a precondition. Without the check the loop would run
2785 // one iteration for before any check of the input value. This means 0 and 1
2786 // would have identical behavior in the original loop and thus
2787 if (!IsCntPhiUsedOutsideLoop) {
2788 auto *PreCondBB = PH->getSinglePredecessor();
2789 auto *PreCondBI =
2790 PreCondBB ? dyn_cast<CondBrInst>(PreCondBB->getTerminator()) : nullptr;
2791 if (!(PreCondBI && matchCondition(PreCondBI, PH) == InitX) &&
2793 InitX, SimplifyQuery(*DL, DT, /*AC=*/nullptr, PH->getTerminator())))
2794 return false;
2795 ZeroCheck = true;
2796 }
2797
2798 // FFS idiom loop has only 6 instructions:
2799 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
2800 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
2801 // %shr = ashr %n.addr.0, 1
2802 // %tobool = icmp eq %shr, 0
2803 // %inc = add nsw %i.0, 1
2804 // br i1 %tobool
2805 size_t IdiomCanonicalSize = 6;
2806 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
2807 return false;
2808
2809 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
2810 DefX->getDebugLoc(), ZeroCheck,
2811 IsCntPhiUsedOutsideLoop);
2812 return true;
2813}
2814
2815/// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
2816/// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
2817/// trip count returns true; otherwise, returns false.
2818bool LoopIdiomRecognize::recognizeAndInsertFFS() {
2819 // Give up if the loop has multiple blocks or multiple backedges.
2820 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
2821 return false;
2822
2823 Intrinsic::ID IntrinID;
2824 Value *InitX;
2825 Instruction *DefX = nullptr;
2826 PHINode *CntPhi = nullptr;
2827 Instruction *CntInst = nullptr;
2828
2829 if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX, CntInst, CntPhi,
2830 DefX))
2831 return false;
2832
2833 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2834}
2835
2836bool LoopIdiomRecognize::recognizeShiftUntilLessThan() {
2837 // Give up if the loop has multiple blocks or multiple backedges.
2838 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
2839 return false;
2840
2841 Intrinsic::ID IntrinID;
2842 Value *InitX;
2843 Instruction *DefX = nullptr;
2844 PHINode *CntPhi = nullptr;
2845 Instruction *CntInst = nullptr;
2846
2847 APInt LoopThreshold;
2848 if (!detectShiftUntilLessThanIdiom(CurLoop, *DL, IntrinID, InitX, CntInst,
2849 CntPhi, DefX, LoopThreshold))
2850 return false;
2851
2852 if (LoopThreshold == 2) {
2853 // Treat as regular FFS.
2854 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2855 }
2856
2857 // Look for Floor Log2 Idiom.
2858 if (LoopThreshold != 4)
2859 return false;
2860
2861 // Abort if CntPhi is used outside of the loop.
2862 for (User *U : CntPhi->users())
2863 if (!CurLoop->contains(cast<Instruction>(U)))
2864 return false;
2865
2866 // It is safe to assume Preheader exist as it was checked in
2867 // parent function RunOnLoop.
2868 BasicBlock *PH = CurLoop->getLoopPreheader();
2869 auto *PreCondBB = PH->getSinglePredecessor();
2870 if (!PreCondBB)
2871 return false;
2872 auto *PreCondBI = dyn_cast<CondBrInst>(PreCondBB->getTerminator());
2873 if (!PreCondBI)
2874 return false;
2875
2876 APInt PreLoopThreshold;
2877 if (matchShiftULTCondition(PreCondBI, PH, PreLoopThreshold) != InitX ||
2878 PreLoopThreshold != 2)
2879 return false;
2880
2881 bool ZeroCheck = true;
2882
2883 // the loop has only 6 instructions:
2884 // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
2885 // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
2886 // %shr = ashr %n.addr.0, 1
2887 // %tobool = icmp ult %n.addr.0, C
2888 // %inc = add nsw %i.0, 1
2889 // br i1 %tobool
2890 size_t IdiomCanonicalSize = 6;
2891 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
2892 return false;
2893
2894 // log2(x) = w − 1 − clz(x)
2895 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
2896 DefX->getDebugLoc(), ZeroCheck,
2897 /*IsCntPhiUsedOutsideLoop=*/false,
2898 /*InsertSub=*/true);
2899 return true;
2900}
2901
2902/// Recognizes a population count idiom in a non-countable loop.
2903///
2904/// If detected, transforms the relevant code to issue the popcount intrinsic
2905/// function call, and returns true; otherwise, returns false.
2906bool LoopIdiomRecognize::recognizePopcount() {
2907 if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
2908 return false;
2909
2910 // Counting population are usually conducted by few arithmetic instructions.
2911 // Such instructions can be easily "absorbed" by vacant slots in a
2912 // non-compact loop. Therefore, recognizing popcount idiom only makes sense
2913 // in a compact loop.
2914
2915 // Give up if the loop has multiple blocks or multiple backedges.
2916 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
2917 return false;
2918
2919 BasicBlock *LoopBody = *(CurLoop->block_begin());
2920 if (LoopBody->size() >= 20) {
2921 // The loop is too big, bail out.
2922 return false;
2923 }
2924
2925 // It should have a preheader containing nothing but an unconditional branch.
2926 BasicBlock *PH = CurLoop->getLoopPreheader();
2927 if (!PH || &PH->front() != PH->getTerminator())
2928 return false;
2929 auto *EntryBI = dyn_cast<UncondBrInst>(PH->getTerminator());
2930 if (!EntryBI)
2931 return false;
2932
2933 // It should have a precondition block where the generated popcount intrinsic
2934 // function can be inserted.
2935 auto *PreCondBB = PH->getSinglePredecessor();
2936 if (!PreCondBB)
2937 return false;
2938 auto *PreCondBI = dyn_cast<CondBrInst>(PreCondBB->getTerminator());
2939 if (!PreCondBI)
2940 return false;
2941
2942 Instruction *CntInst;
2943 PHINode *CntPhi;
2944 Value *Val;
2945 if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
2946 return false;
2947
2948 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
2949 return true;
2950}
2951
2953 const DebugLoc &DL) {
2954 Value *Ops[] = {Val};
2955 Type *Tys[] = {Val->getType()};
2956
2958 return IRBuilder.CreateIntrinsic(Intrinsic::ctpop, Tys, Ops);
2959}
2960
2962 const DebugLoc &DL, bool ZeroCheck,
2963 Intrinsic::ID IID) {
2964 Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)};
2965 Type *Tys[] = {Val->getType()};
2966
2968 return IRBuilder.CreateIntrinsic(IID, Tys, Ops);
2969}
2970
2971/// Transform the following loop (Using CTLZ, CTTZ is similar):
2972/// loop:
2973/// CntPhi = PHI [Cnt0, CntInst]
2974/// PhiX = PHI [InitX, DefX]
2975/// CntInst = CntPhi + 1
2976/// DefX = PhiX >> 1
2977/// LOOP_BODY
2978/// Br: loop if (DefX != 0)
2979/// Use(CntPhi) or Use(CntInst)
2980///
2981/// Into:
2982/// If CntPhi used outside the loop:
2983/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
2984/// Count = CountPrev + 1
2985/// else
2986/// Count = BitWidth(InitX) - CTLZ(InitX)
2987/// loop:
2988/// CntPhi = PHI [Cnt0, CntInst]
2989/// PhiX = PHI [InitX, DefX]
2990/// PhiCount = PHI [Count, Dec]
2991/// CntInst = CntPhi + 1
2992/// DefX = PhiX >> 1
2993/// Dec = PhiCount - 1
2994/// LOOP_BODY
2995/// Br: loop if (Dec != 0)
2996/// Use(CountPrev + Cnt0) // Use(CntPhi)
2997/// or
2998/// Use(Count + Cnt0) // Use(CntInst)
2999///
3000/// If LOOP_BODY is empty the loop will be deleted.
3001/// If CntInst and DefX are not used in LOOP_BODY they will be removed.
3002void LoopIdiomRecognize::transformLoopToCountable(
3003 Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
3004 PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
3005 bool ZeroCheck, bool IsCntPhiUsedOutsideLoop, bool InsertSub) {
3006 // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
3007 IRBuilder<> Builder(Preheader->getTerminator());
3008 Builder.SetCurrentDebugLocation(DL);
3009
3010 // If there are no uses of CntPhi crate:
3011 // Count = BitWidth - CTLZ(InitX);
3012 // NewCount = Count;
3013 // If there are uses of CntPhi create:
3014 // NewCount = BitWidth - CTLZ(InitX >> 1);
3015 // Count = NewCount + 1;
3016 Value *InitXNext;
3017 if (IsCntPhiUsedOutsideLoop) {
3018 if (DefX->getOpcode() == Instruction::AShr)
3019 InitXNext = Builder.CreateAShr(InitX, 1);
3020 else if (DefX->getOpcode() == Instruction::LShr)
3021 InitXNext = Builder.CreateLShr(InitX, 1);
3022 else if (DefX->getOpcode() == Instruction::Shl) // cttz
3023 InitXNext = Builder.CreateShl(InitX, 1);
3024 else
3025 llvm_unreachable("Unexpected opcode!");
3026 } else
3027 InitXNext = InitX;
3028 Value *Count =
3029 createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
3030 Type *CountTy = Count->getType();
3031 Count = Builder.CreateSub(
3032 ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count);
3033 if (InsertSub)
3034 Count = Builder.CreateSub(Count, ConstantInt::get(CountTy, 1));
3035 Value *NewCount = Count;
3036 if (IsCntPhiUsedOutsideLoop)
3037 Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1));
3038
3039 NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType());
3040
3041 Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
3042 if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) {
3043 // If the counter was being incremented in the loop, add NewCount to the
3044 // counter's initial value, but only if the initial value is not zero.
3045 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
3046 if (!InitConst || !InitConst->isZero())
3047 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
3048 } else {
3049 // If the count was being decremented in the loop, subtract NewCount from
3050 // the counter's initial value.
3051 NewCount = Builder.CreateSub(CntInitVal, NewCount);
3052 }
3053
3054 // Step 2: Insert new IV and loop condition:
3055 // loop:
3056 // ...
3057 // PhiCount = PHI [Count, Dec]
3058 // ...
3059 // Dec = PhiCount - 1
3060 // ...
3061 // Br: loop if (Dec != 0)
3062 BasicBlock *Body = *(CurLoop->block_begin());
3063 auto *LbBr = cast<CondBrInst>(Body->getTerminator());
3064 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
3065
3066 PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi");
3067 TcPhi->insertBefore(Body->begin());
3068
3069 Builder.SetInsertPoint(LbCond);
3070 Instruction *TcDec = cast<Instruction>(Builder.CreateSub(
3071 TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true));
3072
3073 TcPhi->addIncoming(Count, Preheader);
3074 TcPhi->addIncoming(TcDec, Body);
3075
3077 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
3078 LbCond->setPredicate(Pred);
3079 LbCond->setOperand(0, TcDec);
3080 LbCond->setOperand(1, ConstantInt::get(CountTy, 0));
3081
3082 // Step 3: All the references to the original counter outside
3083 // the loop are replaced with the NewCount
3084 if (IsCntPhiUsedOutsideLoop)
3085 CntPhi->replaceUsesOutsideBlock(NewCount, Body);
3086 else
3087 CntInst->replaceUsesOutsideBlock(NewCount, Body);
3088
3089 // step 4: Forget the "non-computable" trip-count SCEV associated with the
3090 // loop. The loop would otherwise not be deleted even if it becomes empty.
3091 SE->forgetLoop(CurLoop);
3092}
3093
3094void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
3095 Instruction *CntInst,
3096 PHINode *CntPhi, Value *Var) {
3097 BasicBlock *PreHead = CurLoop->getLoopPreheader();
3098 auto *PreCondBr = cast<CondBrInst>(PreCondBB->getTerminator());
3099 const DebugLoc &DL = CntInst->getDebugLoc();
3100
3101 // Assuming before transformation, the loop is following:
3102 // if (x) // the precondition
3103 // do { cnt++; x &= x - 1; } while(x);
3104
3105 // Step 1: Insert the ctpop instruction at the end of the precondition block
3106 IRBuilder<> Builder(PreCondBr);
3107 Value *PopCnt, *NewCount, *TripCnt;
3108 {
3109 PopCnt = createPopcntIntrinsic(Builder, Var, DL);
3110 NewCount =
3111 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
3112
3113 if (NewCount != PopCnt)
3114 (cast<Instruction>(NewCount))->setDebugLoc(DL);
3115
3116 // TripCnt is exactly the number of iterations the loop has
3117 TripCnt = PopCnt;
3118
3119 // If the population counter's initial value is not zero, insert Add Inst.
3120 Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
3121 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
3122 if (!InitConst || !InitConst->isZero()) {
3123 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
3124 (cast<Instruction>(NewCount))->setDebugLoc(DL);
3125 }
3126 }
3127
3128 // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
3129 // "if (TripCnt == 0) loop-exit". Without this change, the intrinsic
3130 // function would be partial dead code, and downstream passes will drag
3131 // it back from the precondition block to the preheader.
3132 {
3133 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
3134
3135 Value *Opnd0 = TripCnt;
3136 Value *Opnd1 = ConstantInt::get(TripCnt->getType(), 0);
3137 if (PreCond->getOperand(0) != Var)
3138 std::swap(Opnd0, Opnd1);
3139
3140 ICmpInst *NewPreCond = cast<ICmpInst>(
3141 Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
3142 PreCondBr->setCondition(NewPreCond);
3143
3145 }
3146
3147 // Step 3: Note that the population count is exactly the trip count of the
3148 // loop in question, which enable us to convert the loop from noncountable
3149 // loop into a countable one. The benefit is twofold:
3150 //
3151 // - If the loop only counts population, the entire loop becomes dead after
3152 // the transformation. It is a lot easier to prove a countable loop dead
3153 // than to prove a noncountable one. (In some C dialects, an infinite loop
3154 // isn't dead even if it computes nothing useful. In general, DCE needs
3155 // to prove a noncountable loop finite before safely delete it.)
3156 //
3157 // - If the loop also performs something else, it remains alive.
3158 // Since it is transformed to countable form, it can be aggressively
3159 // optimized by some optimizations which are in general not applicable
3160 // to a noncountable loop.
3161 //
3162 // After this step, this loop (conceptually) would look like following:
3163 // newcnt = __builtin_ctpop(x);
3164 // t = newcnt;
3165 // if (x)
3166 // do { cnt++; x &= x-1; t--) } while (t > 0);
3167 BasicBlock *Body = *(CurLoop->block_begin());
3168 {
3169 auto *LbBr = cast<CondBrInst>(Body->getTerminator());
3170 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
3171 Type *Ty = TripCnt->getType();
3172
3173 PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi");
3174 TcPhi->insertBefore(Body->begin());
3175
3176 Builder.SetInsertPoint(LbCond);
3178 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), "tcdec",
3179 /*HasNUW=*/true, /*HasNSW=*/false));
3180
3181 TcPhi->addIncoming(TripCnt, PreHead);
3182 TcPhi->addIncoming(TcDec, Body);
3183
3185 (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_EQ;
3186 LbCond->setPredicate(Pred);
3187 LbCond->setOperand(0, TcDec);
3188 LbCond->setOperand(1, ConstantInt::get(Ty, 0));
3189 }
3190
3191 // Step 4: All the references to the original population counter outside
3192 // the loop are replaced with the NewCount -- the value returned from
3193 // __builtin_ctpop().
3194 CntInst->replaceUsesOutsideBlock(NewCount, Body);
3195
3196 // step 5: Forget the "non-computable" trip-count SCEV associated with the
3197 // loop. The loop would otherwise not be deleted even if it becomes empty.
3198 SE->forgetLoop(CurLoop);
3199}
3200
3201/// Match loop-invariant value.
3202template <typename SubPattern_t> struct match_LoopInvariant {
3203 SubPattern_t SubPattern;
3204 const Loop *L;
3205
3206 match_LoopInvariant(const SubPattern_t &SP, const Loop *L)
3207 : SubPattern(SP), L(L) {}
3208
3209 template <typename ITy> bool match(ITy *V) const {
3210 return L->isLoopInvariant(V) && SubPattern.match(V);
3211 }
3212};
3213
3214/// Matches if the value is loop-invariant.
3215template <typename Ty>
3216inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) {
3217 return match_LoopInvariant<Ty>(M, L);
3218}
3219
3220/// Return true if the idiom is detected in the loop.
3221///
3222/// The core idiom we are trying to detect is:
3223/// \code
3224/// entry:
3225/// <...>
3226/// %bitmask = shl i32 1, %bitpos
3227/// br label %loop
3228///
3229/// loop:
3230/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
3231/// %x.curr.bitmasked = and i32 %x.curr, %bitmask
3232/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
3233/// %x.next = shl i32 %x.curr, 1
3234/// <...>
3235/// br i1 %x.curr.isbitunset, label %loop, label %end
3236///
3237/// end:
3238/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
3239/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
3240/// <...>
3241/// \endcode
3242static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX,
3243 Value *&BitMask, Value *&BitPos,
3244 Value *&CurrX, Instruction *&NextX) {
3246 " Performing shift-until-bittest idiom detection.\n");
3247
3248 // Give up if the loop has multiple blocks or multiple backedges.
3249 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
3250 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
3251 return false;
3252 }
3253
3254 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3255 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3256 assert(LoopPreheaderBB && "There is always a loop preheader.");
3257
3258 using namespace PatternMatch;
3259
3260 // Step 1: Check if the loop backedge is in desirable form.
3261
3263 Value *CmpLHS, *CmpRHS;
3264 BasicBlock *TrueBB, *FalseBB;
3265 if (!match(LoopHeaderBB->getTerminator(),
3266 m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
3267 m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) {
3268 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
3269 return false;
3270 }
3271
3272 // Step 2: Check if the backedge's condition is in desirable form.
3273
3274 auto MatchVariableBitMask = [&]() {
3275 return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
3276 match(CmpLHS,
3277 m_c_And(m_Value(CurrX),
3279 m_Value(BitMask),
3280 m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)),
3281 CurLoop))));
3282 };
3283
3284 auto MatchDecomposableConstantBitMask = [&]() {
3285 auto Res = llvm::decomposeBitTestICmp(
3286 CmpLHS, CmpRHS, Pred, /*LookThroughTrunc=*/true,
3287 /*AllowNonZeroC=*/false, /*DecomposeAnd=*/true);
3288 if (Res && Res->Mask.isPowerOf2()) {
3289 assert(ICmpInst::isEquality(Res->Pred));
3290 Pred = Res->Pred;
3291 CurrX = Res->X;
3292 BitMask = ConstantInt::get(CurrX->getType(), Res->Mask);
3293 BitPos = ConstantInt::get(CurrX->getType(), Res->Mask.logBase2());
3294 return true;
3295 }
3296 return false;
3297 };
3298
3299 if (!MatchVariableBitMask() && !MatchDecomposableConstantBitMask()) {
3300 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n");
3301 return false;
3302 }
3303
3304 // Step 3: Check if the recurrence is in desirable form.
3305 auto *CurrXPN = dyn_cast<PHINode>(CurrX);
3306 if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {
3307 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
3308 return false;
3309 }
3310
3311 BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);
3312 NextX =
3313 dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB));
3314
3315 assert(CurLoop->isLoopInvariant(BaseX) &&
3316 "Expected BaseX to be available in the preheader!");
3317
3318 if (!NextX || (!match(NextX, m_Shl(m_Specific(CurrX), m_One())) &&
3319 !match(NextX, m_LShr(m_Specific(CurrX), m_One())))) {
3320 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
3321 return false;
3322 }
3323
3324 // Step 4: Check if the backedge's destinations are in desirable form.
3325
3327 "Should only get equality predicates here.");
3328
3329 // cmp-br is commutative, so canonicalize to a single variant.
3332 std::swap(TrueBB, FalseBB);
3333 }
3334
3335 // We expect to exit loop when comparison yields false,
3336 // so when it yields true we should branch back to loop header.
3337 if (TrueBB != LoopHeaderBB) {
3338 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
3339 return false;
3340 }
3341
3342 // Okay, idiom checks out.
3343 return true;
3344}
3345
3347 BasicBlock *Preheader,
3348 const DataLayout &DL,
3349 DominatorTree *DT) {
3350 using namespace PatternMatch;
3351
3352 auto *Pos = dyn_cast<ConstantInt>(BitPos);
3353 unsigned Bitwidth = X->getType()->getScalarSizeInBits();
3354 if (!Pos || Bitwidth == 1 || Pos->getValue().uge(Bitwidth))
3355 return false;
3356
3357 SimplifyQuery SQ(DL, DT, /*AC=*/nullptr, Preheader->getTerminator());
3358 if (!isKnownNonZero(X, SQ))
3359 return false;
3360 if (Pos->isZero())
3361 return true;
3362
3363 // The guard must rule out set bits below BitPos; those bits can never
3364 // reach the tested position when X shifts right.
3365 BasicBlock *GuardBB = Preheader->getSinglePredecessor();
3366 if (!GuardBB)
3367 return false;
3368 auto *Guard = dyn_cast<CondBrInst>(GuardBB->getTerminator());
3369 if (!Guard)
3370 return false;
3371
3373 Value *LHS;
3374 if (!match(Guard->getCondition(), m_ICmp(Pred, m_Value(LHS), m_Zero())) ||
3376 return false;
3377
3378 const APInt *Mask;
3379 if (!match(LHS, m_And(m_Specific(X), m_APInt(Mask))))
3380 return false;
3381
3382 BasicBlock *ZeroSuccessor =
3383 Guard->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 0 : 1);
3384 if (ZeroSuccessor != Preheader)
3385 return false;
3386
3387 return Mask->countr_one() >= Pos->getZExtValue();
3388}
3389
3390/// Look for the following loop:
3391/// \code
3392/// entry:
3393/// <...>
3394/// %bitmask = shl i32 1, %bitpos
3395/// br label %loop
3396///
3397/// loop:
3398/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
3399/// %x.curr.bitmasked = and i32 %x.curr, %bitmask
3400/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
3401/// %x.next = shl i32 %x.curr, 1
3402/// <...>
3403/// br i1 %x.curr.isbitunset, label %loop, label %end
3404///
3405/// end:
3406/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
3407/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
3408/// <...>
3409/// \endcode
3410///
3411/// And transform it into:
3412/// \code
3413/// entry:
3414/// %bitmask = shl i32 1, %bitpos
3415/// %lowbitmask = add i32 %bitmask, -1
3416/// %mask = or i32 %lowbitmask, %bitmask
3417/// %x.masked = and i32 %x, %mask
3418/// %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked,
3419/// i1 true)
3420/// %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros
3421/// %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -1
3422/// %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos
3423/// %tripcount = add i32 %backedgetakencount, 1
3424/// %x.curr = shl i32 %x, %backedgetakencount
3425/// %x.next = shl i32 %x, %tripcount
3426/// br label %loop
3427///
3428/// loop:
3429/// %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ]
3430/// %loop.iv.next = add nuw i32 %loop.iv, 1
3431/// %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount
3432/// <...>
3433/// br i1 %loop.ivcheck, label %end, label %loop
3434///
3435/// end:
3436/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
3437/// %x.next.res = phi i32 [ %x.next, %loop ] <...>
3438/// <...>
3439/// \endcode
3440/// A logical right-shift recurrence uses cttz of X shifted by BitPos instead,
3441/// provided the preheader proves that the loop will reach a set bit.
3442bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {
3443 bool MadeChange = false;
3444
3445 Value *X, *BitMask, *BitPos, *XCurr;
3446 Instruction *XNext;
3447 if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr,
3448 XNext)) {
3450 " shift-until-bittest idiom detection failed.\n");
3451 return MadeChange;
3452 }
3453 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n");
3454
3455 // Ok, it is the idiom we were looking for, we *could* transform this loop,
3456 // but is it profitable to transform?
3457
3458 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3459 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3460 assert(LoopPreheaderBB && "There is always a loop preheader.");
3461
3462 BasicBlock *SuccessorBB = CurLoop->getExitBlock();
3463 assert(SuccessorBB && "There is only a single successor.");
3464
3465 IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
3466 Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc());
3467
3468 bool IsRightShift = XNext->getOpcode() == Instruction::LShr;
3469 Intrinsic::ID IntrID = IsRightShift ? Intrinsic::cttz : Intrinsic::ctlz;
3470 Type *Ty = X->getType();
3471 unsigned Bitwidth = Ty->getScalarSizeInBits();
3472
3473 // A right shift must be guaranteed to reach a set bit at BitPos.
3474 if (IsRightShift && !isRightShiftBitTestKnownToTerminate(
3475 X, BitPos, LoopPreheaderBB, *DL, DT)) {
3476 return false;
3477 }
3478
3481
3482 // The rewrite is considered to be unprofitable iff and only iff the
3483 // intrinsic/shift we'll use are not cheap. Note that we are okay with *just*
3484 // making the loop countable, even if nothing else changes.
3486 IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getTrue()});
3487 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
3490 " Intrinsic is too costly, not beneficial\n");
3491 return MadeChange;
3492 }
3493 if (TTI->getArithmeticInstrCost(XNext->getOpcode(), Ty, CostKind) >
3495 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n");
3496 return MadeChange;
3497 }
3498
3499 // Ok, transform appears worthwhile.
3500 MadeChange = true;
3501
3502 if (!isGuaranteedNotToBeUndefOrPoison(BitPos)) {
3503 // BitMask may be computed from BitPos, Freeze BitPos so we can increase
3504 // it's use count.
3505 std::optional<BasicBlock::iterator> InsertPt = std::nullopt;
3506 if (auto *BitPosI = dyn_cast<Instruction>(BitPos))
3507 InsertPt = BitPosI->getInsertionPointAfterDef();
3508 else
3509 InsertPt = DT->getRoot()->getFirstNonPHIOrAlloca();
3510 if (!InsertPt)
3511 return false;
3512 FreezeInst *BitPosFrozen =
3513 new FreezeInst(BitPos, BitPos->getName() + ".fr", *InsertPt);
3514 BitPos->replaceUsesWithIf(BitPosFrozen, [BitPosFrozen](Use &U) {
3515 return U.getUser() != BitPosFrozen;
3516 });
3517 BitPos = BitPosFrozen;
3518 }
3519
3520 // Step 1: Compute the loop trip count.
3521
3522 Value *LoopBackedgeTakenCount;
3523 if (IsRightShift) {
3524 Value *ShiftedX = Builder.CreateLShr(X, BitPos);
3525 LoopBackedgeTakenCount = Builder.CreateIntrinsic(
3526 IntrID, Ty, {ShiftedX, /*is_zero_poison=*/Builder.getTrue()});
3527 } else {
3528 Value *LowBitMask =
3529 Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty),
3530 BitPos->getName() + ".lowbitmask");
3531 Value *Mask =
3532 Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask");
3533 Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked");
3534 Value *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(
3535 IntrID, Ty, {XMasked, /*is_zero_poison=*/Builder.getTrue()},
3536 /*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros");
3537 Value *XMaskedNumActiveBits = Builder.CreateSub(
3538 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros,
3539 XMasked->getName() + ".numactivebits",
3540 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
3541 Value *XMaskedLeadingOnePos = Builder.CreateAdd(
3542 XMaskedNumActiveBits, Constant::getAllOnesValue(Ty),
3543 XMasked->getName() + ".leadingonepos", /*HasNUW=*/false,
3544 /*HasNSW=*/Bitwidth > 2);
3545
3546 LoopBackedgeTakenCount = Builder.CreateSub(
3547 BitPos, XMaskedLeadingOnePos,
3548 CurLoop->getName() + ".backedgetakencount", /*HasNUW=*/true,
3549 /*HasNSW=*/true);
3550 }
3551 // We know loop's backedge-taken count, but what's loop's trip count?
3552 // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
3553 Value *LoopTripCount =
3554 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
3555 CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
3556 /*HasNSW=*/Bitwidth != 2);
3557
3558 // Step 2: Compute the recurrence's final value without a loop.
3559
3560 // NewX is always safe to compute, because `LoopBackedgeTakenCount`
3561 // will always be smaller than `bitwidth(X)`, i.e. we never get poison.
3562 Value *NewX = IsRightShift ? Builder.CreateLShr(X, LoopBackedgeTakenCount)
3563 : Builder.CreateShl(X, LoopBackedgeTakenCount);
3564 NewX->takeName(XCurr);
3565 if (auto *I = dyn_cast<Instruction>(NewX))
3566 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
3567
3568 Value *NewXNext;
3569 // Shifting X by LoopTripCount is poison if the count equals Bitwidth.
3570 // For right shifts, shift NewX by one instead. For left shifts, this can
3571 // happen when BitPos is the highest bit and X is one, so use a single
3572 // additional shift unless the larger shift is known to be safe.
3573 if (IsRightShift) {
3574 NewXNext = Builder.CreateLShr(NewX, ConstantInt::get(Ty, 1));
3575 } else if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() ||
3576 PatternMatch::match(BitPos,
3580 Ty->getScalarSizeInBits() - 1)))) {
3581 NewXNext = Builder.CreateShl(X, LoopTripCount);
3582 } else {
3583 // Otherwise, just additionally shift by one. It's the smallest solution,
3584 // alternatively, we could check that NewX is INT_MIN (or BitPos is )
3585 // and select 0 instead.
3586 NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));
3587 }
3588
3589 NewXNext->takeName(XNext);
3590 if (auto *I = dyn_cast<Instruction>(NewXNext))
3591 I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
3592
3593 // Step 3: Adjust the successor basic block to receive the computed
3594 // recurrence's final value instead of the recurrence itself.
3595
3596 XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB);
3597 XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB);
3598
3599 // Step 4: Rewrite the loop into a countable form, with canonical IV.
3600
3601 // The new canonical induction variable.
3602 Builder.SetInsertPoint(LoopHeaderBB->begin());
3603 auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
3604
3605 // The induction itself.
3606 // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
3607 Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
3608 auto *IVNext =
3609 Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
3610 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
3611
3612 // The loop trip count check.
3613 auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,
3614 CurLoop->getName() + ".ivcheck");
3615 SmallVector<uint32_t> BranchWeights;
3616 const bool HasBranchWeights =
3617 extractBranchWeights(*LoopHeaderBB->getTerminator(), BranchWeights);
3618
3619 auto *BI = Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);
3620 if (HasBranchWeights) {
3621 if (SuccessorBB == LoopHeaderBB->getTerminator()->getSuccessor(1))
3622 std::swap(BranchWeights[0], BranchWeights[1]);
3623 // We're not changing the loop profile, so we can reuse the original loop's
3624 // profile.
3625 setBranchWeights(*BI, BranchWeights,
3626 /*IsExpected=*/false);
3627 }
3628
3629 LoopHeaderBB->getTerminator()->eraseFromParent();
3630
3631 // Populate the IV PHI.
3632 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
3633 IV->addIncoming(IVNext, LoopHeaderBB);
3634
3635 // Step 5: Forget the "non-computable" trip-count SCEV associated with the
3636 // loop. The loop would otherwise not be deleted even if it becomes empty.
3637
3638 SE->forgetLoop(CurLoop);
3639
3640 // Other passes will take care of actually deleting the loop if possible.
3641
3642 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n");
3643
3644 ++NumShiftUntilBitTest;
3645 return MadeChange;
3646}
3647
3648/// Return true if the idiom is detected in the loop.
3649///
3650/// The core idiom we are trying to detect is:
3651/// \code
3652/// entry:
3653/// <...>
3654/// %start = <...>
3655/// %extraoffset = <...>
3656/// <...>
3657/// br label %for.cond
3658///
3659/// loop:
3660/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
3661/// %nbits = add nsw i8 %iv, %extraoffset
3662/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
3663/// %val.shifted.iszero = icmp eq i8 %val.shifted, 0
3664/// %iv.next = add i8 %iv, 1
3665/// <...>
3666/// br i1 %val.shifted.iszero, label %end, label %loop
3667///
3668/// end:
3669/// %iv.res = phi i8 [ %iv, %loop ] <...>
3670/// %nbits.res = phi i8 [ %nbits, %loop ] <...>
3671/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
3672/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
3673/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
3674/// <...>
3675/// \endcode
3677 Instruction *&ValShiftedIsZero,
3678 Intrinsic::ID &IntrinID, Instruction *&IV,
3679 Value *&Start, Value *&Val,
3680 const SCEV *&ExtraOffsetExpr,
3681 bool &InvertedCond) {
3683 " Performing shift-until-zero idiom detection.\n");
3684
3685 // Give up if the loop has multiple blocks or multiple backedges.
3686 if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
3687 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
3688 return false;
3689 }
3690
3691 Instruction *ValShifted, *NBits, *IVNext;
3692 Value *ExtraOffset;
3693
3694 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3695 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3696 assert(LoopPreheaderBB && "There is always a loop preheader.");
3697
3698 using namespace PatternMatch;
3699
3700 // Step 1: Check if the loop backedge, condition is in desirable form.
3701
3703 BasicBlock *TrueBB, *FalseBB;
3704 if (!match(LoopHeaderBB->getTerminator(),
3705 m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB),
3706 m_BasicBlock(FalseBB))) ||
3707 !match(ValShiftedIsZero,
3708 m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) ||
3710 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
3711 return false;
3712 }
3713
3714 // Step 2: Check if the comparison's operand is in desirable form.
3715 // FIXME: Val could be a one-input PHI node, which we should look past.
3716 if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop),
3717 m_Instruction(NBits)))) {
3718 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n");
3719 return false;
3720 }
3721 IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz
3722 : Intrinsic::ctlz;
3723
3724 // Step 3: Check if the shift amount is in desirable form.
3725
3726 if (match(NBits, m_c_Add(m_Instruction(IV),
3727 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
3728 (NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap()))
3729 ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset));
3730 else if (match(NBits,
3732 m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
3733 NBits->hasNoSignedWrap())
3734 ExtraOffsetExpr = SE->getSCEV(ExtraOffset);
3735 else {
3736 IV = NBits;
3737 ExtraOffsetExpr = SE->getZero(NBits->getType());
3738 }
3739
3740 // Step 4: Check if the recurrence is in desirable form.
3741 auto *IVPN = dyn_cast<PHINode>(IV);
3742 if (!IVPN || IVPN->getParent() != LoopHeaderBB) {
3743 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
3744 return false;
3745 }
3746
3747 Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);
3748 IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB));
3749
3750 if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) {
3751 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
3752 return false;
3753 }
3754
3755 // Step 4: Check if the backedge's destinations are in desirable form.
3756
3758 "Should only get equality predicates here.");
3759
3760 // cmp-br is commutative, so canonicalize to a single variant.
3761 InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ;
3762 if (InvertedCond) {
3764 std::swap(TrueBB, FalseBB);
3765 }
3766
3767 // We expect to exit loop when comparison yields true,
3768 // so when it yields false we should branch back to loop header.
3769 if (FalseBB != LoopHeaderBB) {
3770 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
3771 return false;
3772 }
3773
3774 // The new, countable, loop will certainly only run a known number of
3775 // iterations, It won't be infinite. But the old loop might be infinite
3776 // under certain conditions. For logical shifts, the value will become zero
3777 // after at most bitwidth(%Val) loop iterations. However, for arithmetic
3778 // right-shift, iff the sign bit was set, the value will never become zero,
3779 // and the loop may never finish.
3780 if (ValShifted->getOpcode() == Instruction::AShr &&
3781 !isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) {
3782 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n");
3783 return false;
3784 }
3785
3786 // Okay, idiom checks out.
3787 return true;
3788}
3789
3790/// Look for the following loop:
3791/// \code
3792/// entry:
3793/// <...>
3794/// %start = <...>
3795/// %extraoffset = <...>
3796/// <...>
3797/// br label %loop
3798///
3799/// loop:
3800/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %loop ]
3801/// %nbits = add nsw i8 %iv, %extraoffset
3802/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
3803/// %val.shifted.iszero = icmp eq i8 %val.shifted, 0
3804/// %iv.next = add i8 %iv, 1
3805/// <...>
3806/// br i1 %val.shifted.iszero, label %end, label %loop
3807///
3808/// end:
3809/// %iv.res = phi i8 [ %iv, %loop ] <...>
3810/// %nbits.res = phi i8 [ %nbits, %loop ] <...>
3811/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
3812/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
3813/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
3814/// <...>
3815/// \endcode
3816///
3817/// And transform it into:
3818/// \code
3819/// entry:
3820/// <...>
3821/// %start = <...>
3822/// %extraoffset = <...>
3823/// <...>
3824/// %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0)
3825/// %val.numactivebits = sub i8 8, %val.numleadingzeros
3826/// %extraoffset.neg = sub i8 0, %extraoffset
3827/// %tmp = add i8 %val.numactivebits, %extraoffset.neg
3828/// %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start)
3829/// %loop.tripcount = sub i8 %iv.final, %start
3830/// br label %loop
3831///
3832/// loop:
3833/// %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ]
3834/// %loop.iv.next = add i8 %loop.iv, 1
3835/// %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount
3836/// %iv = add i8 %loop.iv, %start
3837/// <...>
3838/// br i1 %loop.ivcheck, label %end, label %loop
3839///
3840/// end:
3841/// %iv.res = phi i8 [ %iv.final, %loop ] <...>
3842/// <...>
3843/// \endcode
3844bool LoopIdiomRecognize::recognizeShiftUntilZero() {
3845 bool MadeChange = false;
3846
3847 Instruction *ValShiftedIsZero;
3848 Intrinsic::ID IntrID;
3849 Instruction *IV;
3850 Value *Start, *Val;
3851 const SCEV *ExtraOffsetExpr;
3852 bool InvertedCond;
3853 if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV,
3854 Start, Val, ExtraOffsetExpr, InvertedCond)) {
3856 " shift-until-zero idiom detection failed.\n");
3857 return MadeChange;
3858 }
3859 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n");
3860
3861 // Ok, it is the idiom we were looking for, we *could* transform this loop,
3862 // but is it profitable to transform?
3863
3864 BasicBlock *LoopHeaderBB = CurLoop->getHeader();
3865 BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
3866 assert(LoopPreheaderBB && "There is always a loop preheader.");
3867
3868 BasicBlock *SuccessorBB = CurLoop->getExitBlock();
3869 assert(SuccessorBB && "There is only a single successor.");
3870
3871 IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
3872 Builder.SetCurrentDebugLocation(IV->getDebugLoc());
3873
3874 Type *Ty = Val->getType();
3875 unsigned Bitwidth = Ty->getScalarSizeInBits();
3876
3879
3880 // The rewrite is considered to be unprofitable iff and only iff the
3881 // intrinsic we'll use are not cheap. Note that we are okay with *just*
3882 // making the loop countable, even if nothing else changes.
3884 IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getFalse()});
3885 InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
3888 " Intrinsic is too costly, not beneficial\n");
3889 return MadeChange;
3890 }
3891
3892 // Ok, transform appears worthwhile.
3893 MadeChange = true;
3894
3895 bool OffsetIsZero = ExtraOffsetExpr->isZero();
3896
3897 // Step 1: Compute the loop's final IV value / trip count.
3898
3899 Value *ValNumLeadingZeros = Builder.CreateIntrinsic(
3900 IntrID, Ty, {Val, /*is_zero_poison=*/Builder.getFalse()},
3901 /*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros");
3902 Value *ValNumActiveBits = Builder.CreateSub(
3903 ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros,
3904 Val->getName() + ".numactivebits", /*HasNUW=*/true,
3905 /*HasNSW=*/Bitwidth != 2);
3906
3907 SCEVExpander Expander(*SE, "loop-idiom");
3908 Expander.setInsertPoint(&*Builder.GetInsertPoint());
3909 Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);
3910
3911 Value *ValNumActiveBitsOffset = Builder.CreateAdd(
3912 ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset",
3913 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true);
3914 Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},
3915 {ValNumActiveBitsOffset, Start},
3916 /*FMFSource=*/nullptr, "iv.final");
3917
3918 auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub(
3919 IVFinal, Start, CurLoop->getName() + ".backedgetakencount",
3920 /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true));
3921 // FIXME: or when the offset was `add nuw`
3922
3923 // We know loop's backedge-taken count, but what's loop's trip count?
3924 Value *LoopTripCount =
3925 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
3926 CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
3927 /*HasNSW=*/Bitwidth != 2);
3928
3929 // Step 2: Adjust the successor basic block to receive the original
3930 // induction variable's final value instead of the orig. IV itself.
3931
3932 IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);
3933
3934 // Step 3: Rewrite the loop into a countable form, with canonical IV.
3935
3936 // The new canonical induction variable.
3937 Builder.SetInsertPoint(LoopHeaderBB->begin());
3938 auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
3939
3940 // The induction itself.
3941 Builder.SetInsertPoint(LoopHeaderBB->getFirstNonPHIIt());
3942 auto *CIVNext =
3943 Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next",
3944 /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
3945
3946 // The loop trip count check.
3947 auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,
3948 CurLoop->getName() + ".ivcheck");
3949 auto *NewIVCheck = CIVCheck;
3950 if (InvertedCond) {
3951 NewIVCheck = Builder.CreateNot(CIVCheck);
3952 NewIVCheck->takeName(ValShiftedIsZero);
3953 }
3954
3955 // The original IV, but rebased to be an offset to the CIV.
3956 auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false,
3957 /*HasNSW=*/true); // FIXME: what about NUW?
3958 IVDePHId->takeName(IV);
3959
3960 // The loop terminator.
3961 Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
3962 SmallVector<uint32_t> BranchWeights;
3963 const bool HasBranchWeights =
3964 extractBranchWeights(*LoopHeaderBB->getTerminator(), BranchWeights);
3965
3966 auto *BI = Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);
3967 if (HasBranchWeights) {
3968 if (InvertedCond)
3969 std::swap(BranchWeights[0], BranchWeights[1]);
3970 // We're not changing the loop profile, so we can reuse the original loop's
3971 // profile.
3972 setBranchWeights(*BI, BranchWeights, /*IsExpected=*/false);
3973 }
3974 LoopHeaderBB->getTerminator()->eraseFromParent();
3975
3976 // Populate the IV PHI.
3977 CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
3978 CIV->addIncoming(CIVNext, LoopHeaderBB);
3979
3980 // Step 4: Forget the "non-computable" trip-count SCEV associated with the
3981 // loop. The loop would otherwise not be deleted even if it becomes empty.
3982
3983 SE->forgetLoop(CurLoop);
3984
3985 // Step 5: Try to cleanup the loop's body somewhat.
3986 IV->replaceAllUsesWith(IVDePHId);
3987 IV->eraseFromParent();
3988
3989 ValShiftedIsZero->replaceAllUsesWith(NewIVCheck);
3990 ValShiftedIsZero->eraseFromParent();
3991
3992 // Other passes will take care of actually deleting the loop if possible.
3993
3994 LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n");
3995
3996 ++NumShiftUntilZero;
3997 return MadeChange;
3998}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
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)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Resource Access
This file defines the DenseMap class.
#define DEBUG_TYPE
ManagedStatic< 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 PHINode * getRecurrenceVar(Value *VarX, Instruction *DefX, BasicBlock *LoopEntry)
static Value * createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL)
static void addRangeAttrFromTripCount(CallInst *NewCall, uint64_t ElemsPerIter, Loop *L, ScalarEvolution *SE)
Add a range to the length (or, for memset.pattern, the count) of a newly formed memset/memset....
static Value * matchShiftULTCondition(CondBrInst *BI, BasicBlock *LoopEntry, APInt &Threshold)
Check if the given conditional branch is based on an unsigned less-than comparison between a variable...
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 Value * matchCondition(CondBrInst *BI, BasicBlock *LoopEntry, bool JmpOnZero=false)
Check if the given conditional branch is based on the comparison between a variable and zero,...
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 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 Value * createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL, bool ZeroCheck, Intrinsic::ID IID)
static bool isRightShiftBitTestKnownToTerminate(Value *X, Value *BitPos, BasicBlock *Preheader, const DataLayout &DL, DominatorTree *DT)
static const SCEV * getStartForNegStride(const SCEV *Start, const SCEV *BECount, Type *IntPtr, const SCEV *StoreSizeSCEV, ScalarEvolution *SE)
static APInt getStoreStride(const SCEVAddRecExpr *StoreEv)
match_LoopInvariant< Ty > m_LoopInvariant(const Ty &M, const Loop *L)
Matches if the value is loop-invariant.
static bool isSameByteValueStore(Instruction &I, Value *SplatByte, Loop *L, const DataLayout &DL)
Return true if I is a (simple, loop-invariant-valued) store of the same bytewise value SplatByte.
static void deleteDeadInstruction(Instruction *I)
#define I(x, y, z)
Definition MD5.cpp:57
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)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
Func MI getDebugLoc()))
This file contains some templates that are useful if you are working with the STL at all.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
Value * LHS
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:1572
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
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:463
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI const_iterator getFirstNonPHIOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a static alloca,...
size_t size() const
Definition BasicBlock.h:461
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
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:409
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
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:831
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
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:231
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
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:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
This is an important base class in LLVM.
Definition Constant.h:44
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:64
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:126
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
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 LLVM_ABI CRCTable genSarwateTable(const APInt &GenPoly, bool IsBigEndian)
Generate a lookup table of 256 entries by interleaving the generating polynomial.
static LLVM_ABI std::pair< APInt, APInt > genBarrettConstants(const PolynomialInfo &Info)
Auxilary entry point after analysis to generate constants for a GF(2) Barrett Reduction.
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:111
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition IRBuilder.h:446
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2215
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
static InstructionCost getInvalid(CostType Val=0)
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 BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
iterator_range< user_iterator > users()
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.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
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 isAtomic() const
Return true if this load has an atomic ordering.
bool isUnordered() const
Align getAlign() const
Return the alignment of the access that is being performed.
static LocationSize precise(uint64_t Value)
bool isPrecise() const
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 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.
LLVM_ABI 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
LLVM_ABI DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:694
LLVM_ABI bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:68
LLVM_ABI ICmpInst * getLatchCmpInst() const
Get the latch condition instruction.
Definition LoopInfo.cpp:199
StringRef getName() const
Definition LoopInfo.h:419
LLVM_ABI 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:175
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:918
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:689
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
unsigned getWCharSize() const
Returns the size of the wchar_t type from the "wchar_size" module flag, or the triple default when th...
Definition Module.cpp:704
Diagnostic information for optimization analysis remarks.
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.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
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.
SCEVUse 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.
static constexpr auto FlagNUW
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.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
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 * 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 * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
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 SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
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 * 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 * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
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:57
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
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()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
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.
@ TCK_Latency
The latency of instruction.
@ TCC_Basic
The cost of a typical 'add' instruction.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
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:46
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
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:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
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:606
LLVM_ABI bool 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:556
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
Value handle that is nullable, but tries to track the Value.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
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
#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 Align[]
Key for Kernel::Arg::Metadata::mAlign.
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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
OperandType
Operands are tagged with one of the values of this enum.
Definition MCInstrDesc.h:59
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
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)
match_bind< 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.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
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.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
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)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
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.
specificloop_ty m_SpecificLoop(const Loop *L)
bool match(const SCEV *S, const Pattern &P)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
constexpr double e
DiagnosticInfoOptimizationBase::Argument NV
DiagnosticInfoOptimizationBase::setExtraArgs setExtraArgs
bool isSimple(Instruction *I)
Definition SLPUtils.cpp:841
This is an optimization pass for GlobalISel generic memory operations.
static cl::opt< bool, true > DisableLIRPHashRecognize("disable-" DEBUG_TYPE "-hashrecognize", cl::desc("Proceed with loop idiom recognize pass, " "but do not do hash-recognize analysis."), cl::location(DisableLIRP::HashRecognize), cl::init(false), cl::ReallyHidden)
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:208
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:522
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)
InstructionCost Cost
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)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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)
@ Store
The extracted value is stored (ExtractElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
const ScalarOptions & getScalarOptions(const LLVMContext &C)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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...
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:2042
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=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:622
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.
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:76
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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:547
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
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
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
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.
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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...
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)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
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)
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.
LLVM_ABI 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.
SCEVUseT< const SCEV * > SCEVUse
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
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:847
static LLVM_ABI bool Memcpy
When true, Memcpy is disabled.
static LLVM_ABI bool Wcslen
When true, Wcslen is disabled.
static LLVM_ABI bool Strlen
When true, Strlen is disabled.
static LLVM_ABI bool HashRecognize
When true, HashRecognize is disabled.
static LLVM_ABI bool Memset
When true, Memset is disabled.
static LLVM_ABI bool All
When true, the entire pass 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:111
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)