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