24 #define DEBUG_TYPE "instcombine" 28 cl::desc(
"Maximum number phis to handle in intptr/ptrint folding"));
38 assert(!isa<CallInst>(Inst));
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;
185 II != EI; II++, NumPhis++) {
190 if (!PtrPHI || PtrPHI == &PN || PtrPHI->
getType() != IntToPtr->getType())
192 MatchingPtrPHI = PtrPHI;
194 if (AvailablePtrVals[i] !=
196 MatchingPtrPHI =
nullptr;
205 if (MatchingPtrPHI) {
206 assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
207 "Phi's Type does not match with IntToPtr");
210 IntToPtr->getOperand(0)->getType());
216 return (V->getType() != IntToPtr->getType()) ||
217 isa<IntToPtrInst>(V);
225 return (V->getType() != IntToPtr->getType()) &&
226 isa<TerminatorInst>(V);
233 InsertNewInstBefore(NewPtrPHI, PN);
237 auto *IncomingVal = AvailablePtrVals[i];
239 if (IncomingVal->getType() == IntToPtr->getType()) {
246 assert((isa<PHINode>(IncomingVal) ||
247 IncomingVal->getType()->isPointerTy() ||
249 "Can not replace LoadInst with multiple uses");
262 IncomingVal->getName() +
".ptr");
263 if (
auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
266 if (isa<PHINode>(IncomingI))
267 InsertPos = IncomingI->getParent()->getFirstInsertionPt();
268 InsertNewInstBefore(CI, *InsertPos);
270 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
271 InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
286 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
305 if (
CmpInst *CI = dyn_cast<CmpInst>(I))
306 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->
getPredicate())
310 if (I->
getOperand(0) != LHSVal) LHSVal =
nullptr;
311 if (I->
getOperand(1) != RHSVal) RHSVal =
nullptr;
318 if (!LHSVal && !RHSVal)
325 PHINode *NewLHS =
nullptr, *NewRHS =
nullptr;
330 InsertNewInstBefore(NewLHS, PN);
338 InsertNewInstBefore(NewRHS, PN);
343 if (NewLHS || NewRHS) {
357 if (
CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
360 PHIArgMergedDebugLoc(NewCI, PN);
373 PHIArgMergedDebugLoc(NewBinOp, PN);
384 bool AllBasePointersAreAllocas =
true;
389 bool NeededPhi =
false;
391 bool AllInBounds =
true;
403 if (AllBasePointersAreAllocas &&
406 AllBasePointersAreAllocas =
false;
432 FixedOperands[
op] =
nullptr;
443 if (AllBasePointersAreAllocas)
450 bool HasAnyPHIs =
false;
451 for (
unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
452 if (FixedOperands[i])
continue;
456 InsertNewInstBefore(NewPN, PN);
459 OperandPhis[i] = NewPN;
460 FixedOperands[i] = NewPN;
471 for (
unsigned op = 0, e = OperandPhis.size();
op != e; ++
op)
473 OpPhi->addIncoming(InGEP->
getOperand(op), InBB);
482 PHIArgMergedDebugLoc(NewGEP, PN);
497 for (++BBI; BBI !=
E; ++BBI)
498 if (BBI->mayWriteToMemory())
504 bool isAddressTaken =
false;
506 if (isa<LoadInst>(U))
continue;
509 if (
SI->getOperand(1) == AI)
continue;
511 isAddressTaken =
true;
515 if (!isAddressTaken && AI->isStaticAlloca())
581 LoadAlignment = std::min(LoadAlignment, LI->
getAlignment());
601 unsigned KnownIDs[] = {
613 for (
unsigned ID : KnownIDs)
621 if (NewInVal != InVal)
632 InsertNewInstBefore(NewPN, PN);
640 cast<LoadInst>(IncValue)->setVolatile(
false);
642 PHIArgMergedDebugLoc(NewLI, PN);
660 if (NumIncomingValues < 3)
664 Type *NarrowType =
nullptr;
666 if (
auto *Zext = dyn_cast<ZExtInst>(V)) {
667 NarrowType = Zext->getSrcTy();
677 unsigned NumZexts = 0;
678 unsigned NumConsts = 0;
680 if (
auto *Zext = dyn_cast<ZExtInst>(V)) {
682 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
684 NewIncoming.
push_back(Zext->getOperand(0));
686 }
else if (
auto *
C = dyn_cast<Constant>(V)) {
705 if (NumConsts == 0 || NumZexts < 2)
713 for (
unsigned i = 0; i != NumIncomingValues; ++i)
716 InsertNewInstBefore(NewPhi, Phi);
732 if (isa<GetElementPtrInst>(FirstInst))
733 return FoldPHIArgGEPIntoPHI(PN);
734 if (isa<LoadInst>(FirstInst))
735 return FoldPHIArgLoadIntoPHI(PN);
742 Type *CastSrcTy =
nullptr;
744 if (isa<CastInst>(FirstInst)) {
750 if (!shouldChangeType(PN.
getType(), CastSrcTy))
753 }
else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
758 return FoldPHIArgBinOpIntoPHI(PN);
788 if (NewInVal != InVal)
800 InsertNewInstBefore(NewPN, PN);
805 if (
CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
808 PHIArgMergedDebugLoc(NewCI, PN);
812 if (
BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
819 PHIArgMergedDebugLoc(BinOp, PN);
823 CmpInst *CIOp = cast<CmpInst>(FirstInst);
826 PHIArgMergedDebugLoc(NewCI, PN);
837 if (!PotentiallyDeadPHIs.
insert(PN).second)
841 if (PotentiallyDeadPHIs.
size() == 16)
856 if (!ValueEqualPHIs.
insert(PN).second)
860 if (ValueEqualPHIs.
size() == 16)
866 if (
PHINode *OpPN = dyn_cast<PHINode>(
Op)) {
869 }
else if (
Op != NonPhiInVal)
879 assert(isa<IntegerType>(PN.
getType()) &&
"Expect only integer type phi");
881 if (
auto *ConstVA = dyn_cast<ConstantInt>(V))
882 if (!ConstVA->isZero())
888 struct PHIUsageRecord {
894 : PHIId(pn), Shift(Sh), Inst(User) {}
896 bool operator<(
const PHIUsageRecord &RHS)
const {
897 if (PHIId < RHS.PHIId)
return true;
898 if (PHIId > RHS.PHIId)
return false;
899 if (Shift < RHS.Shift)
return true;
900 if (Shift > RHS.Shift)
return false;
902 RHS.Inst->getType()->getPrimitiveSizeInBits();
906 struct LoweredPHIRecord {
911 LoweredPHIRecord(
PHINode *pn,
unsigned Sh,
Type *Ty)
915 LoweredPHIRecord(
PHINode *pn,
unsigned Sh)
916 : PN(pn), Shift(Sh), Width(0) {}
924 return LoweredPHIRecord(
nullptr, 0);
927 return LoweredPHIRecord(
nullptr, 1);
933 static bool isEqual(
const LoweredPHIRecord &LHS,
934 const LoweredPHIRecord &RHS) {
935 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
936 LHS.Width == RHS.Width;
963 PHIsInspected.
insert(&FirstPhi);
965 for (
unsigned PHIId = 0; PHIId != PHIsToSlice.
size(); ++PHIId) {
966 PHINode *PN = PHIsToSlice[PHIId];
988 if (
PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
989 if (PHIsInspected.
insert(UserPN).second)
995 if (isa<TruncInst>(UserI)) {
996 PHIUsers.
push_back(PHIUsageRecord(PHIId, 0, UserI));
1001 if (UserI->
getOpcode() != Instruction::LShr ||
1006 unsigned Shift = cast<ConstantInt>(UserI->
getOperand(1))->getZExtValue();
1012 if (PHIUsers.
empty())
1020 for (
unsigned i = 1, e = PHIsToSlice.
size(); i != e; ++i)
dbgs()
1021 <<
"AND USER PHI #" << i <<
": " << *PHIsToSlice[i] <<
'\n';);
1031 for (
unsigned UserI = 0, UserE = PHIUsers.
size(); UserI != UserE; ++UserI) {
1032 unsigned PHIId = PHIUsers[UserI].PHIId;
1033 PHINode *PN = PHIsToSlice[PHIId];
1034 unsigned Offset = PHIUsers[UserI].Shift;
1035 Type *Ty = PHIUsers[UserI].Inst->getType();
1041 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) ==
nullptr) {
1047 "Truncate didn't shrink phi?");
1051 Value *&PredVal = PredValues[Pred];
1067 if (
PHINode *InPHI = dyn_cast<PHINode>(PN)) {
1070 if (
Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
1083 Res = Builder.CreateTrunc(Res, Ty,
"extract.t");
1092 if (PHIsInspected.
count(OldInVal)) {
1094 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
1095 PHIUsers.
push_back(PHIUsageRecord(RefPHIId, Offset,
1096 cast<Instruction>(Res)));
1102 LLVM_DEBUG(
dbgs() <<
" Made element PHI for offset " << Offset <<
": " 1103 << *EltPHI <<
'\n');
1104 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1108 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
1114 for (
unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
1115 replaceInstUsesWith(*PHIsToSlice[i], Undef);
1116 return replaceInstUsesWith(FirstPhi, Undef);
1123 return replaceInstUsesWith(PN, V);
1148 if (
PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
1150 PotentiallyDeadPHIs.
insert(&PN);
1162 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
1200 while (InValNo != NumIncomingVals &&
1204 if (InValNo != NumIncomingVals) {
1209 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
1211 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1218 if (InValNo == NumIncomingVals) {
1221 return replaceInstUsesWith(PN, NonPhiInVal);
1256 if (
Instruction *Res = SliceUpIllegalIntegerPHI(PN))
void push_back(const T &Elt)
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...
Compute iterated dominance frontiers using a linear time algorithm.
BinaryOps getOpcode() const
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
static LoweredPHIRecord getEmptyKey()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
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.
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.
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.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
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.
Subclasses of this class are all able to terminate a basic block.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
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.
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)
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.
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()
InstListType::iterator iterator
Instruction iterators...
amdgpu Simplify well known AMD library false Value Value * Arg
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
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.
void emplace_back(ArgTypes &&... Args)
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.
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())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
bool operator<(int64_t V1, const APSInt &V2)
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
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 isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return true if the given value is known to be non-zero when defined.
bool hasOneUse() const
Return true if there is exactly one user of this value.
static bool isVolatile(Instruction *Inst)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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.
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
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