24 #define DEBUG_TYPE "instcombine" 28 cl::desc(
"Maximum number phis to handle in intptr/ptrint folding"));
38 assert(!isa<CallInst>(Inst));
109 Value *Ptr =
nullptr;
110 if (
LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
111 Ptr = LoadI->getPointerOperand();
112 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(U)) {
113 Ptr =
SI->getPointerOperand();
115 Ptr = GI->getPointerOperand();
118 if (Ptr && Ptr == IIP)
124 if (!HasPointerUse(IntToPtr))
127 if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
128 DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
136 if (
auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
142 Value *ArgIntToPtr =
nullptr;
144 if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
159 if (isa<PHINode>(Arg)) {
169 if (!LoadI->hasOneUse())
181 "Not enough available ptr typed incoming values");
182 PHINode *MatchingPtrPHI =
nullptr;
183 unsigned NumPhis = 0;
184 for (
auto II = BB->begin(); II != BB->end(); II++, NumPhis++) {
191 if (PtrPHI == &PN || PtrPHI->
getType() != IntToPtr->getType())
193 MatchingPtrPHI = PtrPHI;
195 if (AvailablePtrVals[i] !=
197 MatchingPtrPHI =
nullptr;
206 if (MatchingPtrPHI) {
207 assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
208 "Phi's Type does not match with IntToPtr");
211 IntToPtr->getOperand(0)->getType());
216 return (V->
getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V);
225 if (V->
getType() == IntToPtr->getType())
233 if (isa<PHINode>(Inst) && BB->getFirstInsertionPt() == BB->end())
242 InsertNewInstBefore(NewPtrPHI, PN);
246 auto *IncomingVal = AvailablePtrVals[i];
248 if (IncomingVal->getType() == IntToPtr->getType()) {
255 assert((isa<PHINode>(IncomingVal) ||
256 IncomingVal->getType()->isPointerTy() ||
258 "Can not replace LoadInst with multiple uses");
271 IncomingVal->getName() +
".ptr");
272 if (
auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
276 if (isa<PHINode>(IncomingI))
278 assert(InsertPos != BB->
end() &&
"should have checked above");
279 InsertNewInstBefore(CI, *InsertPos);
281 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
282 InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
297 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
316 if (
CmpInst *CI = dyn_cast<CmpInst>(I))
317 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->
getPredicate())
321 if (I->
getOperand(0) != LHSVal) LHSVal =
nullptr;
322 if (I->
getOperand(1) != RHSVal) RHSVal =
nullptr;
329 if (!LHSVal && !RHSVal)
336 PHINode *NewLHS =
nullptr, *NewRHS =
nullptr;
341 InsertNewInstBefore(NewLHS, PN);
349 InsertNewInstBefore(NewRHS, PN);
354 if (NewLHS || NewRHS) {
368 if (
CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
371 PHIArgMergedDebugLoc(NewCI, PN);
384 PHIArgMergedDebugLoc(NewBinOp, PN);
395 bool AllBasePointersAreAllocas =
true;
400 bool NeededPhi =
false;
402 bool AllInBounds =
true;
414 if (AllBasePointersAreAllocas &&
417 AllBasePointersAreAllocas =
false;
443 FixedOperands[
op] =
nullptr;
454 if (AllBasePointersAreAllocas)
461 bool HasAnyPHIs =
false;
462 for (
unsigned i = 0,
e = FixedOperands.size(); i !=
e; ++i) {
463 if (FixedOperands[i])
continue;
467 InsertNewInstBefore(NewPN, PN);
470 OperandPhis[i] = NewPN;
471 FixedOperands[i] = NewPN;
482 for (
unsigned op = 0,
e = OperandPhis.size();
op !=
e; ++
op)
484 OpPhi->addIncoming(InGEP->
getOperand(op), InBB);
493 PHIArgMergedDebugLoc(NewGEP, PN);
508 for (++BBI; BBI !=
E; ++BBI)
509 if (BBI->mayWriteToMemory())
515 bool isAddressTaken =
false;
517 if (isa<LoadInst>(U))
continue;
520 if (
SI->getOperand(1) == AI)
continue;
522 isAddressTaken =
true;
526 if (!isAddressTaken && AI->isStaticAlloca())
589 if ((LoadAlignment.hasValue()) != (LI->
getAlignment() != 0))
613 unsigned KnownIDs[] = {
614 LLVMContext::MD_tbaa,
615 LLVMContext::MD_range,
616 LLVMContext::MD_invariant_load,
617 LLVMContext::MD_alias_scope,
618 LLVMContext::MD_noalias,
619 LLVMContext::MD_nonnull,
620 LLVMContext::MD_align,
621 LLVMContext::MD_dereferenceable,
622 LLVMContext::MD_dereferenceable_or_null,
623 LLVMContext::MD_access_group,
626 for (
unsigned ID : KnownIDs)
634 if (NewInVal != InVal)
645 InsertNewInstBefore(NewPN, PN);
653 cast<LoadInst>(IncValue)->setVolatile(
false);
655 PHIArgMergedDebugLoc(NewLI, PN);
673 if (NumIncomingValues < 3)
677 Type *NarrowType =
nullptr;
679 if (
auto *Zext = dyn_cast<ZExtInst>(V)) {
680 NarrowType = Zext->getSrcTy();
690 unsigned NumZexts = 0;
691 unsigned NumConsts = 0;
693 if (
auto *Zext = dyn_cast<ZExtInst>(V)) {
695 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
697 NewIncoming.
push_back(Zext->getOperand(0));
699 }
else if (
auto *
C = dyn_cast<Constant>(V)) {
718 if (NumConsts == 0 || NumZexts < 2)
726 for (
unsigned i = 0; i != NumIncomingValues; ++i)
729 InsertNewInstBefore(NewPhi, Phi);
745 if (isa<GetElementPtrInst>(FirstInst))
746 return FoldPHIArgGEPIntoPHI(PN);
747 if (isa<LoadInst>(FirstInst))
748 return FoldPHIArgLoadIntoPHI(PN);
755 Type *CastSrcTy =
nullptr;
757 if (isa<CastInst>(FirstInst)) {
763 if (!shouldChangeType(PN.
getType(), CastSrcTy))
766 }
else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
771 return FoldPHIArgBinOpIntoPHI(PN);
801 if (NewInVal != InVal)
813 InsertNewInstBefore(NewPN, PN);
818 if (
CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
821 PHIArgMergedDebugLoc(NewCI, PN);
825 if (
BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
832 PHIArgMergedDebugLoc(BinOp, PN);
836 CmpInst *CIOp = cast<CmpInst>(FirstInst);
839 PHIArgMergedDebugLoc(NewCI, PN);
850 if (!PotentiallyDeadPHIs.
insert(PN).second)
854 if (PotentiallyDeadPHIs.
size() == 16)
869 if (!ValueEqualPHIs.
insert(PN).second)
873 if (ValueEqualPHIs.
size() == 16)
879 if (
PHINode *OpPN = dyn_cast<PHINode>(
Op)) {
882 }
else if (
Op != NonPhiInVal)
892 assert(isa<IntegerType>(PN.
getType()) &&
"Expect only integer type phi");
894 if (
auto *ConstVA = dyn_cast<ConstantInt>(V))
895 if (!ConstVA->isZero())
901 struct PHIUsageRecord {
907 : PHIId(pn), Shift(Sh), Inst(User) {}
909 bool operator<(
const PHIUsageRecord &RHS)
const {
910 if (PHIId < RHS.PHIId)
return true;
911 if (PHIId > RHS.PHIId)
return false;
912 if (Shift < RHS.Shift)
return true;
913 if (Shift > RHS.Shift)
return false;
915 RHS.Inst->getType()->getPrimitiveSizeInBits();
919 struct LoweredPHIRecord {
924 LoweredPHIRecord(
PHINode *pn,
unsigned Sh,
Type *Ty)
928 LoweredPHIRecord(
PHINode *pn,
unsigned Sh)
929 : PN(pn), Shift(Sh),
Width(0) {}
937 return LoweredPHIRecord(
nullptr, 0);
940 return LoweredPHIRecord(
nullptr, 1);
946 static bool isEqual(
const LoweredPHIRecord &LHS,
947 const LoweredPHIRecord &RHS) {
948 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
949 LHS.Width == RHS.Width;
976 PHIsInspected.
insert(&FirstPhi);
978 for (
unsigned PHIId = 0; PHIId != PHIsToSlice.
size(); ++PHIId) {
979 PHINode *PN = PHIsToSlice[PHIId];
1001 if (
PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
1002 if (PHIsInspected.
insert(UserPN).second)
1008 if (isa<TruncInst>(UserI)) {
1009 PHIUsers.
push_back(PHIUsageRecord(PHIId, 0, UserI));
1014 if (UserI->
getOpcode() != Instruction::LShr ||
1021 if (cast<ConstantInt>(UserI->
getOperand(1))->getValue().uge(SizeInBits))
1024 unsigned Shift = cast<ConstantInt>(UserI->
getOperand(1))->getZExtValue();
1030 if (PHIUsers.
empty())
1038 for (
unsigned i = 1,
e = PHIsToSlice.
size(); i !=
e; ++i)
dbgs()
1039 <<
"AND USER PHI #" << i <<
": " << *PHIsToSlice[i] <<
'\n';);
1049 for (
unsigned UserI = 0, UserE = PHIUsers.
size(); UserI != UserE; ++UserI) {
1050 unsigned PHIId = PHIUsers[UserI].PHIId;
1051 PHINode *PN = PHIsToSlice[PHIId];
1052 unsigned Offset = PHIUsers[UserI].Shift;
1053 Type *Ty = PHIUsers[UserI].Inst->getType();
1059 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) ==
nullptr) {
1065 "Truncate didn't shrink phi?");
1069 Value *&PredVal = PredValues[Pred];
1085 if (
PHINode *InPHI = dyn_cast<PHINode>(PN)) {
1088 if (
Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
1101 Res = Builder.CreateTrunc(Res, Ty,
"extract.t");
1110 if (PHIsInspected.
count(OldInVal)) {
1112 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
1113 PHIUsers.
push_back(PHIUsageRecord(RefPHIId, Offset,
1114 cast<Instruction>(Res)));
1120 LLVM_DEBUG(
dbgs() <<
" Made element PHI for offset " << Offset <<
": " 1121 << *EltPHI <<
'\n');
1122 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1126 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
1132 for (
unsigned i = 1,
e = PHIsToSlice.size(); i !=
e; ++i)
1133 replaceInstUsesWith(*PHIsToSlice[i], Undef);
1134 return replaceInstUsesWith(FirstPhi, Undef);
1141 return replaceInstUsesWith(PN, V);
1143 if (
Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
1155 if (
Instruction *Result = FoldPHIArgOpIntoPHI(PN))
1162 if (
Instruction *Result = FoldIntegerTypedPHI(PN))
1166 if (
PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
1168 PotentiallyDeadPHIs.
insert(&PN);
1180 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
1218 while (InValNo != NumIncomingVals &&
1222 if (InValNo != NumIncomingVals) {
1227 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
1229 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1236 if (InValNo == NumIncomingVals) {
1239 return replaceInstUsesWith(PN, NonPhiInVal);
1274 if (
Instruction *Res = SliceUpIllegalIntegerPHI(PN))
reference emplace_back(ArgTypes &&... Args)
This class is the base class for the comparison instructions.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
This class represents lattice values for constants.
BinaryOps getOpcode() const
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
void push_back(const T &Elt)
static LoweredPHIRecord getEmptyKey()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
bool isTerminator() const
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
An instruction for reading from memory.
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...
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
static ConstantInt * GetAnyNonZeroConstInt(PHINode &PN)
Return an existing non-zero constant if this phi node has one, otherwise return constant 1...
static bool isSafeAndProfitableToSinkLoad(LoadInst *L)
Return true if we know that it is safe to sink the load out of the block that defines it...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool match(Val *V, const Pattern &P)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This is the base class for all instructions that perform data casts.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Instruction * SliceUpIllegalIntegerPHI(PHINode &PN)
This is an integer PHI and we know that it has an illegal type: see if it is only used by trunc or tr...
static bool isEqual(const LoweredPHIRecord &LHS, const LoweredPHIRecord &RHS)
Type * getSourceElementType() const
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
OtherOps getOpcode() const
Get the opcode casted to the right type.
Type * getType() const
All values are typed, get the type of this value.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
initializer< Ty > init(const Ty &Val)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
This instruction compares its operands according to the predicate given to the constructor.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
This class represents a cast from an integer to a pointer.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
Instruction * visitPHINode(PHINode &PN)
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
void setIncomingBlock(unsigned i, BasicBlock *BB)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
static cl::opt< unsigned > MaxNumPhis("instcombine-max-num-phis", cl::init(512), cl::desc("Maximum number phis to handle in intptr/ptrint folding"))
static LoweredPHIRecord getTombstoneKey()
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void applyMergedLocation(const DILocation *LocA, const DILocation *LocB)
Merge 2 debug locations and apply it to the Instruction.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to be non-zero when defined.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
static bool DeadPHICycle(PHINode *PN, SmallPtrSetImpl< PHINode *> &PotentiallyDeadPHIs)
Return true if this PHI node is only used by a PHI node cycle that is dead.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate getPredicate() const
Return the predicate for this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool operator<(int64_t V1, const APSInt &V2)
LLVM Value Representation.
bool isEquality() const
This is just a convenience that dispatches to the subclasses.
This file provides internal interfaces used to implement the InstCombine.
static unsigned getHashValue(const LoweredPHIRecord &Val)
bool hasOneUse() const
Return true if there is exactly one user of this value.
static bool isVolatile(Instruction *Inst)
void setIncomingValue(unsigned i, Value *V)
op_range incoming_values()
static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, SmallPtrSetImpl< PHINode *> &ValueEqualPHIs)
Return true if this phi node is always equal to NonPhiInVal.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack