192class ConstantOffsetExtractor {
201 static Value *Extract(
const Use &Idx, User *&UserTreeRoot,
207 static std::optional<APInt>
Find(
const Use &Idx);
212 std::optional<unsigned> LHS;
213 std::optional<unsigned> RHS;
219 void pushCast(CastInst *Cast) {
221 Casts.push_back(Cast);
224 void popCast() { Casts.pop_back(); }
226 bool hasSignExtension()
const {
237 bool hasExtensions()
const {
258 : IP(InsertionPt), DL(InsertionPt->getDataLayout()), SQ(DL) {}
268 std::optional<APInt>
find(
Value *V,
const Use *Idx, CastState &Casts);
271 std::optional<APInt> findInOperands(RewriteNode &Node, CastState &Casts);
280 Value *rebuildWithoutConstOffset(
unsigned NodeIndex, CastState &Casts);
282 Value *rebuildWithoutConstOffset() {
284 return rebuildWithoutConstOffset(UserTree.size() - 1, Casts);
290 Value *applyCasts(
Value *V,
const CastState &Casts);
298 bool canTraceInto(
const CastState &Casts, BinaryOperator *BO,
const Use *Idx);
319 std::optional<APInt> extractDisjointBitsFromXor(RewriteNode &Node);
326 static constexpr unsigned MaxVisitedNodes = 64;
329 unsigned NumVisited = 0;
334 const DataLayout &DL;
335 const SimplifyQuery SQ;
341class SeparateConstOffsetFromGEPLegacyPass :
public FunctionPass {
345 SeparateConstOffsetFromGEPLegacyPass(
bool LowerGEP =
false)
346 : FunctionPass(ID), LowerGEP(LowerGEP) {
351 void getAnalysisUsage(AnalysisUsage &AU)
const override {
368class SeparateConstOffsetFromGEP {
370 SeparateConstOffsetFromGEP(
371 DominatorTree *DT, LoopInfo *LI, TargetLibraryInfo *TLI,
372 function_ref<TargetTransformInfo &(
Function &)> GetTTI,
bool LowerGEP)
373 : DT(DT), LI(LI), TLI(TLI), GetTTI(GetTTI), LowerGEP(LowerGEP) {}
379 using ExprKey = std::pair<Value *, Value *>;
382 static ExprKey createNormalizedCommutablePair(
Value *
A,
Value *
B) {
390 bool splitGEP(GetElementPtrInst *
GEP);
395 bool reorderGEP(GetElementPtrInst *
GEP, TargetTransformInfo &
TTI);
404 void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
405 const APInt &AccumulativeByteOffset);
413 APInt accumulateByteOffset(GetElementPtrInst *
GEP,
bool &NeedsExtraction,
414 bool &SignedOverflow);
431 bool canonicalizeArrayIndicesToIndexSize(GetElementPtrInst *
GEP);
445 bool reuniteExts(Instruction *
I);
449 ExprKey
Key, Instruction *Dominatee,
450 DenseMap<ExprKey, SmallVector<Instruction *, 2>> &DominatingExprs);
455 bool hasMoreThanOneUseInLoop(
Value *v,
Loop *L);
458 void swapGEPOperand(GetElementPtrInst *
First, GetElementPtrInst *Second);
461 bool isLegalToSwapOperand(GetElementPtrInst *
First, GetElementPtrInst *Second,
464 const DataLayout *DL =
nullptr;
465 DominatorTree *DT =
nullptr;
467 TargetLibraryInfo *TLI;
469 function_ref<TargetTransformInfo &(
Function &)> GetTTI;
475 DenseMap<ExprKey, SmallVector<Instruction *, 2>> DominatingAdds;
476 DenseMap<ExprKey, SmallVector<Instruction *, 2>> DominatingSubs;
481char SeparateConstOffsetFromGEPLegacyPass::ID = 0;
484 SeparateConstOffsetFromGEPLegacyPass,
"separate-const-offset-from-gep",
485 "Split GEPs to a variadic base and a constant offset for better CSE",
false,
493 SeparateConstOffsetFromGEPLegacyPass,
"separate-const-offset-from-gep",
494 "Split GEPs to a variadic base and a constant offset for better CSE",
false,
498 return new SeparateConstOffsetFromGEPLegacyPass(LowerGEP);
538 if (!
GEP->isInBounds())
541 const Value *Ptr =
GEP->getPointerOperand();
555 unsigned N =
Add->getType()->getIntegerBitWidth();
558 TypeSize ElemSize = GTI.getSequentialElementStride(
DL);
576 if (Idx->getOperandNo() == 1 &&
Base &&
600 if (
auto AllocSize = AI->getAllocationSize(
DL))
601 if (!AllocSize->isScalable())
602 ObjSize = AllocSize->getFixedValue();
604 TypeSize GVSize =
DL.getTypeAllocSize(GV->getValueType());
608 if (ObjSize > 0 &&
APInt(128, ObjSize).ult(Threshold))
614bool ConstantOffsetExtractor::canTraceInto(
const CastState &Casts,
616 bool SignExtended = Casts.hasSignExtension();
617 bool ZeroExtended = Casts.hasZeroExtension();
626 if (BO->
getOpcode() != Instruction::Add &&
639 if (BO->
getOpcode() == Instruction::Add && !ZeroExtended && Idx) {
644 GEP->hasNoUnsignedWrap())
658std::optional<APInt> ConstantOffsetExtractor::findInOperands(RewriteNode &Node,
665 Node.LHS = UserTree.size() - 1;
670 Node.RHS = UserTree.size() - 1;
676std::optional<APInt> ConstantOffsetExtractor::find(
Value *V,
const Use *Idx,
684 if (NumVisited++ >= MaxVisitedNodes)
692 RewriteNode
Node{
U, std::nullopt, std::nullopt};
693 std::optional<APInt> ConstantOffset;
699 ConstantOffset = Casts.apply(CI->getValue());
700 Node.V = ConstantInt::getNullValue(CI->getType());
703 if (canTraceInto(Casts, BO, Idx))
704 ConstantOffset = findInOperands(Node, Casts);
705 else if (BO->
getOpcode() == Instruction::Xor) {
706 ConstantOffset = extractDisjointBitsFromXor(Node);
708 *ConstantOffset = Casts.apply(*ConstantOffset);
713 ConstantOffset =
find(
U->getOperand(0), Idx, Casts);
716 Node.LHS = UserTree.size() - 1;
720 UserTree.push_back(Node);
721 return ConstantOffset;
724Value *ConstantOffsetExtractor::applyCasts(
Value *V,
const CastState &Casts) {
752Value *ConstantOffsetExtractor::rebuildWithoutConstOffset(
unsigned NodeIndex,
754 const RewriteNode &
Node = UserTree[NodeIndex];
756 return applyCasts(
Node.V, Casts);
759 Casts.pushCast(Cast);
767 : applyCasts(BO->getOperand(0), Casts);
769 : applyCasts(BO->getOperand(1), Casts);
778 BinaryOperator::BinaryOps NewOp = BO->
getOpcode();
793 NewOp = Instruction::Add;
802ConstantOffsetExtractor::extractDisjointBitsFromXor(RewriteNode &Node) {
804 assert(XorInst && XorInst->getOpcode() == Instruction::Xor &&
805 "Expected XOR instruction");
808 ConstantInt *XorConstantOp;
814 const APInt &ConstantValue = XorConstantOp->
getValue();
820 const APInt DisjointBits = ConstantValue & BaseKnownBits.
Zero;
821 if (DisjointBits.
isZero())
830 const APInt NonDisjointBits = ConstantValue & ~DisjointBits;
831 Node.RHS = UserTree.size();
832 UserTree.push_back({ConstantInt::get(XorInst->getContext(), NonDisjointBits),
833 std::nullopt, std::nullopt});
843 if (Opcode == BinaryOperator::Or) {
856 return TI->hasNoUnsignedWrap();
863 if (
auto IP =
I->getInsertionPointAfterDef())
868Value *ConstantOffsetExtractor::Extract(
const Use &Idx, User *&UserTreeRoot,
869 bool &PreservesNUW) {
873 if (!Extractor.find(Idx, &Idx, Casts)) {
874 UserTreeRoot =
nullptr;
879 PreservesNUW =
all_of(Extractor.UserTree, [](
const RewriteNode &Node) {
880 return allowsPreservingNUW(Node.V);
884 Value *IdxWithoutConstOffset = Extractor.rebuildWithoutConstOffset();
886 return IdxWithoutConstOffset;
889std::optional<APInt> ConstantOffsetExtractor::Find(
const Use &Idx) {
892 return ConstantOffsetExtractor(
GEP->getIterator()).find(Idx, &Idx, Casts);
895bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToIndexSize(
896 GetElementPtrInst *
GEP) {
898 Type *PtrIdxTy =
DL->getIndexType(
GEP->getType());
901 I !=
E; ++
I, ++GTI) {
904 if ((*I)->getType() != PtrIdxTy) {
914APInt SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *
GEP,
915 bool &NeedsExtraction,
916 bool &SignedOverflow) {
917 NeedsExtraction =
false;
918 SignedOverflow =
false;
919 unsigned IdxWidth =
DL->getIndexTypeSizeInBits(
GEP->getType());
920 APInt AccumulativeByteOffset(IdxWidth, 0);
922 for (
unsigned I = 1,
E =
GEP->getNumOperands();
I !=
E; ++
I, ++GTI) {
929 if (std::optional<APInt> ConstantOffset =
930 ConstantOffsetExtractor::Find(
GEP->getOperandUse(
I))) {
931 NeedsExtraction =
true;
937 auto ByteOffset = ConstantOffset->sextOrTrunc(IdxWidth).smul_ov(
938 APInt(IdxWidth, Stride,
true,
true),
940 SignedOverflow |= Overflow;
945 auto *
Offset = ConstantInt::get(
GEP->getContext(), *ConstantOffset);
948 OverflowResult::NeverOverflows;
950 AccumulativeByteOffset =
951 AccumulativeByteOffset.sadd_ov(ByteOffset, Overflow);
952 SignedOverflow |= Overflow;
954 }
else if (LowerGEP) {
959 NeedsExtraction =
true;
960 AccumulativeByteOffset +=
961 APInt(IdxWidth,
DL->getStructLayout(StTy)->getElementOffset(
Field),
966 return AccumulativeByteOffset;
969void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
970 GetElementPtrInst *Variadic,
const APInt &AccumulativeByteOffset) {
977 bool isSwapCandidate =
978 L &&
L->isLoopInvariant(ResultPtr) &&
979 !hasMoreThanOneUseInLoop(ResultPtr, L);
980 Value *FirstResult =
nullptr;
985 for (
unsigned I = 1,
E =
Variadic->getNumOperands();
I !=
E; ++
I, ++GTI) {
996 if (ElementSize != 1) {
998 Idx = Builder.CreateShl(
999 Idx, ConstantInt::get(PtrIndexTy, ElementSize.
logBase2()));
1002 Builder.CreateMul(Idx, ConstantInt::get(PtrIndexTy, ElementSize));
1006 ResultPtr = Builder.CreatePtrAdd(ResultPtr, Idx,
"uglygep");
1007 if (FirstResult ==
nullptr)
1008 FirstResult = ResultPtr;
1013 if (AccumulativeByteOffset != 0) {
1014 Value *
Offset = ConstantInt::get(PtrIndexTy, AccumulativeByteOffset);
1015 ResultPtr = Builder.CreatePtrAdd(ResultPtr,
Offset,
"uglygep");
1017 isSwapCandidate =
false;
1024 if (isSwapCandidate && isLegalToSwapOperand(FirstGEP, SecondGEP, L))
1025 swapGEPOperand(FirstGEP, SecondGEP);
1027 Variadic->replaceAllUsesWith(ResultPtr);
1031bool SeparateConstOffsetFromGEP::reorderGEP(GetElementPtrInst *
GEP,
1032 TargetTransformInfo &
TTI) {
1037 bool NestedNeedsExtraction, OffsetOverflow;
1038 APInt NestedByteOffset =
1039 accumulateByteOffset(PtrGEP, NestedNeedsExtraction, OffsetOverflow);
1040 if (!NestedNeedsExtraction)
1043 unsigned AddrSpace = PtrGEP->getPointerAddressSpace();
1047 true, 0, AddrSpace))
1050 bool GEPInBounds =
GEP->isInBounds();
1051 bool PtrGEPInBounds = PtrGEP->isInBounds();
1052 bool IsChainInBounds = GEPInBounds && PtrGEPInBounds;
1053 if (IsChainInBounds) {
1054 auto IsKnownNonNegative = [
this](
Value *
V) {
1057 IsChainInBounds &=
all_of(
GEP->indices(), IsKnownNonNegative);
1058 if (IsChainInBounds)
1059 IsChainInBounds &=
all_of(PtrGEP->indices(), IsKnownNonNegative);
1064 Value *NewSrc = Builder.CreateGEP(
1065 GEP->getSourceElementType(), PtrGEP->getPointerOperand(),
1066 SmallVector<Value *, 4>(
GEP->indices()),
"", IsChainInBounds);
1067 Value *NewGEP = Builder.CreateGEP(PtrGEP->getSourceElementType(), NewSrc,
1068 SmallVector<Value *, 4>(PtrGEP->indices()),
1069 "", IsChainInBounds);
1070 GEP->replaceAllUsesWith(NewGEP);
1075bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *
GEP) {
1077 if (
GEP->getType()->isVectorTy())
1084 const APInt *BaseOffset;
1085 bool ExtractBase =
match(
GEP->getPointerOperand(),
1088 unsigned IdxWidth =
DL->getIndexTypeSizeInBits(
GEP->getType());
1089 APInt BaseByteOffset =
1090 ExtractBase ? BaseOffset->
sextOrTrunc(IdxWidth) : APInt(IdxWidth, 0);
1094 if (
GEP->hasAllConstantIndices() && !ExtractBase)
1097 bool Changed = canonicalizeArrayIndicesToIndexSize(
GEP);
1099 bool NeedsExtraction, OffsetOverflow;
1100 APInt NonBaseByteOffset =
1101 accumulateByteOffset(
GEP, NeedsExtraction, OffsetOverflow);
1103 APInt AccumulativeByteOffset =
1107 TargetTransformInfo &
TTI = GetTTI(*
GEP->getFunction());
1109 if (!NeedsExtraction && !ExtractBase) {
1122 unsigned AddrSpace =
GEP->getPointerAddressSpace();
1124 GEP->getResultElementType(),
1126 true, 0, AddrSpace)) {
1132 ExtractBase =
false;
1133 BaseByteOffset = APInt(IdxWidth, 0);
1134 AccumulativeByteOffset = NonBaseByteOffset;
1136 GEP->getResultElementType(),
1138 true, 0, AddrSpace))
1141 NeedsExtraction =
true;
1146 bool AllOffsetsNonNegative =
1148 bool AllNUWPreserved =
GEP->hasNoUnsignedWrap();
1149 bool NewGEPInBounds =
GEP->isInBounds();
1150 bool NewGEPNUSW =
GEP->hasNoUnsignedSignedWrap();
1160 for (
unsigned I = 1,
E =
GEP->getNumOperands();
I !=
E; ++
I, ++GTI) {
1171 Value *NewIdx = ConstantOffsetExtractor::Extract(
1172 GEP->getOperandUse(
I), UserTreeRoot, PreservesNUW);
1173 if (NewIdx !=
nullptr) {
1175 GEP->setOperand(
I, NewIdx);
1183 AllNUWPreserved &= PreservesNUW;
1185 AllOffsetsNonNegative =
1191 AllNUWPreserved &=
Base->hasNoUnsignedWrap();
1192 NewGEPInBounds &=
Base->isInBounds();
1193 NewGEPNUSW &=
Base->hasNoUnsignedSignedWrap();
1196 GEP->setOperand(0, NewBase);
1222 bool CanPreserveInBoundsNUSW = AllOffsetsNonNegative;
1226 if (AllNUWPreserved) {
1234 CanPreserveInBoundsNUSW |= NewGEPNUSW;
1237 if (CanPreserveInBoundsNUSW) {
1240 else if (NewGEPNUSW)
1244 GEP->setNoWrapFlags(NewGEPFlags);
1248 lowerToSingleIndexGEPs(
GEP, AccumulativeByteOffset);
1253 if (AccumulativeByteOffset == 0)
1276 Type *PtrIdxTy =
DL->getIndexType(
GEP->getType());
1279 NewGEP, ConstantInt::get(PtrIdxTy, AccumulativeByteOffset),
1280 GEP->getName(), NewGEPFlags));
1283 GEP->replaceAllUsesWith(NewGEP);
1284 GEP->eraseFromParent();
1289bool SeparateConstOffsetFromGEPLegacyPass::runOnFunction(
Function &
F) {
1290 if (skipFunction(
F))
1292 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1293 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1294 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
F);
1295 auto GetTTI = [
this](
Function &
F) -> TargetTransformInfo & {
1296 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
F);
1298 SeparateConstOffsetFromGEP Impl(DT, LI, TLI, GetTTI, LowerGEP);
1302bool SeparateConstOffsetFromGEP::run(
Function &
F) {
1303 const ScalarOptions &Opts =
1304 F.getContext().getLibraryOptions().get<ScalarOptions>();
1305 if (Opts.disable_separate_const_offset_from_gep)
1308 DL = &
F.getDataLayout();
1311 ReversePostOrderTraversal<Function *> RPOT(&
F);
1312 for (BasicBlock *
B : RPOT) {
1325 if (Opts.reassociate_geps_verify_no_dead_code)
1326 verifyNoDeadCode(
F);
1331Instruction *SeparateConstOffsetFromGEP::findClosestMatchingDominator(
1332 ExprKey
Key, Instruction *Dominatee,
1333 DenseMap<ExprKey, SmallVector<Instruction *, 2>> &DominatingExprs) {
1334 auto Pos = DominatingExprs.find(
Key);
1335 if (Pos == DominatingExprs.end())
1338 auto &Candidates = Pos->second;
1343 while (!Candidates.empty()) {
1345 if (DT->
dominates(Candidate, Dominatee))
1347 Candidates.pop_back();
1352bool SeparateConstOffsetFromGEP::reuniteExts(Instruction *
I) {
1353 if (!
I->getType()->isIntOrIntVectorTy())
1363 ExprKey
Key = createNormalizedCommutablePair(
LHS,
RHS);
1364 if (
auto *Dom = findClosestMatchingDominator(
Key,
I, DominatingAdds)) {
1366 new SExtInst(Dom,
I->getType(),
"",
I->getIterator());
1368 I->replaceAllUsesWith(NewSExt);
1377 findClosestMatchingDominator({
LHS,
RHS},
I, DominatingSubs)) {
1379 new SExtInst(Dom,
I->getType(),
"",
I->getIterator());
1381 I->replaceAllUsesWith(NewSExt);
1392 ExprKey
Key = createNormalizedCommutablePair(
LHS,
RHS);
1393 DominatingAdds[
Key].push_back(
I);
1397 DominatingSubs[{
LHS,
RHS}].push_back(
I);
1402bool SeparateConstOffsetFromGEP::reuniteExts(
Function &
F) {
1404 DominatingAdds.clear();
1405 DominatingSubs.clear();
1414void SeparateConstOffsetFromGEP::verifyNoDeadCode(
Function &
F) {
1415 for (BasicBlock &
B :
F) {
1416 for (Instruction &
I :
B) {
1418 std::string ErrMessage;
1419 raw_string_ostream RSO(ErrMessage);
1420 RSO <<
"Dead instruction detected!\n" <<
I <<
"\n";
1427bool SeparateConstOffsetFromGEP::isLegalToSwapOperand(
1428 GetElementPtrInst *FirstGEP, GetElementPtrInst *SecondGEP,
Loop *CurLoop) {
1429 if (!FirstGEP || !FirstGEP->
hasOneUse())
1435 if (FirstGEP == SecondGEP)
1441 if (FirstNum != SecondNum || FirstNum != 2)
1466 if (FirstOffsetDef && FirstOffsetDef->
isShift() &&
1475 if ((opc == Instruction::Add || opc == Instruction::Sub) &&
1483bool SeparateConstOffsetFromGEP::hasMoreThanOneUseInLoop(
Value *V,
Loop *L) {
1490 for (User *U :
V->users()) {
1492 if (
L->contains(User))
1493 if (++UsesInLoop > 1)
1499void SeparateConstOffsetFromGEP::swapGEPOperand(GetElementPtrInst *
First,
1500 GetElementPtrInst *Second) {
1503 First->setOperand(1, Offset2);
1508 const DataLayout &DAL =
First->getDataLayout();
1512 auto ClearNoWrapFlags = [&] {
1518 APInt FirstOffset(IdxBits, 0);
1519 if (!
First->accumulateConstantOffset(DAL, FirstOffset)) {
1524 APInt BaseOffset(IdxBits, 0);
1529 bool Overflow =
false;
1530 APInt TotalOffset = BaseOffset.
uadd_ov(FirstOffset, Overflow);
1532 if (Overflow || !
getObjectSize(NewBase, ObjectSize, DAL, TLI) ||
1533 TotalOffset.
ugt(ObjectSize)) {
1538 First->setIsInBounds(
true);
1543 static_cast<PassInfoMixin<SeparateConstOffsetFromGEPPass> *
>(
this)
1559 SeparateConstOffsetFromGEP Impl(DT, LI, TLI, GetTTI, LowerGEP);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool runOnFunction(Function &F, bool PostInlining)
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static const T * Find(StringRef S, ArrayRef< T > A)
Find KV in array using binary search.
OptimizedStructLayoutField Field
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static bool allowsPreservingNUW(const User *U)
Check if reassociating through a tree node would invalidate GEP's nuw flag.
static bool canReorderAddSextToGEP(const Use *Idx, const BinaryOperator *Add, const DataLayout &DL)
static BasicBlock::iterator getIndexInsertionPoint(const Use &Idx)
This file defines the SmallVector class.
Class for arbitrary precision integers.
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
unsigned logBase2() const
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
int64_t getSExtValue() const
Get sign extended value.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
InstListType::iterator iterator
Instruction iterators...
BinaryOps getOpcode() const
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Represents analyses that only rely on functions' control flow.
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
This is the shared class of boolean and integer constants.
const APInt & getValue() const
Return the constant as an APInt value reference.
A parsed version of the target data layout string in and methods for querying it.
unsigned getIndexSizeInBits(unsigned AS) const
The size in bits of indices used for address calculation in getelementptr and for addresses in the gi...
Analysis pass which computes a DominatorTree.
Legacy analysis pass which computes a DominatorTree.
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.
FunctionPass class - This class is used to implement most global optimizations.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GEPNoWrapFlags none()
LLVM_ABI void setNoWrapFlags(GEPNoWrapFlags NW)
Set nowrap flags for GEP instruction.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Analysis pass that exposes the LoopInfo for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
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.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
Represent a constant reference to a string, i.e.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
This class represents a truncation of integer types.
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
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.
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
An efficient, type-erasing, non-owning reference to a callable.
bool isSequential() const
StructType * getStructType() const
TypeSize getSequentialElementStride(const DataLayout &DL) const
Type * getIndexedType() const
const ParentTy * getParent() const
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
@ NeverOverflows
Never overflows.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
LLVM_ABI void initializeSeparateConstOffsetFromGEPLegacyPassPass(PassRegistry &)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
LLVM_ABI bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
auto reverse(ContainerTy &&C)
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI FunctionPass * createSeparateConstOffsetFromGEPPass(bool LowerGEP=false)
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.