99#define DEBUG_TYPE "loop-idiom"
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");
109 "Number of uncountable loops recognized as 'shift until zero' idiom");
115 cl::desc(
"Options to disable Loop Idiom Recognize Pass."),
122 cl::desc(
"Proceed with loop idiom recognize pass, but do "
123 "not convert loop(s) to memset."),
130 cl::desc(
"Proceed with loop idiom recognize pass, but do "
131 "not convert loop(s) to memcpy."),
138 cl::desc(
"Proceed with loop idiom recognize pass, but do "
139 "not convert loop(s) to strlen."),
146 cl::desc(
"Proceed with loop idiom recognize pass, "
147 "enable conversion of loop(s) to wcslen."),
154 cl::desc(
"Proceed with loop idiom recognize pass, "
155 "but do not do hash-recognize analysis."),
160 "use-lir-code-size-heurs",
161 cl::desc(
"Use loop idiom recognition code size heuristics when compiling "
166 "loop-idiom-force-memset-pattern-intrinsic",
167 cl::desc(
"Use memset.pattern intrinsic whenever possible"),
cl::init(
false),
178 cl::desc(
"Preferred strategy for optimizing CRC loops"),
181 "Do not optimize CRC loops"),
183 "Use costing to determine strategy"),
185 "Use a Sarwate table when possible"),
187 "Use carry-less multiplication when possible")));
193class LoopIdiomRecognize {
194 Loop *CurLoop =
nullptr;
203 bool ApplyCodeSizeHeuristics;
204 std::unique_ptr<MemorySSAUpdater> MSSAU;
213 :
AA(
AA), DT(DT), LI(LI), SE(SE), TLI(TLI),
TTI(
TTI),
DL(
DL), ORE(ORE) {
215 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
218 bool runOnLoop(
Loop *L);
221 using StoreList = SmallVector<StoreInst *, 8>;
222 using StoreListMap = MapVector<Value *, StoreList>;
224 StoreListMap StoreRefsForMemset;
225 StoreListMap StoreRefsForMemsetPattern;
226 StoreList StoreRefsForMemcpy;
228 bool HasMemsetPattern;
232 enum LegalStoreKind {
237 UnorderedAtomicMemcpy,
245 bool runOnCountableLoop();
246 bool runOnLoopBlock(BasicBlock *BB,
const SCEV *BECount,
247 SmallVectorImpl<BasicBlock *> &ExitBlocks);
249 void collectStores(BasicBlock *BB);
250 LegalStoreKind isLegalStore(StoreInst *SI);
251 enum class ForMemset {
No,
Yes };
252 bool processLoopStores(SmallVectorImpl<StoreInst *> &SL,
const SCEV *BECount,
255 template <
typename MemInst>
256 bool processLoopMemIntrinsic(
258 bool (LoopIdiomRecognize::*Processor)(MemInst *,
const SCEV *),
259 const SCEV *BECount);
260 bool processLoopMemCpy(MemCpyInst *MCI,
const SCEV *BECount);
261 bool processLoopMemSet(MemSetInst *MSI,
const SCEV *BECount);
263 bool processLoopStridedStore(
Value *DestPtr,
const SCEV *StoreSizeSCEV,
264 MaybeAlign StoreAlignment,
Value *StoredVal,
265 Instruction *TheStore,
266 SmallPtrSetImpl<Instruction *> &Stores,
267 const SCEVAddRecExpr *Ev,
const SCEV *BECount,
268 bool IsNegStride,
bool IsLoopMemset =
false);
269 bool processLoopStoreOfLoopLoad(StoreInst *SI,
const SCEV *BECount);
270 bool processLoopStoreOfLoopLoad(
Value *DestPtr,
Value *SourcePtr,
271 const SCEV *StoreSize, MaybeAlign StoreAlign,
272 MaybeAlign LoadAlign, Instruction *TheStore,
273 Instruction *TheLoad,
274 const SCEVAddRecExpr *StoreEv,
275 const SCEVAddRecExpr *LoadEv,
276 const SCEV *BECount);
277 bool avoidLIRForMultiBlockLoop(
bool IsMemset =
false,
278 bool IsLoopMemset =
false);
279 bool optimizeCRCLoop(
const PolynomialInfo &Info);
280 void optimizeCRCLoopUsingClmul(
const PolynomialInfo &Info);
281 void optimizeCRCLoopUsingTableLookup(
const PolynomialInfo &Info);
287 bool runOnNoncountableLoop();
289 bool recognizePopcount();
290 void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
291 PHINode *CntPhi,
Value *Var);
293 bool ZeroCheck,
size_t CanonicalSize);
295 Instruction *DefX, PHINode *CntPhi,
296 Instruction *CntInst);
297 bool recognizeAndInsertFFS();
298 bool recognizeShiftUntilLessThan();
299 void transformLoopToCountable(
Intrinsic::ID IntrinID, BasicBlock *PreCondBB,
300 Instruction *CntInst, PHINode *CntPhi,
301 Value *Var, Instruction *DefX,
303 bool IsCntPhiUsedOutsideLoop,
304 bool InsertSub =
false);
306 bool recognizeShiftUntilBitTest();
307 bool recognizeShiftUntilZero();
308 bool recognizeAndInsertStrLen();
320 const auto *
DL = &L.getHeader()->getDataLayout();
327 LoopIdiomRecognize LIR(&AR.
AA, &AR.
DT, &AR.
LI, &AR.
SE, &AR.
TLI, &AR.
TTI,
329 if (!LIR.runOnLoop(&L))
340 I->eraseFromParent();
349bool LoopIdiomRecognize::runOnLoop(
Loop *L) {
353 if (!
L->getLoopPreheader())
358 if (Name ==
"memset" || Name ==
"memcpy" || Name ==
"strlen" ||
363 ApplyCodeSizeHeuristics =
366 HasMemset = TLI->
has(LibFunc_memset);
372 HasMemsetPattern = TLI->
has(LibFunc_memset_pattern16);
373 HasMemcpy = TLI->
has(LibFunc_memcpy);
378 return runOnCountableLoop();
380 return runOnNoncountableLoop();
383bool LoopIdiomRecognize::runOnCountableLoop() {
386 "runOnCountableLoop() called on a loop without a predictable"
387 "backedge-taken count");
405 if (SafetyInfo.anyBlockMayThrow())
408 bool MadeChange =
false;
416 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
422 MadeChange |= optimizeCRCLoop(*Res);
457 if (
DL->isBigEndian())
469 Type *CTy =
C->getType();
476LoopIdiomRecognize::LegalStoreKind
479 if (
SI->isVolatile())
480 return LegalStoreKind::None;
482 if (!
SI->isUnordered())
483 return LegalStoreKind::None;
486 if (
SI->getMetadata(LLVMContext::MD_nontemporal))
487 return LegalStoreKind::None;
489 Value *StoredVal =
SI->getValueOperand();
490 Value *StorePtr =
SI->getPointerOperand();
492 if (
DL->hasUnstableRepresentation(StoredVal->
getType()))
493 return LegalStoreKind::None;
502 bool MustPreserveExternalState =
DL->hasExternalState(StoredVal->
getType()) &&
511 return LegalStoreKind::None;
520 return LegalStoreKind::None;
531 bool UnorderedAtomic =
SI->isUnordered() && !
SI->isSimple();
535 if (!MustPreserveExternalState && !UnorderedAtomic && HasMemset &&
541 return LegalStoreKind::Memset;
543 if (!MustPreserveExternalState && !UnorderedAtomic &&
550 return LegalStoreKind::MemsetPattern;
557 unsigned StoreSize =
DL->getTypeStoreSize(
SI->getValueOperand()->getType());
559 if (StoreSize != StrideAP && StoreSize != -StrideAP)
560 return LegalStoreKind::None;
567 return LegalStoreKind::None;
570 return LegalStoreKind::None;
580 return LegalStoreKind::None;
583 UnorderedAtomic = UnorderedAtomic || LI->
isAtomic();
584 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
585 : LegalStoreKind::Memcpy;
588 return LegalStoreKind::None;
591void LoopIdiomRecognize::collectStores(
BasicBlock *BB) {
592 StoreRefsForMemset.clear();
593 StoreRefsForMemsetPattern.clear();
594 StoreRefsForMemcpy.clear();
601 switch (isLegalStore(
SI)) {
602 case LegalStoreKind::None:
605 case LegalStoreKind::Memset: {
608 StoreRefsForMemset[Ptr].push_back(
SI);
610 case LegalStoreKind::MemsetPattern: {
613 StoreRefsForMemsetPattern[Ptr].push_back(
SI);
615 case LegalStoreKind::Memcpy:
616 case LegalStoreKind::UnorderedAtomicMemcpy:
617 StoreRefsForMemcpy.push_back(
SI);
620 assert(
false &&
"unhandled return value");
629bool LoopIdiomRecognize::runOnLoopBlock(
639 bool MadeChange =
false;
646 for (
auto &SL : StoreRefsForMemset)
647 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
649 for (
auto &SL : StoreRefsForMemsetPattern)
650 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
653 for (
auto &
SI : StoreRefsForMemcpy)
654 MadeChange |= processLoopStoreOfLoopLoad(
SI, BECount);
656 MadeChange |= processLoopMemIntrinsic<MemCpyInst>(
657 BB, &LoopIdiomRecognize::processLoopMemCpy, BECount);
658 MadeChange |= processLoopMemIntrinsic<MemSetInst>(
659 BB, &LoopIdiomRecognize::processLoopMemSet, BECount);
666 const SCEV *BECount, ForMemset For) {
674 for (
unsigned i = 0, e = SL.
size(); i < e; ++i) {
675 assert(SL[i]->
isSimple() &&
"Expected only non-volatile stores.");
677 Value *FirstStoredVal = SL[i]->getValueOperand();
678 Value *FirstStorePtr = SL[i]->getPointerOperand();
682 unsigned FirstStoreSize =
DL->getTypeStoreSize(SL[i]->getValueOperand()->
getType());
685 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
690 Value *FirstSplatValue =
nullptr;
691 Constant *FirstPatternValue =
nullptr;
693 if (For == ForMemset::Yes)
698 assert((FirstSplatValue || FirstPatternValue) &&
699 "Expected either splat value or pattern value.");
707 for (j = i + 1;
j <
e; ++
j)
709 for (j = i;
j > 0; --
j)
712 for (
auto &k : IndexQueue) {
713 assert(SL[k]->
isSimple() &&
"Expected only non-volatile stores.");
714 Value *SecondStorePtr = SL[
k]->getPointerOperand();
719 if (FirstStride != SecondStride)
722 Value *SecondStoredVal = SL[
k]->getValueOperand();
723 Value *SecondSplatValue =
nullptr;
724 Constant *SecondPatternValue =
nullptr;
726 if (For == ForMemset::Yes)
731 assert((SecondSplatValue || SecondPatternValue) &&
732 "Expected either splat value or pattern value.");
735 if (For == ForMemset::Yes) {
737 FirstSplatValue = SecondSplatValue;
738 if (FirstSplatValue != SecondSplatValue)
742 FirstPatternValue = SecondPatternValue;
743 if (FirstPatternValue != SecondPatternValue)
748 ConsecutiveChain[SL[i]] = SL[
k];
768 unsigned StoreSize = 0;
771 while (Tails.
count(
I) || Heads.count(
I)) {
772 if (TransformedStores.
count(
I))
776 StoreSize +=
DL->getTypeStoreSize(
I->getValueOperand()->getType());
778 I = ConsecutiveChain[
I];
788 if (StoreSize != Stride && StoreSize != -Stride)
791 bool IsNegStride = StoreSize == -Stride;
795 if (processLoopStridedStore(StorePtr, StoreSizeSCEV,
797 HeadStore, AdjacentStores, StoreEv, BECount,
809template <
typename MemInst>
810bool LoopIdiomRecognize::processLoopMemIntrinsic(
812 bool (LoopIdiomRecognize::*Processor)(MemInst *,
const SCEV *),
813 const SCEV *BECount) {
814 bool MadeChange =
false;
820 if (!(this->*Processor)(
MI, BECount))
834bool LoopIdiomRecognize::processLoopMemCpy(
MemCpyInst *MCI,
835 const SCEV *BECount) {
848 if (!Dest || !Source)
856 const APInt *StoreStrideValue, *LoadStrideValue;
867 if ((SizeInBytes >> 32) != 0)
875 if (SizeInBytes != *StoreStrideValue && SizeInBytes != -*StoreStrideValue) {
878 <<
ore::NV(
"Inst",
"memcpy") <<
" in "
880 <<
" function will not be hoisted: "
881 <<
ore::NV(
"Reason",
"memcpy size is not equal to stride");
886 int64_t StoreStrideInt = StoreStrideValue->
getSExtValue();
887 int64_t LoadStrideInt = LoadStrideValue->
getSExtValue();
889 if (StoreStrideInt != LoadStrideInt)
892 return processLoopStoreOfLoopLoad(
899bool LoopIdiomRecognize::processLoopMemSet(
MemSetInst *MSI,
900 const SCEV *BECount) {
916 const SCEV *PointerStrideSCEV;
925 bool IsNegStride =
false;
928 if (IsConstantSize) {
938 if (SizeInBytes != *Stride && SizeInBytes != -*Stride)
941 IsNegStride = SizeInBytes == -*Stride;
949 if (
Pointer->getType()->getPointerAddressSpace() != 0) {
965 LLVM_DEBUG(
dbgs() <<
" MemsetSizeSCEV: " << *MemsetSizeSCEV <<
"\n"
966 <<
" PositiveStrideSCEV: " << *PositiveStrideSCEV
969 if (PositiveStrideSCEV != MemsetSizeSCEV) {
972 const SCEV *FoldedPositiveStride =
974 const SCEV *FoldedMemsetSize =
978 <<
" FoldedMemsetSize: " << *FoldedMemsetSize <<
"\n"
979 <<
" FoldedPositiveStride: " << *FoldedPositiveStride
982 if (FoldedPositiveStride != FoldedMemsetSize) {
1007 assert(SplatByte &&
"expected a bytewise splat value to match against");
1009 if (!
SI || !
SI->isSimple() || !L->isLoopInvariant(
SI->getValueOperand()))
1021 const SCEV *BECount,
1024 Value *SplatByte =
nullptr,
1033 const APInt *BECst, *ConstSize;
1037 std::optional<uint64_t> SizeInt = ConstSize->
tryZExtValue();
1039 if (BEInt && SizeInt)
1051 bool TrySameByteValue = !AccessSize.
isPrecise() && SplatByte &&
DL;
1068 Type *IntPtr,
const SCEV *StoreSizeSCEV,
1071 if (!StoreSizeSCEV->
isOne()) {
1086 const SCEV *StoreSizeSCEV,
Loop *CurLoop,
1088 const SCEV *TripCountSCEV =
1097bool LoopIdiomRecognize::processLoopStridedStore(
1101 const SCEV *BECount,
bool IsNegStride,
bool IsLoopMemset) {
1107 "inline mem intrinsics should be filtered out by callers");
1120 Type *DestInt8PtrTy = Builder.getPtrTy(DestAS);
1131 if (!Expander.isSafeToExpand(Start))
1140 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->
getTerminator());
1153 StoreSizeSCEV, *
AA, Stores, SplatValue,
DL))
1156 if (avoidLIRForMultiBlockLoop(
true, IsLoopMemset))
1167 std::optional<int64_t> BytesWritten;
1170 const SCEV *TripCountS =
1172 if (!Expander.isSafeToExpand(TripCountS))
1175 if (!ConstStoreSize)
1177 Value *TripCount = Expander.expandCodeFor(TripCountS, IntIdxTy,
1180 (ConstStoreSize->
getValue()->getZExtValue() * 8) /
1181 DL->getTypeSizeInBits(PatternValue->
getType());
1186 PatternRepsPerTrip == 1
1188 : Builder.CreateMul(TripCount,
1190 PatternRepsPerTrip));
1196 const SCEV *NumBytesS =
1197 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop,
DL, SE);
1201 if (!Expander.isSafeToExpand(NumBytesS))
1204 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->
getTerminator());
1206 BytesWritten = CI->getZExtValue();
1208 assert(MemsetArg &&
"MemsetArg should have been set");
1212 AATags = AATags.
merge(
Store->getAAMetadata());
1214 AATags = AATags.
extendTo(BytesWritten.value());
1220 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, MemsetArg,
1227 NewCall = Builder.CreateIntrinsicWithoutFolding(
1228 Intrinsic::experimental_memset_pattern,
1229 {DestInt8PtrTy, PatternValue->
getType(), IntIdxTy},
1230 {
BasePtr, PatternValue, MemsetArg,
1243 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1249 <<
" from store to: " << *Ev <<
" at: " << *TheStore
1255 R <<
"Transformed loop-strided store in "
1257 <<
" function into a call to "
1260 if (!Stores.empty())
1262 for (
auto *
I : Stores) {
1263 R <<
ore::NV(
"FromBlock",
I->getParent()->getName())
1271 for (
auto *
I : Stores) {
1273 MSSAU->removeMemoryAccess(
I,
true);
1277 MSSAU->getMemorySSA()->verifyMemorySSA();
1279 ExpCleaner.markResultUsed();
1286bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
StoreInst *
SI,
1287 const SCEV *BECount) {
1288 assert(
SI->isUnordered() &&
"Expected only non-volatile non-ordered stores.");
1290 Value *StorePtr =
SI->getPointerOperand();
1292 unsigned StoreSize =
DL->getTypeStoreSize(
SI->getValueOperand()->getType());
1305 return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSizeSCEV,
1307 StoreEv, LoadEv, BECount);
1311class MemmoveVerifier {
1313 explicit MemmoveVerifier(
const SCEV &LoadStart,
const SCEV &StoreStart,
1314 ScalarEvolution &SE)
1315 :
DL(SE.getDataLayout()),
1316 Off(
dyn_cast<SCEVConstant>(SE.getMinusSCEV(&StoreStart, &LoadStart))),
1318 IsSameObject(
Off != nullptr) {}
1320 bool loadAndStoreMayFormMemmove(
unsigned StoreSize,
bool IsNegStride,
1321 const Instruction &TheLoad,
1322 bool IsMemCpy)
const {
1325 if (!
Off || !BasePtr)
1327 const APInt &OffVal =
Off->getAPInt();
1332 NullBase->getPointerType()->getPointerAddressSpace()))
1339 LoadSize =
DL.getTypeSizeInBits(TheLoad.
getType()).getFixedValue() / 8;
1340 if (LoadSize != StoreSize)
1345 if (IsNegStride ? OffVal.
slt(LoadSize) : OffVal.
sgt(-LoadSize))
1351 const DataLayout &
DL;
1352 const SCEVConstant *
Off;
1356 const bool IsSameObject;
1360bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
1370 "inline mem intrinsics should be filtered out by callers");
1390 assert(ConstStoreSize &&
"store size is expected to be a constant");
1393 bool IsNegStride = StoreSize == -Stride;
1406 Value *StoreBasePtr = Expander.expandCodeFor(
1407 StrStart, Builder.getPtrTy(StrAS), Preheader->
getTerminator());
1419 IgnoredInsts.
insert(TheStore);
1422 const StringRef InstRemark = IsMemCpy ?
"memcpy" :
"load and store";
1424 bool LoopAccessStore =
1426 StoreSizeSCEV, *
AA, IgnoredInsts);
1427 if (LoopAccessStore) {
1433 IgnoredInsts.
insert(TheLoad);
1435 BECount, StoreSizeSCEV, *
AA, IgnoredInsts)) {
1439 <<
ore::NV(
"Inst", InstRemark) <<
" in "
1441 <<
" function will not be hoisted: "
1442 <<
ore::NV(
"Reason",
"The loop may access store location");
1446 IgnoredInsts.
erase(TheLoad);
1459 Value *LoadBasePtr = Expander.expandCodeFor(LdStart, Builder.getPtrTy(LdAS),
1464 MemmoveVerifier
Verifier(*LdStart, *StrStart, *SE);
1465 if (IsMemCpy && !
Verifier.IsSameObject)
1466 IgnoredInsts.
erase(TheStore);
1468 StoreSizeSCEV, *
AA, IgnoredInsts)) {
1471 <<
ore::NV(
"Inst", InstRemark) <<
" in "
1473 <<
" function will not be hoisted: "
1474 <<
ore::NV(
"Reason",
"The loop may access load location");
1480 bool UseMemMove = IsMemCpy ?
Verifier.IsSameObject : LoopAccessStore;
1489 assert((StoreAlign && LoadAlign) &&
1490 "Expect unordered load/store to have align.");
1491 if (*StoreAlign < StoreSize || *LoadAlign < StoreSize)
1498 if (StoreSize >
TTI->getAtomicMemIntrinsicMaxElementSize())
1503 if (!
Verifier.loadAndStoreMayFormMemmove(StoreSize, IsNegStride, *TheLoad,
1507 if (avoidLIRForMultiBlockLoop())
1512 const SCEV *NumBytesS =
1513 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop,
DL, SE);
1516 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->
getTerminator());
1520 AATags = AATags.
merge(StoreAATags);
1522 AATags = AATags.
extendTo(CI->getZExtValue());
1532 NewCall = Builder.CreateMemMove(StoreBasePtr, StoreAlign, LoadBasePtr,
1533 LoadAlign, NumBytes,
1537 Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign,
1538 NumBytes,
false, AATags);
1543 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1544 StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, StoreSize,
1550 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1556 <<
" from load ptr=" << *LoadEv <<
" at: " << *TheLoad
1558 <<
" from store ptr=" << *StoreEv <<
" at: " << *TheStore
1564 <<
"Formed a call to "
1566 <<
"() intrinsic from " <<
ore::NV(
"Inst", InstRemark)
1577 MSSAU->removeMemoryAccess(TheStore,
true);
1580 MSSAU->getMemorySSA()->verifyMemorySSA();
1585 ExpCleaner.markResultUsed();
1592bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(
bool IsMemset,
1593 bool IsLoopMemset) {
1594 if (ApplyCodeSizeHeuristics && CurLoop->
getNumBlocks() > 1) {
1595 if (CurLoop->
isOutermost() && (!IsMemset || !IsLoopMemset)) {
1597 <<
" : LIR " << (IsMemset ?
"Memset" :
"Memcpy")
1598 <<
" avoided: multi-block top-level loop\n");
1606bool LoopIdiomRecognize::optimizeCRCLoop(
const PolynomialInfo &Info) {
1626 TTI->getArithmeticInstrCost(Instruction::Xor, CRCTy,
CostKind);
1628 TTI->getArithmeticInstrCost(Instruction::LShr, CRCTy,
CostKind);
1630 TTI->getArithmeticInstrCost(Instruction::And, CRCTy,
CostKind);
1635 TTI->getMemoryOpCost(Instruction::Load, CRCTy,
DL->getABITypeAlign(CRCTy),
1636 DL->getDefaultGlobalsAddressSpace(),
CostKind);
1637 auto ClmulCost = [&](
unsigned BW) {
1640 return TTI->getIntrinsicInstrCost(Attrs,
CostKind);
1645 (2 * ShiftCost + 2 * XorCost + AndCost + SelectCost) *
Info.TripCount;
1650 Info.TripCount % 8 != 0
1652 : (LoadCost + XorCost + 2 * ShiftCost) * (
Info.TripCount / 8);
1656 ClmulCost(CRCBW +
Info.TripCount) +
1657 2 * XorCost + 2 * ShiftCost + AndCost;
1663 <<
"CRC loop costs: original="
1664 <<
ore::NV(
"OrigLoopCost", OrigLoopCost)
1665 <<
", table=" <<
ore::NV(
"TableStrategyCost", TableStrategyCost)
1666 <<
", clmul=" <<
ore::NV(
"ClmulStrategyCost", ClmulStrategyCost);
1669 auto ReportMissed = [&](
StringRef Reason) {
1674 <<
"CRC loop not optimized: " << Reason;
1681 <<
"CRC loop optimized using " <<
ore::NV(
"Strategy", Strategy)
1688 ReportMissed(
"disabled by user");
1693 if (
Info.TripCount % 8 == 0) {
1694 optimizeCRCLoopUsingTableLookup(Info);
1695 ReportOptimized(
"table",
"forced by user");
1698 ReportMissed(
"table strategy forced, but not possible");
1701 optimizeCRCLoopUsingClmul(Info);
1702 ReportOptimized(
"clmul",
"forced by user");
1710 if (ApplyCodeSizeHeuristics) {
1711 ReportMissed(
"optimizing for size");
1716 if (std::min(TableStrategyCost, ClmulStrategyCost) >= OrigLoopCost) {
1717 ReportMissed(
"no profitable strategy");
1721 if (TableStrategyCost <= ClmulStrategyCost) {
1722 optimizeCRCLoopUsingTableLookup(Info);
1723 ReportOptimized(
"table",
"most profitable strategy");
1725 optimizeCRCLoopUsingClmul(Info);
1726 ReportOptimized(
"clmul",
"most profitable strategy");
1735void LoopIdiomRecognize::optimizeCRCLoopUsingClmul(
const PolynomialInfo &Info) {
1744 unsigned TC =
Info.TripCount;
1755 ConstantInt::get(Ctx, Mu.zextOrTrunc(ClmulMuTy->
getBitWidth()));
1756 Value *GenPolyConst =
1757 ConstantInt::get(Ctx, FullGenPoly.zext(ClmulGPTy->
getBitWidth()));
1764 bool SetupShiftNeeded =
Info.IsBigEndian && TC != CRCBW;
1780 Value *ClmulMuInput =
1781 Builder.CreateZExtOrTrunc(
Info.LHS, SetupTy,
"crc.cast");
1787 Data = Builder.CreateZExtOrTrunc(
Data, SetupTy,
"data.cast");
1789 ClmulMuInput = Builder.CreateXor(ClmulMuInput,
Data,
"xor.crc.data");
1793 if (SetupShiftNeeded) {
1796 ? Builder.CreateShl(ClmulMuInput, TC - CRCBW,
"crc.align.tc")
1797 : Builder.CreateLShr(ClmulMuInput, CRCBW - TC,
"crc.align.tc");
1802 if (SetupTy->getBitWidth() > TC) {
1805 ClmulMuInput = Builder.CreateAnd(ClmulMuInput, Mask,
"crc.tcbits");
1811 Builder.CreateZExtOrTrunc(ClmulMuInput, ClmulMuTy,
"tcbits.cast");
1812 Value *ClmulMu = Builder.CreateBinaryIntrinsic(
1813 Intrinsic::clmul, ClmulMuInput, MuConst, {},
"clmul.mu");
1816 Value *ClmulGPInput =
1817 Info.IsBigEndian ? Builder.CreateLShr(ClmulMu, TC,
"quot.lshr") : ClmulMu;
1822 Builder.CreateZExtOrTrunc(ClmulGPInput, ClmulGPTy,
"quot.cast");
1823 Value *ClmulGP = Builder.CreateBinaryIntrinsic(Intrinsic::clmul, ClmulGPInput,
1830 Value *CRCNext = Builder.CreateZExt(
Info.LHS, ClmulGPTy,
"crc.recast");
1831 if (
Info.IsBigEndian)
1832 CRCNext = Builder.CreateShl(CRCNext, TC,
"crc.shl");
1835 CRCNext = Builder.CreateXor(CRCNext, ClmulGP,
"xor.crc.mult");
1836 if (!
Info.IsBigEndian)
1837 CRCNext = Builder.CreateLShr(CRCNext, TC,
"crc.lshr");
1840 CRCNext = Builder.CreateTrunc(CRCNext, CRCTy,
"crc.next");
1843 Info.ComputedValue->replaceUsesOutsideBlock(CRCNext, CurLoop->
getLoopLatch());
1857 Ctx, BrInst->getSuccessor(0) == CurLoop->
getExitBlock()));
1862void LoopIdiomRecognize::optimizeCRCLoopUsingTableLookup(
1864 assert(
Info.TripCount % 8 == 0 &&
"A byte-multiple trip count is required");
1870 std::array<Constant *, 256> CRCConstants;
1872 CRCConstants.begin(),
1873 [CRCTy](
const APInt &
E) { return ConstantInt::get(CRCTy, E); });
1895 unsigned NewBTC = (
Info.TripCount / 8) - 1;
1902 Value *ExitLimit = ConstantInt::get(
IV->getType(), NewBTC);
1904 Value *NewExitCond =
1905 Builder.CreateICmp(ExitPred,
IV, ExitLimit,
"exit.cond");
1927 Op = CRCBW > 8 ? Builder.CreateLShr(
Op, CRCBW - 8, Name)
1928 : Builder.CreateShl(
Op, 8 - CRCBW, Name);
1930 return LoByte(Builder,
Op, Name +
".lo.byte");
1938 PHINode *CRCPhi = Builder.CreatePHI(CRCTy, 2,
"crc");
1942 Value *CRC = CRCPhi;
1946 Value *Indexer = CRC;
1954 Value *IVBits = Builder.CreateZExtOrTrunc(
1955 Builder.CreateShl(
IV, 3,
"iv.bits"), DataTy,
"iv.indexer");
1956 Value *DataIndexer =
1957 Info.IsBigEndian ? Builder.CreateShl(
Data, IVBits,
"data.indexer")
1958 : Builder.CreateLShr(
Data, IVBits,
"data.indexer");
1959 Indexer = Builder.CreateXor(
1961 Builder.CreateZExtOrTrunc(Indexer, DataTy,
"crc.indexer.cast"),
1962 "crc.data.indexer");
1965 Indexer =
Info.IsBigEndian ? HiIdx(Builder, Indexer,
"indexer.hi")
1966 : LoByte(Builder, Indexer,
"indexer.lo");
1969 Indexer = Builder.CreateZExt(
1974 Value *CRCTableGEP =
1975 Builder.CreateInBoundsGEP(CRCTy, GV, Indexer,
"tbl.ptradd");
1976 Instruction *CRCTableLd = Builder.CreateLoad(CRCTy, CRCTableGEP,
"tbl.ld");
1980 auto *NewMemAcc = MSSAU->createMemoryAccessInBB(
1981 CRCTableLd,
nullptr, CRCTableLd->getParent(),
1988 Value *CRCNext = CRCTableLd;
1991 ? Builder.CreateShl(CRC, 8,
"crc.be.shift")
1992 : Builder.CreateLShr(CRC, 8,
"crc.le.shift");
1993 CRCNext = Builder.CreateXor(CRCShift, CRCTableLd,
"crc.next");
1998 Info.ComputedValue->replaceUsesOutsideBlock(CRCNext,
2008 MSSAU->getMemorySSA()->verifyMemorySSA();
2012bool LoopIdiomRecognize::runOnNoncountableLoop() {
2015 <<
"] Noncountable Loop %"
2018 return recognizePopcount() || recognizeAndInsertFFS() ||
2019 recognizeShiftUntilBitTest() || recognizeShiftUntilZero() ||
2020 recognizeShiftUntilLessThan() || recognizeAndInsertStrLen();
2030 bool JmpOnZero =
false) {
2036 if (!CmpZero || !CmpZero->isZero())
2047 return Cond->getOperand(0);
2054class StrlenVerifier {
2056 explicit StrlenVerifier(
const Loop *CurLoop, ScalarEvolution *SE,
2057 const TargetLibraryInfo *TLI)
2058 : CurLoop(CurLoop), SE(SE), TLI(TLI) {}
2060 bool isValidStrlenIdiom() {
2079 if (!LoopBody || LoopBody->
size() >= 15)
2100 const SCEV *LoadEv = SE->
getSCEV(IncPtr);
2113 if (OpWidth != 8 && OpWidth != 16 && OpWidth != 32)
2115 if (StepSize != OpWidth / 8)
2118 if (OpWidth != WcharSize * 8)
2122 for (Instruction &
I : *LoopBody)
2123 if (
I.mayHaveSideEffects())
2130 for (PHINode &PN : LoopExitBB->
phis()) {
2134 const SCEV *Ev = SE->
getSCEV(&PN);
2144 if (!AddRecEv || !AddRecEv->
isAffine())
2158 const Loop *CurLoop;
2159 ScalarEvolution *SE;
2160 const TargetLibraryInfo *TLI;
2163 ConstantInt *StepSizeCI;
2164 const SCEV *LoadBaseEv;
2229bool LoopIdiomRecognize::recognizeAndInsertStrLen() {
2233 StrlenVerifier
Verifier(CurLoop, SE, TLI);
2235 if (!
Verifier.isValidStrlenIdiom())
2242 assert(Preheader && LoopBody && LoopExitBB &&
2243 "Should be verified to be valid by StrlenVerifier");
2258 Builder.SetCurrentDebugLocation(CurLoop->
getStartLoc());
2260 Value *MaterialzedBase = Expander.expandCodeFor(
2262 Builder.GetInsertPoint());
2264 Value *StrLenFunc =
nullptr;
2266 StrLenFunc =
emitStrLen(MaterialzedBase, Builder, *
DL, TLI);
2268 StrLenFunc =
emitWcsLen(MaterialzedBase, Builder, *
DL, TLI);
2270 assert(StrLenFunc &&
"Failed to emit strlen function.");
2289 StrlenEv,
Base->getType())));
2291 Value *MaterializedPHI = Expander.expandCodeFor(NewEv, NewEv->
getType(),
2292 Builder.GetInsertPoint());
2307 "loop body must have a successor that is it self");
2309 ? Builder.getFalse()
2310 : Builder.getTrue();
2315 LLVM_DEBUG(
dbgs() <<
" Formed strlen idiom: " << *StrLenFunc <<
"\n");
2319 <<
"Transformed " << StrLenFunc->
getName() <<
" loop idiom";
2344 return Cond->getOperand(0);
2355 if (PhiX && PhiX->getParent() == LoopEntry &&
2356 (PhiX->getOperand(0) == DefX || PhiX->
getOperand(1) == DefX))
2423 if (DefX->
getOpcode() != Instruction::LShr)
2426 IntrinID = Intrinsic::ctlz;
2428 if (!Shft || !Shft->
isOne())
2442 if (Inst.
getOpcode() != Instruction::Add)
2494 Value *VarX1, *VarX0;
2497 DefX2 = CountInst =
nullptr;
2498 VarX1 = VarX0 =
nullptr;
2499 PhiX = CountPhi =
nullptr;
2512 if (!DefX2 || DefX2->
getOpcode() != Instruction::And)
2523 if (!SubOneOp || SubOneOp->
getOperand(0) != VarX1)
2529 (SubOneOp->
getOpcode() == Instruction::Add &&
2542 CountInst =
nullptr;
2545 if (Inst.
getOpcode() != Instruction::Add)
2549 if (!Inc || !Inc->
isOne())
2557 bool LiveOutLoop =
false;
2586 CntInst = CountInst;
2626 Value *VarX =
nullptr;
2640 if (!DefX || !DefX->
isShift())
2642 IntrinID = DefX->
getOpcode() == Instruction::Shl ? Intrinsic::cttz :
2645 if (!Shft || !Shft->
isOne())
2670 if (Inst.
getOpcode() != Instruction::Add)
2693bool LoopIdiomRecognize::isProfitableToInsertFFS(
Intrinsic::ID IntrinID,
2694 Value *InitX,
bool ZeroCheck,
2695 size_t CanonicalSize) {
2713bool LoopIdiomRecognize::insertFFSIfProfitable(
Intrinsic::ID IntrinID,
2717 bool IsCntPhiUsedOutsideLoop =
false;
2720 IsCntPhiUsedOutsideLoop =
true;
2723 bool IsCntInstUsedOutsideLoop =
false;
2726 IsCntInstUsedOutsideLoop =
true;
2731 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
2737 bool ZeroCheck =
false;
2746 if (!IsCntPhiUsedOutsideLoop) {
2764 size_t IdiomCanonicalSize = 6;
2765 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
2768 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
2770 IsCntPhiUsedOutsideLoop);
2777bool LoopIdiomRecognize::recognizeAndInsertFFS() {
2792 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2795bool LoopIdiomRecognize::recognizeShiftUntilLessThan() {
2806 APInt LoopThreshold;
2808 CntPhi, DefX, LoopThreshold))
2811 if (LoopThreshold == 2) {
2813 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2817 if (LoopThreshold != 4)
2835 APInt PreLoopThreshold;
2837 PreLoopThreshold != 2)
2840 bool ZeroCheck =
true;
2849 size_t IdiomCanonicalSize = 6;
2850 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
2854 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
2865bool LoopIdiomRecognize::recognizePopcount() {
2879 if (LoopBody->
size() >= 20) {
2907 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
2961void LoopIdiomRecognize::transformLoopToCountable(
2964 bool ZeroCheck,
bool IsCntPhiUsedOutsideLoop,
bool InsertSub) {
2967 Builder.SetCurrentDebugLocation(
DL);
2976 if (IsCntPhiUsedOutsideLoop) {
2977 if (DefX->
getOpcode() == Instruction::AShr)
2978 InitXNext = Builder.CreateAShr(InitX, 1);
2979 else if (DefX->
getOpcode() == Instruction::LShr)
2980 InitXNext = Builder.CreateLShr(InitX, 1);
2981 else if (DefX->
getOpcode() == Instruction::Shl)
2982 InitXNext = Builder.CreateShl(InitX, 1);
2990 Count = Builder.CreateSub(
2993 Count = Builder.CreateSub(
Count, ConstantInt::get(CountTy, 1));
2995 if (IsCntPhiUsedOutsideLoop)
2996 Count = Builder.CreateAdd(
Count, ConstantInt::get(CountTy, 1));
2998 NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->
getType());
3005 if (!InitConst || !InitConst->
isZero())
3006 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
3010 NewCount = Builder.CreateSub(CntInitVal, NewCount);
3028 Builder.SetInsertPoint(LbCond);
3030 TcPhi, ConstantInt::get(CountTy, 1),
"tcdec",
false,
true));
3039 LbCond->
setOperand(1, ConstantInt::get(CountTy, 0));
3043 if (IsCntPhiUsedOutsideLoop)
3053void LoopIdiomRecognize::transformLoopToPopcount(
BasicBlock *PreCondBB,
3066 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
3069 NewCount = PopCntZext =
3072 if (NewCount != PopCnt)
3081 if (!InitConst || !InitConst->
isZero()) {
3082 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
3094 Value *Opnd0 = PopCntZext;
3095 Value *Opnd1 = ConstantInt::get(PopCntZext->
getType(), 0);
3100 Builder.CreateICmp(PreCond->
getPredicate(), Opnd0, Opnd1));
3101 PreCondBr->setCondition(NewPreCond);
3135 Builder.SetInsertPoint(LbCond);
3137 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
3138 "tcdec",
false,
true));
3147 LbCond->
setOperand(1, ConstantInt::get(Ty, 0));
3168 template <
typename ITy>
bool match(ITy *V)
const {
3169 return L->isLoopInvariant(V) &&
SubPattern.match(V);
3174template <
typename Ty>
3205 " Performing shift-until-bittest idiom detection.\n");
3215 assert(LoopPreheaderBB &&
"There is always a loop preheader.");
3222 Value *CmpLHS, *CmpRHS;
3233 auto MatchVariableBitMask = [&]() {
3243 auto MatchDecomposableConstantBitMask = [&]() {
3245 CmpLHS, CmpRHS, Pred,
true,
3247 if (Res && Res->Mask.isPowerOf2()) {
3251 BitMask = ConstantInt::get(CurrX->
getType(), Res->Mask);
3252 BitPos = ConstantInt::get(CurrX->
getType(), Res->Mask.logBase2());
3258 if (!MatchVariableBitMask() && !MatchDecomposableConstantBitMask()) {
3265 if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {
3270 BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);
3275 "Expected BaseX to be available in the preheader!");
3286 "Should only get equality predicates here.");
3296 if (TrueBB != LoopHeaderBB) {
3355bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {
3356 bool MadeChange =
false;
3358 Value *
X, *BitMask, *BitPos, *XCurr;
3363 " shift-until-bittest idiom detection failed.\n");
3373 assert(LoopPreheaderBB &&
"There is always a loop preheader.");
3376 assert(SuccessorBB &&
"There is only a single successor.");
3382 Type *Ty =
X->getType();
3396 " Intrinsic is too costly, not beneficial\n");
3399 if (
TTI->getArithmeticInstrCost(Instruction::Shl, Ty,
CostKind) >
3411 std::optional<BasicBlock::iterator> InsertPt = std::nullopt;
3413 InsertPt = BitPosI->getInsertionPointAfterDef();
3421 return U.getUser() != BitPosFrozen;
3423 BitPos = BitPosFrozen;
3429 BitPos->
getName() +
".lowbitmask");
3431 Builder.CreateOr(LowBitMask, BitMask, BitPos->
getName() +
".mask");
3432 Value *XMasked = Builder.CreateAnd(
X, Mask,
X->getName() +
".masked");
3433 Value *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(
3434 IntrID, Ty, {XMasked, Builder.getTrue()},
3435 nullptr, XMasked->
getName() +
".numleadingzeros");
3436 Value *XMaskedNumActiveBits = Builder.CreateSub(
3438 XMasked->
getName() +
".numactivebits",
true,
3440 Value *XMaskedLeadingOnePos =
3442 XMasked->
getName() +
".leadingonepos",
false,
3445 Value *LoopBackedgeTakenCount = Builder.CreateSub(
3446 BitPos, XMaskedLeadingOnePos, CurLoop->
getName() +
".backedgetakencount",
3450 Value *LoopTripCount =
3451 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
3452 CurLoop->
getName() +
".tripcount",
true,
3459 Value *NewX = Builder.CreateShl(
X, LoopBackedgeTakenCount);
3462 I->copyIRFlags(XNext,
true);
3474 NewXNext = Builder.CreateShl(
X, LoopTripCount);
3479 NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));
3484 I->copyIRFlags(XNext,
true);
3495 Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->
begin());
3496 auto *
IV = Builder.CreatePHI(Ty, 2, CurLoop->
getName() +
".iv");
3502 Builder.CreateAdd(
IV, ConstantInt::get(Ty, 1),
IV->getName() +
".next",
3503 true, Bitwidth != 2);
3506 auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,
3507 CurLoop->
getName() +
".ivcheck");
3509 const bool HasBranchWeights =
3512 auto *BI = Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);
3513 if (HasBranchWeights) {
3515 std::swap(BranchWeights[0], BranchWeights[1]);
3525 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
3526 IV->addIncoming(IVNext, LoopHeaderBB);
3537 ++NumShiftUntilBitTest;
3573 const SCEV *&ExtraOffsetExpr,
3574 bool &InvertedCond) {
3576 " Performing shift-until-zero idiom detection.\n");
3589 assert(LoopPreheaderBB &&
"There is always a loop preheader.");
3600 !
match(ValShiftedIsZero,
3614 IntrinID = ValShifted->
getOpcode() == Instruction::Shl ? Intrinsic::cttz
3623 else if (
match(NBits,
3627 ExtraOffsetExpr = SE->
getSCEV(ExtraOffset);
3635 if (!IVPN || IVPN->getParent() != LoopHeaderBB) {
3640 Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);
3651 "Should only get equality predicates here.");
3662 if (FalseBB != LoopHeaderBB) {
3673 if (ValShifted->
getOpcode() == Instruction::AShr &&
3737bool LoopIdiomRecognize::recognizeShiftUntilZero() {
3738 bool MadeChange =
false;
3744 const SCEV *ExtraOffsetExpr;
3747 Start, Val, ExtraOffsetExpr, InvertedCond)) {
3749 " shift-until-zero idiom detection failed.\n");
3759 assert(LoopPreheaderBB &&
"There is always a loop preheader.");
3762 assert(SuccessorBB &&
"There is only a single successor.");
3765 Builder.SetCurrentDebugLocation(
IV->getDebugLoc());
3781 " Intrinsic is too costly, not beneficial\n");
3788 bool OffsetIsZero = ExtraOffsetExpr->
isZero();
3792 Value *ValNumLeadingZeros = Builder.CreateIntrinsic(
3793 IntrID, Ty, {Val, Builder.getFalse()},
3794 nullptr, Val->
getName() +
".numleadingzeros");
3795 Value *ValNumActiveBits = Builder.CreateSub(
3797 Val->
getName() +
".numactivebits",
true,
3801 Expander.setInsertPoint(&*Builder.GetInsertPoint());
3802 Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);
3804 Value *ValNumActiveBitsOffset = Builder.CreateAdd(
3805 ValNumActiveBits, ExtraOffset, ValNumActiveBits->
getName() +
".offset",
3806 OffsetIsZero,
true);
3807 Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},
3808 {ValNumActiveBitsOffset,
Start},
3809 nullptr,
"iv.final");
3812 IVFinal, Start, CurLoop->
getName() +
".backedgetakencount",
3813 OffsetIsZero,
true));
3817 Value *LoopTripCount =
3818 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
3819 CurLoop->
getName() +
".tripcount",
true,
3825 IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);
3830 Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->
begin());
3831 auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->
getName() +
".iv");
3836 Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() +
".next",
3837 true, Bitwidth != 2);
3840 auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,
3841 CurLoop->
getName() +
".ivcheck");
3842 auto *NewIVCheck = CIVCheck;
3844 NewIVCheck = Builder.CreateNot(CIVCheck);
3845 NewIVCheck->takeName(ValShiftedIsZero);
3849 auto *IVDePHId = Builder.CreateAdd(CIV, Start,
"",
false,
3851 IVDePHId->takeName(
IV);
3856 const bool HasBranchWeights =
3859 auto *BI = Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);
3860 if (HasBranchWeights) {
3862 std::swap(BranchWeights[0], BranchWeights[1]);
3870 CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
3871 CIV->addIncoming(CIVNext, LoopHeaderBB);
3879 IV->replaceAllUsesWith(IVDePHId);
3880 IV->eraseFromParent();
3889 ++NumShiftUntilZero;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
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")))
This file defines the DenseMap class.
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...
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)
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...
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
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)
static SymbolRef::Type getType(const Symbol *Sym)
static const uint32_t IV[8]
Class for arbitrary precision integers.
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
uint64_t getZExtValue() const
Get zero extended value.
bool sgt(const APInt &RHS) const
Signed greater than comparison.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
bool slt(const APInt &RHS) const
Signed less than comparison.
int64_t getSExtValue() const
Get sign extended value.
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.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
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
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI const_iterator getFirstNonPHIOrDbgOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a debug intrinsic,...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
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
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.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLE
signed less or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_ULT
unsigned less than
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Predicate getPredicate() const
Return the predicate for this instruction.
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.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
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...
const APInt & getValue() const
Return the constant as an APInt value reference.
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
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.
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.
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
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...
static InstructionCost getInvalid(CostType Val=0)
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
iterator_range< user_iterator > users()
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
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.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
This is an important class for using LLVM in a threaded context.
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.
Align getAlign() const
Return the alignment of the access that is being performed.
static LocationSize precise(uint64_t Value)
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
bool contains(const LoopT *L) const
Return true if the specified loop is contained within 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.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
ICmpInst * getLatchCmpInst() const
Get the latch condition instruction.
StringRef getName() const
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
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
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.
Encapsulates MemorySSA, including all data associated with memory accesses.
A Module instance is used to store all the information related to an LLVM module.
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.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
Helper to remove instructions inserted during SCEV expansion, unless they are marked as used.
This class uses information about analyze scalars to rewrite expressions in canonical form.
SCEVUse getOperand(unsigned i) const
This class represents an analyzed expression in the program.
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
static constexpr auto FlagNUW
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
A vector that has set insertion semantics.
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Value * getValueOperand()
Value * getPointerOperand()
Represent a constant reference to a string, i.e.
Provides information about what library functions are available for the current target.
unsigned getWCharSize(const Module &M) const
Returns the size of the wchar_t type in bytes.
bool has(LibFunc F) const
Tests whether a library function is available.
Triple - Helper class for working with autoconf configuration names.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
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)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
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...
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Value handle that is nullable, but tries to track the Value.
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
const ParentTy * getParent() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
OperandType
Operands are tagged with one of the values of this enum.
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)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
DiagnosticInfoOptimizationBase::Argument NV
DiagnosticInfoOptimizationBase::setExtraArgs setExtraArgs
bool isSimple(Instruction *I)
This is an optimization pass for GlobalISel generic memory operations.
static cl::opt< bool, true > DisableLIRPHashRecognize("disable-" DEBUG_TYPE "-hashrecognize", cl::desc("Proceed with loop idiom recognize pass, " "but do not do hash-recognize analysis."), cl::location(DisableLIRP::HashRecognize), cl::init(false), cl::ReallyHidden)
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
static cl::opt< bool, true > EnableLIRPWcslen("disable-loop-idiom-wcslen", cl::desc("Proceed with loop idiom recognize pass, " "enable conversion of loop(s) to wcslen."), cl::location(DisableLIRP::Wcslen), cl::init(false), cl::ReallyHidden)
static 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.
static cl::opt< bool, true > DisableLIRPStrlen("disable-loop-idiom-strlen", cl::desc("Proceed with loop idiom recognize pass, but do " "not convert loop(s) to strlen."), cl::location(DisableLIRP::Strlen), cl::init(false), cl::ReallyHidden)
@ Store
The extracted value is stored (ExtractElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
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
LLVM_ABI bool isLibFuncEmittable(const Module *M, const TargetLibraryInfo *TLI, LibFunc TheLibFunc)
Check whether the library function is available on target and also that it in the current Module is a...
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
auto dyn_cast_or_null(const Y &Val)
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.
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
static cl::opt< CRCStrategyKind > CRCStrategy(DEBUG_TYPE "-crc-strategy", cl::desc("Preferred strategy for optimizing CRC loops"), cl::init(CRCStrategyKind::Auto), cl::Hidden, cl::values(clEnumValN(CRCStrategyKind::Disable, "disable", "Do not optimize CRC loops"), clEnumValN(CRCStrategyKind::Auto, "auto", "Use costing to determine strategy"), clEnumValN(CRCStrategyKind::Table, "table", "Use a Sarwate table when possible"), clEnumValN(CRCStrategyKind::Clmul, "clmul", "Use carry-less multiplication when possible")))
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isModOrRefSet(const ModRefInfo MRI)
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...
LLVM_ABI Value * emitStrLen(Value *Ptr, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the strlen function to the builder, for the specified pointer.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
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.
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)
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.
@ Auto
Determine whether to use color based on the command line argument and the raw_ostream.
SCEVUseT< const SCEV * > SCEVUse
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
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...
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...
TargetTransformInfo & TTI
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
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)