37using namespace PatternMatch;
39#define DEBUG_TYPE "aggressive-instcombine"
41STATISTIC(NumAnyOrAllBitsSet,
"Number of any/all-bits-set patterns folded");
43 "Number of guarded rotates transformed into funnel shifts");
45 "Number of guarded funnel shifts transformed into funnel shifts");
46STATISTIC(NumPopCountRecognized,
"Number of popcount idioms recognized");
50 cl::desc(
"Max number of instructions to scan for aggressive instcombine."));
54 cl::desc(
"The maximum length of a constant string for a builtin string cmp "
55 "call eligible for inlining. The default value is 3."));
59 cl::desc(
"The maximum length of a constant string to "
60 "inline a memchr call."));
66 if (
I.getOpcode() != Instruction::PHI ||
I.getNumOperands() != 2)
80 unsigned Width = V->getType()->getScalarSizeInBits();
88 return Intrinsic::fshl;
97 return Intrinsic::fshr;
109 unsigned FunnelOp = 0, GuardOp = 1;
110 Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1);
111 Value *ShVal0, *ShVal1, *ShAmt;
114 (IID == Intrinsic::fshl && ShVal0 != P1) ||
115 (IID == Intrinsic::fshr && ShVal1 != P1)) {
118 (IID == Intrinsic::fshl && ShVal0 != P0) ||
119 (IID == Intrinsic::fshr && ShVal1 != P0))
121 assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
122 "Pattern must match funnel shift left or right");
130 BasicBlock *GuardBB = Phi.getIncomingBlock(GuardOp);
131 BasicBlock *FunnelBB = Phi.getIncomingBlock(FunnelOp);
146 if (ShVal0 == ShVal1)
149 ++NumGuardedFunnelShifts;
153 bool IsFshl = IID == Intrinsic::fshl;
154 if (ShVal0 != ShVal1) {
175 Phi.replaceAllUsesWith(
186 Value *Root =
nullptr;
189 bool FoundAnd1 =
false;
191 MaskOps(
unsigned BitWidth,
bool MatchAnds)
205 if (MOps.MatchAndChain) {
210 MOps.FoundAnd1 =
true;
224 const APInt *BitIndex =
nullptr;
230 MOps.Root = Candidate;
233 if (BitIndex && BitIndex->
uge(MOps.Mask.getBitWidth()))
237 MOps.Mask.setBit(BitIndex ? BitIndex->
getZExtValue() : 0);
238 return MOps.Root == Candidate;
252 bool MatchAllBitsSet;
254 MatchAllBitsSet =
true;
256 MatchAllBitsSet =
false;
260 MaskOps MOps(
I.getType()->getScalarSizeInBits(), MatchAllBitsSet);
261 if (MatchAllBitsSet) {
272 Constant *Mask = ConstantInt::get(
I.getType(), MOps.Mask);
277 I.replaceAllUsesWith(Zext);
278 ++NumAnyOrAllBitsSet;
294 if (
I.getOpcode() != Instruction::LShr)
297 Type *Ty =
I.getType();
303 if (!(Len <= 128 && Len > 8 && Len % 8 == 0))
312 Value *Op0 =
I.getOperand(0);
313 Value *Op1 =
I.getOperand(1);
329 Value *Root, *SubOp1;
331 const APInt *AndMask;
335 auto CheckAndMask = [&]() {
336 if (*AndMask == Mask55)
344 APInt NeededMask = Mask55 & ~*AndMask;
350 if (CheckAndMask()) {
353 I.replaceAllUsesWith(
355 ++NumPopCountRecognized;
377 const APInt *MinC, *MaxC;
387 if (!(*MinC + 1).isPowerOf2() || -*MaxC != *MinC + 1)
390 Type *IntTy =
I.getType();
391 Type *FpTy = In->getType();
394 if (
auto *VecTy = dyn_cast<VectorType>(IntTy))
395 SatTy = VectorType::get(SatTy, VecTy->getElementCount());
416 if (SatCost >= MinMaxCost)
422 I.replaceAllUsesWith(Builder.
CreateSExt(Sat, IntTy));
438 Type *Ty = Call->getType();
439 Value *Arg = Call->getArgOperand(0);
441 (Call->hasNoNaNs() ||
443 Arg,
SimplifyQuery(Call->getDataLayout(), &TLI, &DT, &AC, Call)))) {
447 Call->replaceAllUsesWith(NewSqrt);
451 Call->eraseFromParent();
463 unsigned InputBits,
const APInt &GEPIdxFactor,
465 for (
unsigned Idx = 0;
Idx < InputBits;
Idx++) {
469 if (!
C ||
C->getValue() !=
Idx)
545 if (!
GEP || !
GEP->hasNoUnsignedSignedWrap())
552 unsigned BW =
DL.getIndexTypeSizeInBits(
GEP->getType());
553 APInt ModOffset(BW, 0);
555 if (!
GEP->collectOffset(
DL, BW, VarOffsets, ModOffset) ||
556 VarOffsets.
size() != 1 || ModOffset != 0)
558 auto [GepIdx, GEPScale] = VarOffsets.
front();
561 const APInt *MulConst, *ShiftConst, *AndCst =
nullptr;
574 if (InputBits != 16 && InputBits != 32 && InputBits != 64 && InputBits != 128)
577 if (!GEPScale.isIntN(InputBits) ||
580 InputBits, GEPScale.zextOrTrunc(InputBits),
DL))
585 bool DefinedForZero = ZeroTableElem->
getZExtValue() == InputBits;
590 auto Cttz =
B.CreateIntrinsic(Intrinsic::cttz, {XType}, {X1, BoolConst});
591 Value *ZExtOrTrunc =
nullptr;
593 if (DefinedForZero) {
594 ZExtOrTrunc =
B.CreateZExtOrTrunc(Cttz, AccessType);
598 auto Cmp =
B.CreateICmpEQ(X1, ConstantInt::get(XType, 0));
599 auto Select =
B.CreateSelect(Cmp,
B.CreateZExt(ZeroTableElem, XType), Cttz);
604 ZExtOrTrunc =
B.CreateZExtOrTrunc(
Select, AccessType);
651 LI1 = dyn_cast<LoadInst>(L1);
653 LoadInst *LI2 = dyn_cast<LoadInst>(L2);
665 bool IsBigEndian =
DL.isBigEndian();
683 if (Load1Ptr != Load2Ptr)
687 if (!
DL.typeSizeEqualsStoreSize(LI1->
getType()) ||
688 !
DL.typeSizeEqualsStoreSize(LI2->
getType()))
694 if (!Start->comesBefore(
End)) {
701 unsigned NumScanned = 0;
713 if (Offset2.
slt(Offset1)) {
737 uint64_t ShiftDiff = IsBigEndian ? LoadSize2 : LoadSize1;
740 if ((ShAmt2 - ShAmt1) != ShiftDiff || (Offset2 - Offset1) != PrevSize)
750 LOps.
LoadSize = LoadSize1 + LoadSize2;
769 if (isa<VectorType>(
I.getType()))
785 unsigned AS = LI1->getPointerAddressSpace();
788 AS, LI1->getAlign(), &
Fast);
789 if (!Allowed || !
Fast)
793 Value *Load1Ptr = LI1->getPointerOperand();
803 LI1->isVolatile(),
"");
809 Value *NewOp = NewLoad;
818 I.replaceAllUsesWith(NewOp);
843 auto *Store = dyn_cast<StoreInst>(&
I);
844 if (!Store || !Store->isSimple())
847 Value *StoredVal = Store->getValueOperand();
849 if (!StoredTy->
isIntegerTy() || !
DL.typeSizeEqualsStoreSize(StoredTy))
858 Value *
Ptr = Store->getPointerOperand();
859 APInt PtrOffset(
DL.getIndexTypeSizeInBits(
Ptr->getType()), 0);
860 Value *PtrBase =
Ptr->stripAndAccumulateConstantOffsets(
861 DL, PtrOffset,
true);
862 return {{PtrBase, PtrOffset, Val, ValOffset, ValWidth, Store}};
868 if (Parts.
size() < 2)
879 First.Store->getPointerAddressSpace(),
887 if (
First.ValOffset != 0)
891 Val,
First.Store->getPointerOperand(),
First.Store->getAlign());
895 AATags = AATags.
concat(Part.Store->getAAMetadata());
896 Store->setAAMetadata(AATags);
900 Part.Store->eraseFromParent();
907 if (Parts.
size() < 2)
914 bool Changed =
false;
916 int64_t LastEndOffsetFromFirst = 0;
919 APInt PtrOffsetFromFirst = Part.PtrOffset -
First->PtrOffset;
920 int64_t ValOffsetFromFirst = Part.ValOffset -
First->ValOffset;
921 if (PtrOffsetFromFirst * 8 != ValOffsetFromFirst ||
922 LastEndOffsetFromFirst != ValOffsetFromFirst) {
924 LastEndOffsetFromFirst,
DL,
TTI);
926 LastEndOffsetFromFirst = Part.ValWidth;
930 LastEndOffsetFromFirst = ValOffsetFromFirst + Part.ValWidth;
934 LastEndOffsetFromFirst,
DL,
TTI);
941 if (
DL.isBigEndian())
946 bool MadeChange =
false;
949 if (Parts.
empty() || Part->isCompatibleWith(Parts[0])) {
964 (
I.mayReadOrWriteMemory() &&
980 auto *
I = dyn_cast<Instruction>(V);
981 if (!
I ||
I->getOpcode() != Instruction::Or || !
I->hasOneUse())
988 Value *Op0 =
I->getOperand(0);
995 Value *Op1 =
I->getOperand(1);
1002 if (Op0 !=
I->getOperand(0) || Op1 !=
I->getOperand(1))
1018 if (
auto OpI = dyn_cast<Instruction>(Op0))
1019 if (OpI->getOpcode() == Instruction::Or)
1026 I.replaceAllUsesWith(Builder.
CreateICmp(Pred, Res,
I.getOperand(1)));
1035static std::pair<APInt, APInt>
1037 unsigned BW =
DL.getIndexTypeSizeInBits(PtrOp->
getType());
1038 std::optional<APInt> Stride;
1039 APInt ModOffset(BW, 0);
1042 while (
auto *
GEP = dyn_cast<GEPOperator>(PtrOp)) {
1044 if (!
GEP->collectOffset(
DL, BW, VarOffsets, ModOffset))
1047 for (
auto [V, Scale] : VarOffsets) {
1049 if (!
GEP->hasNoUnsignedSignedWrap())
1058 PtrOp =
GEP->getPointerOperand();
1063 if (!isa<GlobalVariable>(PtrOp) || !Stride)
1068 ModOffset = ModOffset.
srem(*Stride);
1070 ModOffset += *Stride;
1072 return {*Stride, ModOffset};
1078 auto *LI = dyn_cast<LoadInst>(&
I);
1079 if (!LI || LI->isVolatile())
1084 auto *PtrOp = LI->getPointerOperand();
1086 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1091 uint64_t GVSize =
DL.getTypeAllocSize(
C->getType());
1092 if (!GVSize || 4096 < GVSize)
1095 Type *LoadTy = LI->getType();
1096 unsigned BW =
DL.getIndexTypeSizeInBits(PtrOp->getType());
1102 if (
auto LA = LI->getAlign();
1103 LA <= GV->
getAlign().valueOrOne() && Stride.getZExtValue() < LA.value()) {
1104 ConstOffset =
APInt(BW, 0);
1105 Stride =
APInt(BW, LA.value());
1112 unsigned E = GVSize -
DL.getTypeStoreSize(LoadTy);
1113 for (; ConstOffset.getZExtValue() <= E; ConstOffset += Stride)
1117 I.replaceAllUsesWith(Ca);
1123class StrNCmpInliner {
1129 bool optimizeStrNCmp();
1170bool StrNCmpInliner::optimizeStrNCmp() {
1177 Value *Str1P = CI->getArgOperand(0);
1178 Value *Str2P = CI->getArgOperand(1);
1186 if (HasStr1 == HasStr2)
1191 Value *StrP = HasStr1 ? Str2P : Str1P;
1193 size_t Idx = Str.find(
'\0');
1195 if (Func == LibFunc_strncmp) {
1196 if (
auto *ConstInt = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
1197 N = std::min(
N, ConstInt->getZExtValue());
1207 bool CanBeNull =
false, CanBeFreed =
false;
1210 inlineCompare(StrP, Str,
N, HasStr1);
1250 auto &Ctx = CI->getContext();
1258 B.SetCurrentDebugLocation(CI->getDebugLoc());
1270 cast<BranchInst>(BBCI->
getTerminator())->setSuccessor(0, BBSubs[0]);
1272 B.SetInsertPoint(BBNE);
1278 B.SetInsertPoint(BBSubs[i]);
1280 B.CreateZExt(
B.CreateLoad(
B.getInt8Ty(),
1281 B.CreateInBoundsPtrAdd(
Base,
B.getInt64(i))),
1284 ConstantInt::get(CI->getType(),
static_cast<unsigned char>(RHS[i]));
1285 Value *
Sub = Swapped ?
B.CreateSub(VR, VL) :
B.CreateSub(VL, VR);
1287 B.CreateCondBr(
B.CreateICmpNE(
Sub, ConstantInt::get(CI->getType(), 0)),
1288 BBNE, BBSubs[i + 1]);
1292 Phi->addIncoming(
Sub, BBSubs[i]);
1295 CI->replaceAllUsesWith(Phi);
1296 CI->eraseFromParent();
1300 Updates.
push_back({DominatorTree::Insert, BBCI, BBSubs[0]});
1303 Updates.
push_back({DominatorTree::Insert, BBSubs[i], BBSubs[i + 1]});
1304 Updates.
push_back({DominatorTree::Insert, BBSubs[i], BBNE});
1306 Updates.
push_back({DominatorTree::Insert, BBNE, BBTail});
1307 Updates.
push_back({DominatorTree::Delete, BBCI, BBTail});
1308 DTU->applyUpdates(Updates);
1315 if (isa<Constant>(Call->getArgOperand(1)))
1324 if (
auto *ConstInt = dyn_cast<ConstantInt>(Call->getArgOperand(2))) {
1325 uint64_t Val = ConstInt->getZExtValue();
1343 IRB.
CreateTrunc(Call->getArgOperand(1), ByteTy), BBNext,
N);
1344 Type *IndexTy =
DL.getIndexType(Call->getType());
1348 Call->getContext(),
"memchr.success", BB->
getParent(), BBNext);
1354 Updates.
push_back({DominatorTree::Insert, BBSuccess, BBNext});
1358 ConstantInt *CaseVal = ConstantInt::get(ByteTy, Str[
I]);
1359 if (!Cases.
insert(CaseVal).second)
1364 SI->addCase(CaseVal, BBCase);
1366 IndexPHI->
addIncoming(ConstantInt::get(IndexTy,
I), BBCase);
1369 Updates.
push_back({DominatorTree::Insert, BB, BBCase});
1370 Updates.
push_back({DominatorTree::Insert, BBCase, BBSuccess});
1377 PHI->addIncoming(FirstOccursLocation, BBSuccess);
1379 Call->replaceAllUsesWith(
PHI);
1380 Call->eraseFromParent();
1391 bool &MadeCFGChange) {
1393 auto *CI = dyn_cast<CallInst>(&
I);
1394 if (!CI || CI->isNoBuiltin())
1397 Function *CalledFunc = CI->getCalledFunction();
1413 case LibFunc_strcmp:
1414 case LibFunc_strncmp:
1415 if (StrNCmpInliner(CI, LF, &DTU,
DL).optimizeStrNCmp()) {
1416 MadeCFGChange =
true;
1420 case LibFunc_memchr:
1422 MadeCFGChange =
true;
1438 bool MadeChange =
false;
1483 bool MadeChange =
false;
1486 MadeChange |= TIC.
run(
F);
1498 bool MadeCFGChange =
false;
1499 if (!
runImpl(
F, AC,
TTI, TLI, DT, AA, MadeCFGChange)) {
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool tryToRecognizePopCount(Instruction &I)
static bool foldSqrt(CallInst *Call, LibFunc Func, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT)
Try to replace a mathlib call to sqrt with the LLVM intrinsic.
static bool foldAnyOrAllBitsSet(Instruction &I)
Match patterns that correspond to "any-bits-set" and "all-bits-set".
static cl::opt< unsigned > MemChrInlineThreshold("memchr-inline-threshold", cl::init(3), cl::Hidden, cl::desc("The maximum length of a constant string to " "inline a memchr call."))
static bool tryToFPToSat(Instruction &I, TargetTransformInfo &TTI)
Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and C2 saturate the value of t...
static cl::opt< unsigned > StrNCmpInlineThreshold("strncmp-inline-threshold", cl::init(3), cl::Hidden, cl::desc("The maximum length of a constant string for a builtin string cmp " "call eligible for inlining. The default value is 3."))
static bool matchAndOrChain(Value *V, MaskOps &MOps)
This is a recursive helper for foldAnyOrAllBitsSet() that walks through a chain of 'and' or 'or' inst...
static bool foldMemChr(CallInst *Call, DomTreeUpdater *DTU, const DataLayout &DL)
Convert memchr with a small constant string into a switch.
static Value * optimizeShiftInOrChain(Value *V, IRBuilder<> &Builder)
Combine away instructions providing they are still equivalent when compared against 0.
static bool foldConsecutiveLoads(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA, const DominatorTree &DT)
static bool runImpl(Function &F, AssumptionCache &AC, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, DominatorTree &DT, AliasAnalysis &AA, bool &MadeCFGChange)
This is the entry point for all transforms.
static bool foldGuardedFunnelShift(Instruction &I, const DominatorTree &DT)
Match a pattern for a bitwise funnel/rotate operation that partially guards against undefined behavio...
static bool tryToRecognizeTableBasedCttz(Instruction &I, const DataLayout &DL)
static bool mergePartStores(SmallVectorImpl< PartStore > &Parts, const DataLayout &DL, TargetTransformInfo &TTI)
static bool mergeConsecutivePartStores(ArrayRef< PartStore > Parts, unsigned Width, const DataLayout &DL, TargetTransformInfo &TTI)
static cl::opt< unsigned > MaxInstrsToScan("aggressive-instcombine-max-scan-instrs", cl::init(64), cl::Hidden, cl::desc("Max number of instructions to scan for aggressive instcombine."))
static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL, AliasAnalysis &AA)
static bool foldICmpOrChain(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA, const DominatorTree &DT)
static bool isCTTZTable(Constant *Table, const APInt &Mul, const APInt &Shift, const APInt &AndMask, Type *AccessTy, unsigned InputBits, const APInt &GEPIdxFactor, const DataLayout &DL)
static std::optional< PartStore > matchPartStore(Instruction &I, const DataLayout &DL)
static bool foldConsecutiveStores(BasicBlock &BB, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA)
static std::pair< APInt, APInt > getStrideAndModOffsetOfGEP(Value *PtrOp, const DataLayout &DL)
static bool foldPatternedLoads(Instruction &I, const DataLayout &DL)
If C is a constant patterned array and all valid loaded results for given alignment are same to a con...
static bool foldLibCalls(Instruction &I, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, const DataLayout &DL, bool &MadeCFGChange)
static bool foldUnusualPatterns(Function &F, DominatorTree &DT, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AliasAnalysis &AA, AssumptionCache &AC, bool &MadeCFGChange)
This is the entry point for folds that could be implemented in regular InstCombine,...
AggressiveInstCombiner - Combine expression patterns to form expressions with fewer,...
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
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
std::optional< std::vector< StOtherPiece > > Other
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool runImpl(Function &F, const TargetLowering &TLI)
This is the interface for a simple mod/ref and alias analysis over globals.
static MaybeAlign getAlign(Value *Ptr)
static Instruction * matchFunnelShift(Instruction &Or, InstCombinerImpl &IC)
Match UB-safe variants of the funnel shift intrinsic.
static const MCExpr * MaskShift(const MCExpr *Val, uint32_t Mask, uint32_t Shift, MCContext &Ctx)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
A manager for alias analyses.
A private abstract base class describing the concept of an individual alias analysis implementation.
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.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
uint64_t getZExtValue() const
Get zero extended value.
bool isNegative() const
Determine sign of this APInt.
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
APInt shl(unsigned shiftAmt) const
Left-shift function.
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
bool slt(const APInt &RHS) const
Signed less than comparison.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A container for analyses that lazily runs them and caches their results.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
front - Get the first element.
size_t size() const
size - Get the array size.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Function * getParent() const
Return the enclosing method, or null if none.
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...
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Represents analyses that only rely on functions' control flow.
This class represents a function call, abstracting a target machine's calling convention.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
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.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool isEquality() const
Return true if this predicate is either EQ or NE.
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateFreeze(Value *V, const Twine &Name="")
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata 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.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
std::pair< KeyT, ValueT > & front()
Representation for a specific memory location.
MemoryLocation getWithNewSize(LocationSize NewSize) const
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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...
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.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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.
StringRef - Represent a constant reference to a string, i.e.
static constexpr size_t npos
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
bool run(Function &F)
Perform TruncInst pattern optimization on given function.
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 TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
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.
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool &CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
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.
const ParentTy * getParent() const
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
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.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ C
The default llvm calling convention, compatible with C.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
ShiftLike_match< LHS, Instruction::LShr > m_LShrOrSelf(const LHS &L, uint64_t &R)
Matches lshr L, ConstShAmt or L itself (R will be set to zero in this case).
match_combine_or< CastInst_match< OpTy, CastInst >, OpTy > m_CastOrSelf(const OpTy &Op)
Matches any cast or self. Used to ignore casts.
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.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
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.
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
ShiftLike_match< LHS, Instruction::Shl > m_ShlOrSelf(const LHS &L, uint64_t &R)
Matches shl L, ConstShAmt or L itself (R will be set to zero in this case).
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
specific_bbval m_SpecificBB(BasicBlock *BB)
Match a specific basic block value.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(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.
CastInst_match< OpTy, FPToSIInst > m_FPToSI(const OpTy &Op)
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
initializer< Ty > init(const Ty &Val)
NodeAddr< PhiNode * > Phi
NodeAddr< FuncNode * > Func
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
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...
LLVM_ABI bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
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...
auto reverse(ContainerTy &&C)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
bool isModSet(const ModRefInfo MRI)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isModOrRefSet(const ModRefInfo MRI)
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ Sub
Subtraction of integers.
constexpr unsigned BitWidth
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This is used by foldLoadsRecursive() to capture a Root Load node which is of type or(load,...
ValWidth bits starting at ValOffset of Val stored at PtrBase+PtrOffset.
bool operator<(const PartStore &Other) const
bool isCompatibleWith(const PartStore &Other) const
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_ABI AAMDNodes concat(const AAMDNodes &Other) const
Determine the best AAMDNodes after concatenating two different locations together.
A MapVector that performs no allocations if smaller than a certain size.