96#define DEBUG_TYPE "loop-idiom"
98STATISTIC(NumMemSet,
"Number of memset's formed from loop stores");
99STATISTIC(NumMemCpy,
"Number of memcpy's formed from loop load+stores");
100STATISTIC(NumMemMove,
"Number of memmove's formed from loop load+stores");
102 NumShiftUntilBitTest,
103 "Number of uncountable loops recognized as 'shift until bitttest' idiom");
105 "Number of uncountable loops recognized as 'shift until zero' idiom");
110 cl::desc(
"Options to disable Loop Idiom Recognize Pass."),
117 cl::desc(
"Proceed with loop idiom recognize pass, but do "
118 "not convert loop(s) to memset."),
125 cl::desc(
"Proceed with loop idiom recognize pass, but do "
126 "not convert loop(s) to memcpy."),
131 "use-lir-code-size-heurs",
132 cl::desc(
"Use loop idiom recognition code size heuristics when compiling"
138class LoopIdiomRecognize {
139 Loop *CurLoop =
nullptr;
148 bool ApplyCodeSizeHeuristics;
149 std::unique_ptr<MemorySSAUpdater> MSSAU;
158 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI),
TTI(
TTI),
DL(
DL), ORE(ORE) {
160 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
163 bool runOnLoop(
Loop *L);
169 StoreListMap StoreRefsForMemset;
170 StoreListMap StoreRefsForMemsetPattern;
171 StoreList StoreRefsForMemcpy;
173 bool HasMemsetPattern;
177 enum LegalStoreKind {
182 UnorderedAtomicMemcpy,
190 bool runOnCountableLoop();
195 LegalStoreKind isLegalStore(
StoreInst *SI);
196 enum class ForMemset {
No,
Yes };
200 template <
typename MemInst>
201 bool processLoopMemIntrinsic(
203 bool (LoopIdiomRecognize::*Processor)(MemInst *,
const SCEV *),
204 const SCEV *BECount);
208 bool processLoopStridedStore(
Value *DestPtr,
const SCEV *StoreSizeSCEV,
213 bool IsNegStride,
bool IsLoopMemset =
false);
214 bool processLoopStoreOfLoopLoad(
StoreInst *SI,
const SCEV *BECount);
215 bool processLoopStoreOfLoopLoad(
Value *DestPtr,
Value *SourcePtr,
221 const SCEV *BECount);
222 bool avoidLIRForMultiBlockLoop(
bool IsMemset =
false,
223 bool IsLoopMemset =
false);
229 bool runOnNoncountableLoop();
231 bool recognizePopcount();
235 bool ZeroCheck,
size_t CanonicalSize);
239 bool recognizeAndInsertFFS();
240 bool recognizeShiftUntilLessThan();
245 bool IsCntPhiUsedOutsideLoop,
246 bool InsertSub =
false);
248 bool recognizeShiftUntilBitTest();
249 bool recognizeShiftUntilZero();
261 const auto *
DL = &L.getHeader()->getDataLayout();
268 LoopIdiomRecognize LIR(&AR.
AA, &AR.
DT, &AR.
LI, &AR.
SE, &AR.
TLI, &AR.
TTI,
270 if (!LIR.runOnLoop(&L))
281 I->eraseFromParent();
290bool LoopIdiomRecognize::runOnLoop(
Loop *L) {
294 if (!
L->getLoopPreheader())
299 if (
Name ==
"memset" ||
Name ==
"memcpy")
303 ApplyCodeSizeHeuristics =
306 HasMemset = TLI->
has(LibFunc_memset);
307 HasMemsetPattern = TLI->
has(LibFunc_memset_pattern16);
308 HasMemcpy = TLI->
has(LibFunc_memcpy);
310 if (HasMemset || HasMemsetPattern || HasMemcpy)
312 return runOnCountableLoop();
314 return runOnNoncountableLoop();
317bool LoopIdiomRecognize::runOnCountableLoop() {
319 assert(!isa<SCEVCouldNotCompute>(BECount) &&
320 "runOnCountableLoop() called on a loop without a predictable"
321 "backedge-taken count");
325 if (
const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
326 if (BECst->getAPInt() == 0)
344 bool MadeChange =
false;
352 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
376 if (!
C || isa<ConstantExpr>(
C))
385 if (
DL->isBigEndian())
401 unsigned ArraySize = 16 /
Size;
406LoopIdiomRecognize::LegalStoreKind
407LoopIdiomRecognize::isLegalStore(
StoreInst *SI) {
409 if (
SI->isVolatile())
410 return LegalStoreKind::None;
412 if (!
SI->isUnordered())
413 return LegalStoreKind::None;
416 if (
SI->getMetadata(LLVMContext::MD_nontemporal))
417 return LegalStoreKind::None;
419 Value *StoredVal =
SI->getValueOperand();
420 Value *StorePtr =
SI->getPointerOperand();
425 return LegalStoreKind::None;
433 return LegalStoreKind::None;
439 dyn_cast<SCEVAddRecExpr>(SE->
getSCEV(StorePtr));
441 return LegalStoreKind::None;
444 if (!isa<SCEVConstant>(StoreEv->
getOperand(1)))
445 return LegalStoreKind::None;
456 bool UnorderedAtomic =
SI->isUnordered() && !
SI->isSimple();
465 return LegalStoreKind::Memset;
472 return LegalStoreKind::MemsetPattern;
480 unsigned StoreSize =
DL->getTypeStoreSize(
SI->getValueOperand()->getType());
481 if (StoreSize != Stride && StoreSize != -Stride)
482 return LegalStoreKind::None;
485 LoadInst *LI = dyn_cast<LoadInst>(
SI->getValueOperand());
489 return LegalStoreKind::None;
492 return LegalStoreKind::None;
500 return LegalStoreKind::None;
504 return LegalStoreKind::None;
507 UnorderedAtomic = UnorderedAtomic || LI->
isAtomic();
508 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
509 : LegalStoreKind::Memcpy;
512 return LegalStoreKind::None;
515void LoopIdiomRecognize::collectStores(
BasicBlock *BB) {
516 StoreRefsForMemset.clear();
517 StoreRefsForMemsetPattern.clear();
518 StoreRefsForMemcpy.clear();
525 switch (isLegalStore(SI)) {
526 case LegalStoreKind::None:
529 case LegalStoreKind::Memset: {
532 StoreRefsForMemset[
Ptr].push_back(SI);
534 case LegalStoreKind::MemsetPattern: {
537 StoreRefsForMemsetPattern[
Ptr].push_back(SI);
539 case LegalStoreKind::Memcpy:
540 case LegalStoreKind::UnorderedAtomicMemcpy:
541 StoreRefsForMemcpy.push_back(SI);
544 assert(
false &&
"unhandled return value");
553bool LoopIdiomRecognize::runOnLoopBlock(
563 bool MadeChange =
false;
570 for (
auto &SL : StoreRefsForMemset)
571 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
573 for (
auto &SL : StoreRefsForMemsetPattern)
574 MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
577 for (
auto &SI : StoreRefsForMemcpy)
578 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
580 MadeChange |= processLoopMemIntrinsic<MemCpyInst>(
581 BB, &LoopIdiomRecognize::processLoopMemCpy, BECount);
582 MadeChange |= processLoopMemIntrinsic<MemSetInst>(
583 BB, &LoopIdiomRecognize::processLoopMemSet, BECount);
590 const SCEV *BECount, ForMemset For) {
598 for (
unsigned i = 0, e = SL.
size(); i < e; ++i) {
599 assert(SL[i]->
isSimple() &&
"Expected only non-volatile stores.");
601 Value *FirstStoredVal = SL[i]->getValueOperand();
602 Value *FirstStorePtr = SL[i]->getPointerOperand();
604 cast<SCEVAddRecExpr>(SE->
getSCEV(FirstStorePtr));
606 unsigned FirstStoreSize =
DL->getTypeStoreSize(SL[i]->getValueOperand()->
getType());
609 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
614 Value *FirstSplatValue =
nullptr;
615 Constant *FirstPatternValue =
nullptr;
617 if (For == ForMemset::Yes)
622 assert((FirstSplatValue || FirstPatternValue) &&
623 "Expected either splat value or pattern value.");
631 for (j = i + 1;
j <
e; ++
j)
633 for (j = i;
j > 0; --
j)
636 for (
auto &k : IndexQueue) {
637 assert(SL[k]->
isSimple() &&
"Expected only non-volatile stores.");
638 Value *SecondStorePtr = SL[
k]->getPointerOperand();
640 cast<SCEVAddRecExpr>(SE->
getSCEV(SecondStorePtr));
643 if (FirstStride != SecondStride)
646 Value *SecondStoredVal = SL[
k]->getValueOperand();
647 Value *SecondSplatValue =
nullptr;
648 Constant *SecondPatternValue =
nullptr;
650 if (For == ForMemset::Yes)
655 assert((SecondSplatValue || SecondPatternValue) &&
656 "Expected either splat value or pattern value.");
659 if (For == ForMemset::Yes) {
660 if (isa<UndefValue>(FirstSplatValue))
661 FirstSplatValue = SecondSplatValue;
662 if (FirstSplatValue != SecondSplatValue)
665 if (isa<UndefValue>(FirstPatternValue))
666 FirstPatternValue = SecondPatternValue;
667 if (FirstPatternValue != SecondPatternValue)
672 ConsecutiveChain[SL[i]] = SL[
k];
681 bool Changed =
false;
692 unsigned StoreSize = 0;
695 while (Tails.
count(
I) || Heads.count(
I)) {
696 if (TransformedStores.
count(
I))
700 StoreSize +=
DL->getTypeStoreSize(
I->getValueOperand()->getType());
702 I = ConsecutiveChain[
I];
712 if (StoreSize != Stride && StoreSize != -Stride)
715 bool IsNegStride = StoreSize == -Stride;
719 if (processLoopStridedStore(StorePtr, StoreSizeSCEV,
721 HeadStore, AdjacentStores, StoreEv, BECount,
723 TransformedStores.
insert(AdjacentStores.
begin(), AdjacentStores.
end());
733template <
typename MemInst>
734bool LoopIdiomRecognize::processLoopMemIntrinsic(
736 bool (LoopIdiomRecognize::*Processor)(MemInst *,
const SCEV *),
737 const SCEV *BECount) {
738 bool MadeChange =
false;
742 if (MemInst *
MI = dyn_cast<MemInst>(Inst)) {
744 if (!(this->*Processor)(
MI, BECount))
758bool LoopIdiomRecognize::processLoopMemCpy(
MemCpyInst *MCI,
759 const SCEV *BECount) {
770 if (!Dest || !Source)
785 if ((SizeInBytes >> 32) != 0)
791 dyn_cast<SCEVConstant>(StoreEv->
getOperand(1));
793 dyn_cast<SCEVConstant>(LoadEv->
getOperand(1));
794 if (!ConstStoreStride || !ConstLoadStride)
803 if (SizeInBytes != StoreStrideValue && SizeInBytes != -StoreStrideValue) {
806 <<
ore::NV(
"Inst",
"memcpy") <<
" in "
808 <<
" function will not be hoisted: "
809 <<
ore::NV(
"Reason",
"memcpy size is not equal to stride");
814 int64_t StoreStrideInt = StoreStrideValue.
getSExtValue();
817 if (StoreStrideInt != LoadStrideInt)
820 return processLoopStoreOfLoopLoad(
827bool LoopIdiomRecognize::processLoopMemSet(
MemSetInst *MSI,
828 const SCEV *BECount) {
843 if (!Ev || Ev->
getLoop() != CurLoop)
852 if (!PointerStrideSCEV || !MemsetSizeSCEV)
855 bool IsNegStride =
false;
856 const bool IsConstantSize = isa<ConstantInt>(MSI->
getLength());
858 if (IsConstantSize) {
869 if (SizeInBytes != Stride && SizeInBytes != -Stride)
872 IsNegStride = SizeInBytes == -Stride;
880 if (
Pointer->getType()->getPointerAddressSpace() != 0) {
893 const SCEV *PositiveStrideSCEV =
896 LLVM_DEBUG(
dbgs() <<
" MemsetSizeSCEV: " << *MemsetSizeSCEV <<
"\n"
897 <<
" PositiveStrideSCEV: " << *PositiveStrideSCEV
900 if (PositiveStrideSCEV != MemsetSizeSCEV) {
903 const SCEV *FoldedPositiveStride =
905 const SCEV *FoldedMemsetSize =
909 <<
" FoldedMemsetSize: " << *FoldedMemsetSize <<
"\n"
910 <<
" FoldedPositiveStride: " << *FoldedPositiveStride
913 if (FoldedPositiveStride != FoldedMemsetSize) {
930 BECount, IsNegStride,
true);
938 const SCEV *BECount,
const SCEV *StoreSizeSCEV,
948 const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount);
949 const SCEVConstant *ConstSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
950 if (BECst && ConstSize) {
954 if (BEInt && SizeInt)
976 Type *IntPtr,
const SCEV *StoreSizeSCEV,
979 if (!StoreSizeSCEV->
isOne()) {
994 const SCEV *StoreSizeSCEV,
Loop *CurLoop,
996 const SCEV *TripCountSCEV =
1005bool LoopIdiomRecognize::processLoopStridedStore(
1009 const SCEV *BECount,
bool IsNegStride,
bool IsLoopMemset) {
1017 assert((SplatValue || PatternValue) &&
1018 "Expected either splat value or pattern value.");
1029 Type *DestInt8PtrTy = Builder.getPtrTy(DestAS);
1032 bool Changed =
false;
1040 if (!Expander.isSafeToExpand(Start))
1049 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->
getTerminator());
1061 StoreSizeSCEV, *AA, Stores))
1064 if (avoidLIRForMultiBlockLoop(
true, IsLoopMemset))
1069 const SCEV *NumBytesS =
1070 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop,
DL, SE);
1074 if (!Expander.isSafeToExpand(NumBytesS))
1078 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->
getTerminator());
1085 AATags = AATags.
merge(
Store->getAAMetadata());
1086 if (
auto CI = dyn_cast<ConstantInt>(NumBytes))
1087 AATags = AATags.
extendTo(CI->getZExtValue());
1093 NewCall = Builder.CreateMemSet(
1094 BasePtr, SplatValue, NumBytes,
MaybeAlign(StoreAlignment),
1099 Type *Int8PtrTy = DestInt8PtrTy;
1101 StringRef FuncName =
"memset_pattern16";
1103 Builder.getVoidTy(), Int8PtrTy, Int8PtrTy, IntIdxTy);
1110 PatternValue,
".memset_pattern");
1113 Value *PatternPtr = GV;
1114 NewCall = Builder.CreateCall(MSP, {
BasePtr, PatternPtr, NumBytes});
1130 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1132 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc),
true);
1136 <<
" from store to: " << *Ev <<
" at: " << *TheStore
1142 R <<
"Transformed loop-strided store in "
1144 <<
" function into a call to "
1147 if (!Stores.empty())
1149 for (
auto *
I : Stores) {
1150 R <<
ore::NV(
"FromBlock",
I->getParent()->getName())
1158 for (
auto *
I : Stores) {
1160 MSSAU->removeMemoryAccess(
I,
true);
1164 MSSAU->getMemorySSA()->verifyMemorySSA();
1166 ExpCleaner.markResultUsed();
1173bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
StoreInst *SI,
1174 const SCEV *BECount) {
1175 assert(
SI->isUnordered() &&
"Expected only non-volatile non-ordered stores.");
1177 Value *StorePtr =
SI->getPointerOperand();
1179 unsigned StoreSize =
DL->getTypeStoreSize(
SI->getValueOperand()->getType());
1182 LoadInst *LI = cast<LoadInst>(
SI->getValueOperand());
1192 return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSizeSCEV,
1194 StoreEv, LoadEv, BECount);
1198class MemmoveVerifier {
1200 explicit MemmoveVerifier(
const Value &LoadBasePtr,
const Value &StoreBasePtr,
1203 LoadBasePtr.stripPointerCasts(), LoadOff,
DL)),
1205 StoreBasePtr.stripPointerCasts(), StoreOff,
DL)),
1206 IsSameObject(BP1 == BP2) {}
1208 bool loadAndStoreMayFormMemmove(
unsigned StoreSize,
bool IsNegStride,
1210 bool IsMemCpy)
const {
1214 if ((!IsNegStride && LoadOff <= StoreOff) ||
1215 (IsNegStride && LoadOff >= StoreOff))
1221 DL.getTypeSizeInBits(TheLoad.
getType()).getFixedValue() / 8;
1222 if (BP1 != BP2 || LoadSize != int64_t(StoreSize))
1224 if ((!IsNegStride && LoadOff < StoreOff + int64_t(StoreSize)) ||
1225 (IsNegStride && LoadOff + LoadSize > StoreOff))
1233 int64_t LoadOff = 0;
1234 int64_t StoreOff = 0;
1239 const bool IsSameObject;
1243bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
1252 if (isa<MemCpyInlineInst>(TheStore))
1264 bool Changed =
false;
1270 const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1273 assert(ConstStoreSize &&
"store size is expected to be a constant");
1276 bool IsNegStride = StoreSize == -Stride;
1289 Value *StoreBasePtr = Expander.expandCodeFor(
1290 StrStart, Builder.getPtrTy(StrAS), Preheader->
getTerminator());
1302 IgnoredInsts.
insert(TheStore);
1304 bool IsMemCpy = isa<MemCpyInst>(TheStore);
1305 const StringRef InstRemark = IsMemCpy ?
"memcpy" :
"load and store";
1307 bool LoopAccessStore =
1309 StoreSizeSCEV, *AA, IgnoredInsts);
1310 if (LoopAccessStore) {
1316 IgnoredInsts.
insert(TheLoad);
1318 BECount, StoreSizeSCEV, *AA, IgnoredInsts)) {
1322 <<
ore::NV(
"Inst", InstRemark) <<
" in "
1324 <<
" function will not be hoisted: "
1325 <<
ore::NV(
"Reason",
"The loop may access store location");
1329 IgnoredInsts.
erase(TheLoad);
1342 Value *LoadBasePtr = Expander.expandCodeFor(LdStart, Builder.getPtrTy(LdAS),
1347 MemmoveVerifier
Verifier(*LoadBasePtr, *StoreBasePtr, *
DL);
1348 if (IsMemCpy && !
Verifier.IsSameObject)
1349 IgnoredInsts.
erase(TheStore);
1351 StoreSizeSCEV, *AA, IgnoredInsts)) {
1354 <<
ore::NV(
"Inst", InstRemark) <<
" in "
1356 <<
" function will not be hoisted: "
1357 <<
ore::NV(
"Reason",
"The loop may access load location");
1362 bool UseMemMove = IsMemCpy ?
Verifier.IsSameObject : LoopAccessStore;
1364 if (!
Verifier.loadAndStoreMayFormMemmove(StoreSize, IsNegStride, *TheLoad,
1368 if (avoidLIRForMultiBlockLoop())
1373 const SCEV *NumBytesS =
1374 getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop,
DL, SE);
1377 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->
getTerminator());
1381 AATags = AATags.
merge(StoreAATags);
1382 if (
auto CI = dyn_cast<ConstantInt>(NumBytes))
1383 AATags = AATags.
extendTo(CI->getZExtValue());
1393 NewCall = Builder.CreateMemMove(
1394 StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign, NumBytes,
1398 Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign,
1399 NumBytes,
false, AATags.
TBAA,
1407 assert((StoreAlign && LoadAlign) &&
1408 "Expect unordered load/store to have align.");
1409 if (*StoreAlign < StoreSize || *LoadAlign < StoreSize)
1422 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1423 StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, StoreSize,
1429 MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1431 MSSAU->insertDef(cast<MemoryDef>(NewMemAcc),
true);
1435 <<
" from load ptr=" << *LoadEv <<
" at: " << *TheLoad
1437 <<
" from store ptr=" << *StoreEv <<
" at: " << *TheStore
1443 <<
"Formed a call to "
1445 <<
"() intrinsic from " <<
ore::NV(
"Inst", InstRemark)
1456 MSSAU->removeMemoryAccess(TheStore,
true);
1459 MSSAU->getMemorySSA()->verifyMemorySSA();
1464 ExpCleaner.markResultUsed();
1471bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(
bool IsMemset,
1472 bool IsLoopMemset) {
1473 if (ApplyCodeSizeHeuristics && CurLoop->
getNumBlocks() > 1) {
1474 if (CurLoop->
isOutermost() && (!IsMemset || !IsLoopMemset)) {
1476 <<
" : LIR " << (IsMemset ?
"Memset" :
"Memcpy")
1477 <<
" avoided: multi-block top-level loop\n");
1485bool LoopIdiomRecognize::runOnNoncountableLoop() {
1488 <<
"] Noncountable Loop %"
1491 return recognizePopcount() || recognizeAndInsertFFS() ||
1492 recognizeShiftUntilBitTest() || recognizeShiftUntilZero() ||
1493 recognizeShiftUntilLessThan();
1503 bool JmpOnZero =
false) {
1512 if (!CmpZero || !CmpZero->
isZero())
1523 return Cond->getOperand(0);
1550 return Cond->getOperand(0);
1560 auto *PhiX = dyn_cast<PHINode>(VarX);
1561 if (PhiX && PhiX->getParent() == LoopEntry &&
1562 (PhiX->getOperand(0) == DefX || PhiX->
getOperand(1) == DefX))
1608 dyn_cast<BranchInst>(LoopEntry->
getTerminator()), LoopEntry,
1610 DefX = dyn_cast<Instruction>(
T);
1615 if (!DefX || !isa<PHINode>(DefX))
1618 PHINode *VarPhi = cast<PHINode>(DefX);
1628 if (DefX->
getOpcode() != Instruction::LShr)
1631 IntrinID = Intrinsic::ctlz;
1633 if (!Shft || !Shft->
isOne())
1647 if (Inst.
getOpcode() != Instruction::Add)
1699 Value *VarX1, *VarX0;
1702 DefX2 = CountInst =
nullptr;
1703 VarX1 = VarX0 =
nullptr;
1704 PhiX = CountPhi =
nullptr;
1710 dyn_cast<BranchInst>(LoopEntry->
getTerminator()), LoopEntry))
1711 DefX2 = dyn_cast<Instruction>(
T);
1718 if (!DefX2 || DefX2->
getOpcode() != Instruction::And)
1723 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->
getOperand(0))))
1727 SubOneOp = dyn_cast<BinaryOperator>(DefX2->
getOperand(1));
1729 if (!SubOneOp || SubOneOp->
getOperand(0) != VarX1)
1735 (SubOneOp->
getOpcode() == Instruction::Add &&
1748 CountInst =
nullptr;
1751 if (Inst.
getOpcode() != Instruction::Add)
1755 if (!Inc || !Inc->
isOne())
1763 bool LiveOutLoop =
false;
1765 if ((cast<Instruction>(U))->
getParent() != LoopEntry) {
1785 auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->
getTerminator());
1790 CntInst = CountInst;
1830 Value *VarX =
nullptr;
1839 dyn_cast<BranchInst>(LoopEntry->
getTerminator()), LoopEntry))
1840 DefX = dyn_cast<Instruction>(
T);
1845 if (!DefX || !DefX->
isShift())
1847 IntrinID = DefX->
getOpcode() == Instruction::Shl ? Intrinsic::cttz :
1850 if (!Shft || !Shft->
isOne())
1875 if (Inst.
getOpcode() != Instruction::Add)
1898bool LoopIdiomRecognize::isProfitableToInsertFFS(
Intrinsic::ID IntrinID,
1899 Value *InitX,
bool ZeroCheck,
1900 size_t CanonicalSize) {
1907 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());
1921bool LoopIdiomRecognize::insertFFSIfProfitable(
Intrinsic::ID IntrinID,
1925 bool IsCntPhiUsedOutsideLoop =
false;
1927 if (!CurLoop->
contains(cast<Instruction>(U))) {
1928 IsCntPhiUsedOutsideLoop =
true;
1931 bool IsCntInstUsedOutsideLoop =
false;
1933 if (!CurLoop->
contains(cast<Instruction>(U))) {
1934 IsCntInstUsedOutsideLoop =
true;
1939 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1945 bool ZeroCheck =
false;
1954 if (!IsCntPhiUsedOutsideLoop) {
1958 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1973 size_t IdiomCanonicalSize = 6;
1974 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
1977 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
1979 IsCntPhiUsedOutsideLoop);
1986bool LoopIdiomRecognize::recognizeAndInsertFFS() {
2001 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2004bool LoopIdiomRecognize::recognizeShiftUntilLessThan() {
2015 APInt LoopThreshold;
2017 CntPhi, DefX, LoopThreshold))
2020 if (LoopThreshold == 2) {
2022 return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);
2026 if (LoopThreshold != 4)
2031 if (!CurLoop->
contains(cast<Instruction>(U)))
2040 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
2044 APInt PreLoopThreshold;
2046 PreLoopThreshold != 2)
2049 bool ZeroCheck =
true;
2058 size_t IdiomCanonicalSize = 6;
2059 if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))
2063 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
2074bool LoopIdiomRecognize::recognizePopcount() {
2088 if (LoopBody->
size() >= 20) {
2098 if (!EntryBI || EntryBI->isConditional())
2106 auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
2107 if (!PreCondBI || PreCondBI->isUnconditional())
2116 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
2122 Value *Ops[] = {Val};
2178void LoopIdiomRecognize::transformLoopToCountable(
2181 bool ZeroCheck,
bool IsCntPhiUsedOutsideLoop,
bool InsertSub) {
2186 Builder.SetCurrentDebugLocation(
DL);
2195 if (IsCntPhiUsedOutsideLoop) {
2196 if (DefX->
getOpcode() == Instruction::AShr)
2197 InitXNext = Builder.CreateAShr(InitX, 1);
2198 else if (DefX->
getOpcode() == Instruction::LShr)
2199 InitXNext = Builder.CreateLShr(InitX, 1);
2200 else if (DefX->
getOpcode() == Instruction::Shl)
2201 InitXNext = Builder.CreateShl(InitX, 1);
2209 Count = Builder.CreateSub(
2212 Count = Builder.CreateSub(Count, ConstantInt::get(CountTy, 1));
2213 Value *NewCount = Count;
2214 if (IsCntPhiUsedOutsideLoop)
2215 Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1));
2217 NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->
getType());
2220 if (cast<ConstantInt>(CntInst->
getOperand(1))->isOne()) {
2223 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
2224 if (!InitConst || !InitConst->
isZero())
2225 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
2229 NewCount = Builder.CreateSub(CntInitVal, NewCount);
2242 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
2247 Builder.SetInsertPoint(LbCond);
2248 Instruction *TcDec = cast<Instruction>(Builder.CreateSub(
2249 TcPhi, ConstantInt::get(CountTy, 1),
"tcdec",
false,
true));
2258 LbCond->
setOperand(1, ConstantInt::get(CountTy, 0));
2262 if (IsCntPhiUsedOutsideLoop)
2272void LoopIdiomRecognize::transformLoopToPopcount(
BasicBlock *PreCondBB,
2276 auto *PreCondBr = cast<BranchInst>(PreCondBB->
getTerminator());
2285 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
2288 NewCount = PopCntZext =
2289 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->
getType()));
2291 if (NewCount != PopCnt)
2292 (cast<Instruction>(NewCount))->setDebugLoc(
DL);
2299 ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
2300 if (!InitConst || !InitConst->
isZero()) {
2301 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
2302 (cast<Instruction>(NewCount))->setDebugLoc(
DL);
2311 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
2313 Value *Opnd0 = PopCntZext;
2314 Value *Opnd1 = ConstantInt::get(PopCntZext->
getType(), 0);
2318 ICmpInst *NewPreCond = cast<ICmpInst>(
2319 Builder.CreateICmp(PreCond->
getPredicate(), Opnd0, Opnd1));
2320 PreCondBr->setCondition(NewPreCond);
2348 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
2354 Builder.SetInsertPoint(LbCond);
2356 Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
2357 "tcdec",
false,
true));
2366 LbCond->
setOperand(1, ConstantInt::get(Ty, 0));
2385 : SubPattern(SP), L(L) {}
2387 template <
typename ITy>
bool match(ITy *V) {
2388 return L->isLoopInvariant(V) && SubPattern.match(V);
2393template <
typename Ty>
2424 " Performing shift-until-bittest idiom detection.\n");
2434 assert(LoopPreheaderBB &&
"There is always a loop preheader.");
2436 using namespace PatternMatch;
2441 Value *CmpLHS, *CmpRHS;
2452 auto MatchVariableBitMask = [&]() {
2461 auto MatchConstantBitMask = [&]() {
2467 auto MatchDecomposableConstantBitMask = [&]() {
2471 (BitMask = ConstantInt::get(CurrX->
getType(), Mask)) &&
2472 (BitPos = ConstantInt::get(CurrX->
getType(), Mask.logBase2()));
2475 if (!MatchVariableBitMask() && !MatchConstantBitMask() &&
2476 !MatchDecomposableConstantBitMask()) {
2482 auto *CurrXPN = dyn_cast<PHINode>(CurrX);
2483 if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {
2488 BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);
2490 dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB));
2493 "Expected BaseX to be avaliable in the preheader!");
2504 "Should only get equality predicates here.");
2514 if (TrueBB != LoopHeaderBB) {
2573bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {
2574 bool MadeChange =
false;
2576 Value *
X, *BitMask, *BitPos, *XCurr;
2581 " shift-until-bittest idiom detection failed.\n");
2591 assert(LoopPreheaderBB &&
"There is always a loop preheader.");
2594 assert(SuccessorBB &&
"There is only a single successor.");
2597 Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->
getDebugLoc());
2600 Type *Ty =
X->getType();
2614 " Intrinsic is too costly, not beneficial\n");
2629 std::optional<BasicBlock::iterator> InsertPt = std::nullopt;
2630 if (
auto *BitPosI = dyn_cast<Instruction>(BitPos))
2631 InsertPt = BitPosI->getInsertionPointAfterDef();
2639 return U.getUser() != BitPosFrozen;
2641 BitPos = BitPosFrozen;
2647 BitPos->
getName() +
".lowbitmask");
2649 Builder.CreateOr(LowBitMask, BitMask, BitPos->
getName() +
".mask");
2650 Value *XMasked = Builder.CreateAnd(
X, Mask,
X->getName() +
".masked");
2651 CallInst *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(
2652 IntrID, Ty, {XMasked, Builder.getTrue()},
2653 nullptr, XMasked->
getName() +
".numleadingzeros");
2654 Value *XMaskedNumActiveBits = Builder.CreateSub(
2656 XMasked->
getName() +
".numactivebits",
true,
2658 Value *XMaskedLeadingOnePos =
2660 XMasked->
getName() +
".leadingonepos",
false,
2663 Value *LoopBackedgeTakenCount = Builder.CreateSub(
2664 BitPos, XMaskedLeadingOnePos, CurLoop->
getName() +
".backedgetakencount",
2668 Value *LoopTripCount =
2669 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
2670 CurLoop->
getName() +
".tripcount",
true,
2677 Value *NewX = Builder.CreateShl(
X, LoopBackedgeTakenCount);
2679 if (
auto *
I = dyn_cast<Instruction>(NewX))
2680 I->copyIRFlags(XNext,
true);
2692 NewXNext = Builder.CreateShl(
X, LoopTripCount);
2697 NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));
2701 if (
auto *
I = dyn_cast<Instruction>(NewXNext))
2702 I->copyIRFlags(XNext,
true);
2713 Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->
begin());
2714 auto *
IV = Builder.CreatePHI(Ty, 2, CurLoop->
getName() +
".iv");
2720 Builder.CreateAdd(
IV, ConstantInt::get(Ty, 1),
IV->getName() +
".next",
2721 true, Bitwidth != 2);
2724 auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,
2725 CurLoop->
getName() +
".ivcheck");
2726 Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);
2730 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
2731 IV->addIncoming(IVNext, LoopHeaderBB);
2742 ++NumShiftUntilBitTest;
2778 const SCEV *&ExtraOffsetExpr,
2779 bool &InvertedCond) {
2781 " Performing shift-until-zero idiom detection.\n");
2794 assert(LoopPreheaderBB &&
"There is always a loop preheader.");
2796 using namespace PatternMatch;
2805 !
match(ValShiftedIsZero,
2819 IntrinID = ValShifted->
getOpcode() == Instruction::Shl ? Intrinsic::cttz
2828 else if (
match(NBits,
2832 ExtraOffsetExpr = SE->
getSCEV(ExtraOffset);
2839 auto *IVPN = dyn_cast<PHINode>(
IV);
2840 if (!IVPN || IVPN->getParent() != LoopHeaderBB) {
2845 Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);
2846 IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB));
2856 "Should only get equality predicates here.");
2867 if (FalseBB != LoopHeaderBB) {
2878 if (ValShifted->
getOpcode() == Instruction::AShr &&
2942bool LoopIdiomRecognize::recognizeShiftUntilZero() {
2943 bool MadeChange =
false;
2949 const SCEV *ExtraOffsetExpr;
2952 Start, Val, ExtraOffsetExpr, InvertedCond)) {
2954 " shift-until-zero idiom detection failed.\n");
2964 assert(LoopPreheaderBB &&
"There is always a loop preheader.");
2967 assert(SuccessorBB &&
"There is only a single successor.");
2970 Builder.SetCurrentDebugLocation(
IV->getDebugLoc());
2986 " Intrinsic is too costly, not beneficial\n");
2993 bool OffsetIsZero =
false;
2994 if (
auto *ExtraOffsetExprC = dyn_cast<SCEVConstant>(ExtraOffsetExpr))
2995 OffsetIsZero = ExtraOffsetExprC->isZero();
2999 CallInst *ValNumLeadingZeros = Builder.CreateIntrinsic(
3000 IntrID, Ty, {Val, Builder.getFalse()},
3001 nullptr, Val->
getName() +
".numleadingzeros");
3002 Value *ValNumActiveBits = Builder.CreateSub(
3004 Val->
getName() +
".numactivebits",
true,
3008 Expander.setInsertPoint(&*Builder.GetInsertPoint());
3009 Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);
3011 Value *ValNumActiveBitsOffset = Builder.CreateAdd(
3012 ValNumActiveBits, ExtraOffset, ValNumActiveBits->
getName() +
".offset",
3013 OffsetIsZero,
true);
3014 Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},
3015 {ValNumActiveBitsOffset, Start},
3016 nullptr,
"iv.final");
3018 auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub(
3019 IVFinal, Start, CurLoop->
getName() +
".backedgetakencount",
3020 OffsetIsZero,
true));
3024 Value *LoopTripCount =
3025 Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
3026 CurLoop->
getName() +
".tripcount",
true,
3032 IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);
3037 Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->
begin());
3038 auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->
getName() +
".iv");
3043 Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() +
".next",
3044 true, Bitwidth != 2);
3047 auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,
3048 CurLoop->
getName() +
".ivcheck");
3049 auto *NewIVCheck = CIVCheck;
3051 NewIVCheck = Builder.CreateNot(CIVCheck);
3052 NewIVCheck->takeName(ValShiftedIsZero);
3056 auto *IVDePHId = Builder.CreateAdd(CIV, Start,
"",
false,
3058 IVDePHId->takeName(
IV);
3062 Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);
3066 CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
3067 CIV->addIncoming(CIVNext, LoopHeaderBB);
3075 IV->replaceAllUsesWith(IVDePHId);
3076 IV->eraseFromParent();
3085 ++NumShiftUntilZero;
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< 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< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
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...
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
static Value * matchCondition(BranchInst *BI, BasicBlock *LoopEntry, bool JmpOnZero=false)
Check if the given conditional branch is based on the comparison between a variable and zero,...
static PHINode * getRecurrenceVar(Value *VarX, Instruction *DefX, BasicBlock *LoopEntry)
static cl::opt< bool, true > DisableLIRPMemset("disable-" DEBUG_TYPE "-memset", cl::desc("Proceed with loop idiom recognize pass, but do " "not convert loop(s) to memset."), cl::location(DisableLIRP::Memset), cl::init(false), cl::ReallyHidden)
static cl::opt< bool > 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 CallInst * createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL, bool ZeroCheck, Intrinsic::ID IID)
static bool detectShiftUntilLessThanIdiom(Loop *CurLoop, const DataLayout &DL, Intrinsic::ID &IntrinID, Value *&InitX, Instruction *&CntInst, PHINode *&CntPhi, Instruction *&DefX, APInt &Threshold)
Return true if the idiom is detected in the loop.
static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX, Value *&BitMask, Value *&BitPos, Value *&CurrX, Instruction *&NextX)
Return true if the idiom is detected in the loop.
static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, Instruction *&CntInst, PHINode *&CntPhi, Value *&Var)
Return true iff the idiom is detected in the loop.
static Constant * getMemSetPatternValue(Value *V, const DataLayout *DL)
getMemSetPatternValue - If a strided store of the specified value is safe to turn into a memset_patte...
static cl::opt< bool, true > DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy", cl::desc("Proceed with loop idiom recognize pass, but do " "not convert loop(s) to memcpy."), cl::location(DisableLIRP::Memcpy), cl::init(false), cl::ReallyHidden)
static CallInst * createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL)
static const SCEV * getNumBytes(const SCEV *BECount, Type *IntPtr, const SCEV *StoreSizeSCEV, Loop *CurLoop, const DataLayout *DL, ScalarEvolution *SE)
Compute the number of bytes as a SCEV from the backedge taken count.
static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL, Intrinsic::ID &IntrinID, Value *&InitX, Instruction *&CntInst, PHINode *&CntPhi, Instruction *&DefX)
Return true if the idiom is detected in the loop.
static const SCEV * getStartForNegStride(const SCEV *Start, const SCEV *BECount, Type *IntPtr, const SCEV *StoreSizeSCEV, ScalarEvolution *SE)
static APInt getStoreStride(const SCEVAddRecExpr *StoreEv)
static Value * matchShiftULTCondition(BranchInst *BI, BasicBlock *LoopEntry, APInt &Threshold)
Check if the given conditional branch is based on an unsigned less-than comparison between a variable...
match_LoopInvariant< Ty > m_LoopInvariant(const Ty &M, const Loop *L)
Matches if the value is loop-invariant.
static cl::opt< bool, true > DisableLIRPAll("disable-" DEBUG_TYPE "-all", cl::desc("Options to disable Loop Idiom Recognize Pass."), cl::location(DisableLIRP::All), cl::init(false), cl::ReallyHidden)
static void deleteDeadInstruction(Instruction *I)
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
This file implements a map that provides insertion order iteration.
This file provides utility analysis objects describing memory locations.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
Module.h This file contains the declarations for the Module class.
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
This header defines various interfaces for pass management in LLVM.
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isSimple(Instruction *I)
verify safepoint Safepoint IR Verifier
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
static const uint32_t IV[8]
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
Class for arbitrary precision integers.
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
unsigned getBitWidth() const
Return the number of bits in the APInt.
int64_t getSExtValue() const
Get sign extended value.
A container for analyses that lazily runs them and caches their results.
static 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< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug(bool SkipPseudoOp=true) const
Return a const iterator range over the instructions in the block, skipping any debug instructions.
InstListType::const_iterator getFirstNonPHIIt() const
Iterator returning form of getFirstNonPHI.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const Instruction & front() const
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
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 if the block is well formed or null if the block is not well forme...
BinaryOps getOpcode() const
Conditional or Unconditional Branch instruction.
bool isConditional() const
BasicBlock * getSuccessor(unsigned i) const
Value * getCondition() const
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
This class represents a function call, abstracting a target machine's calling convention.
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
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.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getExactLogBase2(Constant *C)
If C is a scalar/fixed width vector of known powers of 2, then this function returns a new scalar/fix...
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.
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 ConstantInt * getBool(LLVMContext &Context, bool V)
This is an important base class in LLVM.
static Constant * getAllOnesValue(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
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 ...
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
void setUnnamedAddr(UnnamedAddr Val)
Module * getParent()
Get the module that this global value is contained inside of...
@ PrivateLinkage
Like Internal, but omit from symbol table.
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.
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
BasicBlock * GetInsertBlock() const
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const Function * getFunction() const
Return the function this instruction belongs to.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
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.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
An instruction for reading from memory.
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 in this loop.
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
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
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.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
StringRef getName() const
This class implements a map that also provides access to all stored values in a deterministic order.
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
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 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.
const SCEV * getStart() const
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
const Loop * getLoop() const
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
Helper to remove instructions inserted during SCEV expansion, unless they are marked as used.
This class uses information about analyze scalars to rewrite expressions in canonical form.
const SCEV * getOperand(unsigned i) const
This class represents an analyzed expression in the program.
bool isOne() const
Return true if the expression is a constant one.
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
The main scalar evolution driver.
bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
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.
const SCEV * getConstant(ConstantInt *V)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
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...
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
const SCEV * getMulExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
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.
A vector that has set insertion semantics.
size_type count(const key_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 ...
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.
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()
StringRef - Represent a constant reference to a string, i.e.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
The instances of the Type class are immutable: once they are created, they are never changed.
unsigned getIntegerBitWidth() const
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
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.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
void replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
LLVMContext & getContext() const
All values hold a context through their type.
StringRef getName() const
Return a constant reference to the value's name.
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
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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.
@ C
The default llvm calling convention, compatible with C.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
bool match(Val *V, const Pattern &P)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
DiagnosticInfoOptimizationBase::setExtraArgs setExtraArgs
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
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.
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.
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool inferNonMandatoryLibFuncAttrs(Module *M, StringRef Name, const TargetLibraryInfo &TLI)
Analyze the name and prototype of the given function and set any applicable attributes.
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...
bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isModOrRefSet(const ModRefInfo MRI)
FunctionCallee getOrInsertLibFunc(Module *M, const TargetLibraryInfo &TLI, LibFunc TheLibFunc, FunctionType *T, AttributeList AttributeList)
Calls getOrInsertFunction() and then makes sure to add mandatory argument attributes.
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.
bool VerifyMemorySSA
Enables verification of MemorySSA.
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.
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.
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
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...
bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred, Value *&X, APInt &Mask, bool LookThroughTrunc=true)
Decompose an icmp into the form ((X & Mask) pred 0) if possible.
bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
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...
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
MDNode * Scope
The tag for alias scope specification (used with noalias).
MDNode * TBAA
The tag for type-based alias analysis.
AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
MDNode * NoAlias
The tag specifying the noalias scope.
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...
This struct is a compact representation of a valid (non-zero power of two) alignment.
static bool Memset
When true, Memset is disabled.
static bool All
When true, the entire pass is disabled.
static bool Memcpy
When true, Memcpy is disabled.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
TargetTransformInfo & TTI
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Match loop-invariant value.
match_LoopInvariant(const SubPattern_t &SP, const Loop *L)