53 #define DEBUG_TYPE "correlated-value-propagation" 55 STATISTIC(NumPhis,
"Number of phis propagated");
56 STATISTIC(NumPhiCommon,
"Number of phis deleted via common incoming value");
57 STATISTIC(NumSelects,
"Number of selects propagated");
58 STATISTIC(NumMemAccess,
"Number of memory access targets propagated");
59 STATISTIC(NumCmps,
"Number of comparisons propagated");
60 STATISTIC(NumReturns,
"Number of return values propagated");
61 STATISTIC(NumDeadCases,
"Number of switch cases removed");
62 STATISTIC(NumSDivs,
"Number of sdiv converted to udiv");
63 STATISTIC(NumUDivs,
"Number of udivs whose width was decreased");
64 STATISTIC(NumAShrs,
"Number of ashr converted to lshr");
65 STATISTIC(NumSRems,
"Number of srem converted to urem");
66 STATISTIC(NumSExt,
"Number of sext converted to zext");
67 STATISTIC(NumAnd,
"Number of ands removed");
68 STATISTIC(NumNW,
"Number of no-wrap deductions");
69 STATISTIC(NumNSW,
"Number of no-signed-wrap deductions");
70 STATISTIC(NumNUW,
"Number of no-unsigned-wrap deductions");
71 STATISTIC(NumAddNW,
"Number of no-wrap deductions for add");
72 STATISTIC(NumAddNSW,
"Number of no-signed-wrap deductions for add");
73 STATISTIC(NumAddNUW,
"Number of no-unsigned-wrap deductions for add");
74 STATISTIC(NumSubNW,
"Number of no-wrap deductions for sub");
75 STATISTIC(NumSubNSW,
"Number of no-signed-wrap deductions for sub");
76 STATISTIC(NumSubNUW,
"Number of no-unsigned-wrap deductions for sub");
77 STATISTIC(NumMulNW,
"Number of no-wrap deductions for mul");
78 STATISTIC(NumMulNSW,
"Number of no-signed-wrap deductions for mul");
79 STATISTIC(NumMulNUW,
"Number of no-unsigned-wrap deductions for mul");
80 STATISTIC(NumShlNW,
"Number of no-wrap deductions for shl");
81 STATISTIC(NumShlNSW,
"Number of no-signed-wrap deductions for shl");
82 STATISTIC(NumShlNUW,
"Number of no-unsigned-wrap deductions for shl");
83 STATISTIC(NumOverflows,
"Number of overflow checks removed");
85 "Number of saturating arithmetics converted to normal arithmetics");
115 "Value Propagation",
false,
false)
123 return new CorrelatedValuePropagation();
128 if (isa<Constant>(S->
getOperand(0)))
return false;
131 if (!C)
return false;
134 if (!CI)
return false;
164 Value *CommonValue =
nullptr;
167 if (
auto *IncomingConstant = dyn_cast<Constant>(Incoming)) {
168 IncomingConstants.
push_back(std::make_pair(IncomingConstant, i));
169 }
else if (!CommonValue) {
171 CommonValue = Incoming;
172 }
else if (Incoming != CommonValue) {
178 if (!CommonValue || IncomingConstants.
empty())
183 if (
auto *CommonInst = dyn_cast<Instruction>(CommonValue))
190 for (
auto &IncomingConstant : IncomingConstants) {
204 if (
auto *CommonInst = dyn_cast<Instruction>(CommonValue))
205 CommonInst->dropPoisonGeneratingFlags();
214 bool Changed =
false;
219 if (isa<Constant>(Incoming))
continue;
235 if (
C->isOneValue()) {
237 }
else if (
C->isZeroValue()) {
283 Value *Pointer =
nullptr;
284 if (
LoadInst *L = dyn_cast<LoadInst>(I))
285 Pointer = L->getPointerOperand();
289 if (isa<Constant>(Pointer))
return false;
292 if (!C)
return false;
345 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->
getParent() == BB)
350 if (PB == PE)
return false;
353 bool Changed =
false;
356 SuccessorsCount[Succ]++;
388 if (Value != State) {
407 if (--SuccessorsCount[Succ] == 0)
446 bool NewNSW,
bool NewNUW) {
454 case Instruction::Sub:
459 case Instruction::Mul:
464 case Instruction::Shl:
480 Inst->setHasNoSignedWrap();
488 Inst->setHasNoUnsignedWrap();
515 if (
auto *BO = dyn_cast<BinaryOperator>(NewOp))
533 if (
auto *BO = dyn_cast<BinaryOperator>(BinOp))
543 if (WO->getLHS()->getType()->isIntegerTy() &&
willNotOverflow(WO, LVI)) {
564 bool Progress =
false;
565 for (
const Use &ConstU : DeoptBundle->Inputs) {
566 Use &U =
const_cast<Use&
>(ConstU);
569 if (isa<Constant>(V))
continue;
585 if (Type && !CS.
paramHasAttr(ArgNo, Attribute::NonNull) &&
622 Instr->
getOpcode() == Instruction::URem);
635 unsigned NewWidth = std::max<unsigned>(
639 if (NewWidth >= OrigWidth)
645 auto *LHS =
B.CreateTruncOrBitCast(Instr->
getOperand(0), TruncTy,
646 Instr->
getName() +
".lhs.trunc");
647 auto *RHS =
B.CreateTruncOrBitCast(Instr->
getOperand(1), TruncTy,
648 Instr->
getName() +
".rhs.trunc");
650 auto *Zext =
B.CreateZExt(BO, Instr->
getType(), Instr->
getName() +
".zext");
651 if (
auto *BinOp = dyn_cast<BinaryOperator>(BO))
652 if (BinOp->
getOpcode() == Instruction::UDiv)
690 BO->setIsExact(SDI->
isExact());
713 BO->setIsExact(SDI->
isExact());
764 bool Changed =
false;
765 bool NewNUW =
false, NewNSW =
false;
768 Opcode, RRange, OBO::NoUnsignedWrap);
774 Opcode, RRange, OBO::NoSignedWrap);
814 if (!
C)
return nullptr;
818 if (!Op1)
return nullptr;
832 bool FnChanged =
false;
839 bool BBChanged =
false;
846 case Instruction::PHI:
847 BBChanged |=
processPHI(cast<PHINode>(II), LVI, DT, SQ);
849 case Instruction::ICmp:
850 case Instruction::FCmp:
851 BBChanged |=
processCmp(cast<CmpInst>(II), LVI);
858 case Instruction::Invoke:
861 case Instruction::SRem:
862 BBChanged |=
processSRem(cast<BinaryOperator>(II), LVI);
864 case Instruction::SDiv:
865 BBChanged |=
processSDiv(cast<BinaryOperator>(II), LVI);
867 case Instruction::UDiv:
868 case Instruction::URem:
871 case Instruction::AShr:
872 BBChanged |=
processAShr(cast<BinaryOperator>(II), LVI);
874 case Instruction::SExt:
878 case Instruction::Sub:
879 case Instruction::Mul:
880 case Instruction::Shl:
881 BBChanged |=
processBinOp(cast<BinaryOperator>(II), LVI);
883 case Instruction::And:
884 BBChanged |=
processAnd(cast<BinaryOperator>(II), LVI);
891 case Instruction::Switch:
895 auto *RI = cast<ReturnInst>(Term);
899 auto *RetVal = RI->getReturnValue();
901 if (isa<Constant>(RetVal))
break;
904 RI->replaceUsesOfWith(RetVal,
C);
910 FnChanged |= BBChanged;
920 LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
921 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Legacy wrapper pass to provide the GlobalsAAResult object.
Pass interface - Implemented by all 'passes'.
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static ConstantInt * getFalse(LLVMContext &Context)
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
This class is the base class for the comparison instructions.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
ConstantRange getConstantRange(Value *V, BasicBlock *BB, Instruction *CxtI=nullptr)
Return the ConstantRange constraint that is known to hold for the specified value at the end of the s...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
BinaryOps getOpcode() const
Wrapper around LazyValueInfo.
Type * getElementType(unsigned N) const
This is the interface for a simple mod/ref and alias analysis over globals.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
Represents an op.with.overflow intrinsic.
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
void push_back(const T &Elt)
Value * getCondition() const
const Value * getTrueValue() const
CaseIt case_begin()
Returns a read/write iterator that points to the first case in the SwitchInst.
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
LLVMContext & getContext() const
All values hold a context through their type.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
This class represents a sign extension of integer types.
An instruction for reading from memory.
Optional< OperandBundleUse > getOperandBundle(StringRef Name) const
bool isVectorTy() const
True if this is an instance of VectorType.
const SimplifyQuery getBestSimplifyQuery(Pass &, Function &)
unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Constant * getConstant(Value *V, BasicBlock *BB, Instruction *CxtI=nullptr)
Determine whether the specified value is known to be a constant at the end of the specified block...
This class represents the LLVM 'select' instruction.
static constexpr UpdateKind Delete
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
This file contains the simple types necessary to represent the attributes associated with functions a...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
InstrTy * getInstruction() const
unsigned getActiveBits() const
Compute the number of active bits in the value.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag...
Type * getType() const
All values are typed, get the type of this value.
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the call or the callee has the given attribute.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
Class to represent pointers.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight...
const BasicBlock & getEntryBlock() const
Pass * createCorrelatedValuePropagationPass()
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Constant * getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value is known to be a constant on the specified edge.
LLVM Basic Block Representation.
LLVM_NODISCARD AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isSigned() const
Whether the intrinsic is signed or unsigned.
AttributeList getAttributes() const
Get the parameter attributes of the call.
bool isMask(unsigned numBits) const
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
Represent the analysis usage information of a pass.
Analysis pass providing a never-invalidated alias analysis result.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl...
FunctionPass class - This class is used to implement most global optimizations.
static Constant * get(StructType *T, ArrayRef< Constant *> V)
Interval::pred_iterator pred_end(Interval *I)
void applyUpdatesPermissive(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
const Value * getCondition() const
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
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.
bool isExact() const
Determine whether the exact flag is set.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
iterator_range< IterTy > args() const
Tristate
This is used to return true/false/dunno results.
Tristate getPredicateOnEdge(unsigned Pred, Value *V, Constant *C, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value comparison with a constant is known to be true or false on the ...
Tristate getPredicateAt(unsigned Pred, Value *V, Constant *C, Instruction *CxtI)
Determine whether the specified value comparison with a constant is known to be true or false at the ...
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
void initializeCorrelatedValuePropagationPass(PassRegistry &)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Represents a saturating add/sub intrinsic.
unsigned arg_size() const
This class represents a range of values.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
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.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
BBTy * getParent() const
Get the basic block containing the call site.
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.
const Value * getFalseValue() const
Predicate getPredicate() const
Return the predicate for this instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
void setCondition(Value *V)
unsigned getIntegerBitWidth() const
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)
void preserve()
Mark an analysis as preserved.
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
This class represents an intrinsic that is based on a binary operation.
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
iterator_range< df_iterator< T > > depth_first(const T &G)
This pass computes, caches, and vends lazy value constraint information.
static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
succ_range successors(Instruction *I)
static const Function * getParent(const Value *V)
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
This header defines various interfaces for pass management in LLVM.
void setIncomingValue(unsigned i, Value *V)
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Analysis to compute lazy value information.
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
const BasicBlock * getParent() const