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