52 #define DEBUG_TYPE "correlated-value-propagation" 54 STATISTIC(NumPhis,
"Number of phis propagated");
55 STATISTIC(NumPhiCommon,
"Number of phis deleted via common incoming value");
56 STATISTIC(NumSelects,
"Number of selects propagated");
57 STATISTIC(NumMemAccess,
"Number of memory access targets propagated");
58 STATISTIC(NumCmps,
"Number of comparisons propagated");
59 STATISTIC(NumReturns,
"Number of return values propagated");
60 STATISTIC(NumDeadCases,
"Number of switch cases removed");
61 STATISTIC(NumSDivs,
"Number of sdiv converted to udiv");
62 STATISTIC(NumUDivs,
"Number of udivs whose width was decreased");
63 STATISTIC(NumAShrs,
"Number of ashr converted to lshr");
64 STATISTIC(NumSRems,
"Number of srem converted to urem");
65 STATISTIC(NumOverflows,
"Number of overflow checks removed");
94 "Value Propagation",
false,
false)
102 return new CorrelatedValuePropagation();
107 if (isa<Constant>(S->
getOperand(0)))
return false;
110 if (!C)
return false;
113 if (!CI)
return false;
143 Value *CommonValue =
nullptr;
146 if (
auto *IncomingConstant = dyn_cast<Constant>(Incoming)) {
147 IncomingConstants.
push_back(std::make_pair(IncomingConstant, i));
148 }
else if (!CommonValue) {
150 CommonValue = Incoming;
151 }
else if (Incoming != CommonValue) {
157 if (!CommonValue || IncomingConstants.
empty())
162 if (
auto *CommonInst = dyn_cast<Instruction>(CommonValue))
169 for (
auto &IncomingConstant : IncomingConstants) {
186 bool Changed =
false;
191 if (isa<Constant>(Incoming))
continue;
207 if (
C->isOneValue()) {
209 }
else if (
C->isZeroValue()) {
255 Value *Pointer =
nullptr;
256 if (
LoadInst *L = dyn_cast<LoadInst>(I))
257 Pointer = L->getPointerOperand();
261 if (isa<Constant>(Pointer))
return false;
264 if (!C)
return false;
278 if (!Op1)
return false;
316 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->
getParent() == BB)
321 if (PB == PE)
return false;
324 bool Changed =
false;
327 SuccessorsCount[Succ]++;
355 if (Value != State) {
374 if (--SuccessorsCount[Succ] == 0)
411 BinOp, RRange, NoWrapKind);
422 case Intrinsic::uadd_with_overflow:
424 case Intrinsic::sadd_with_overflow:
426 case Intrinsic::usub_with_overflow:
427 return NoWrap(Instruction::Sub, OBO::NoUnsignedWrap);
428 case Intrinsic::ssub_with_overflow:
429 return NoWrap(Instruction::Sub, OBO::NoSignedWrap);
435 Value *NewOp =
nullptr;
439 case Intrinsic::uadd_with_overflow:
440 case Intrinsic::sadd_with_overflow:
444 case Intrinsic::usub_with_overflow:
445 case Intrinsic::ssub_with_overflow:
475 if (Type && !CS.
paramHasAttr(ArgNo, Attribute::NonNull) &&
512 Instr->
getOpcode() == Instruction::URem);
525 unsigned NewWidth = std::max<unsigned>(
529 if (NewWidth >= OrigWidth)
535 Instr->
getName() +
".lhs.trunc", Instr);
537 Instr->
getName() +
".rhs.trunc", Instr);
541 Instr->
getName() +
".zext", Instr);
542 if (BO->getOpcode() == Instruction::UDiv)
578 BO->setIsExact(SDI->
isExact());
600 BO->setIsExact(SDI->
isExact());
632 auto LazyRRange = [&] () {
638 bool Changed =
false;
643 bool NewNUW = NUWRange.
contains(LazyRRange());
652 bool NewNSW = NSWRange.
contains(LazyRRange());
668 if (!
C)
return nullptr;
672 if (!Op1)
return nullptr;
686 bool FnChanged =
false;
693 bool BBChanged =
false;
700 case Instruction::PHI:
701 BBChanged |=
processPHI(cast<PHINode>(II), LVI, DT, SQ);
703 case Instruction::ICmp:
704 case Instruction::FCmp:
705 BBChanged |=
processCmp(cast<CmpInst>(II), LVI);
712 case Instruction::Invoke:
715 case Instruction::SRem:
716 BBChanged |=
processSRem(cast<BinaryOperator>(II), LVI);
718 case Instruction::SDiv:
719 BBChanged |=
processSDiv(cast<BinaryOperator>(II), LVI);
721 case Instruction::UDiv:
722 case Instruction::URem:
725 case Instruction::AShr:
726 BBChanged |=
processAShr(cast<BinaryOperator>(II), LVI);
729 BBChanged |=
processAdd(cast<BinaryOperator>(II), LVI);
736 case Instruction::Switch:
740 auto *RI = cast<ReturnInst>(Term);
744 auto *RetVal = RI->getReturnValue();
746 if (isa<Constant>(RetVal))
break;
749 RI->replaceUsesOfWith(RetVal,
C);
755 FnChanged |= BBChanged;
765 LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
766 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.
void push_back(const T &Elt)
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.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * getPointerOperand(Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
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...
ConstantRange unionWith(const ConstantRange &CR) const
Return the range that results from the union of this range with another range.
unsigned arg_size() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Compute iterated dominance frontiers using a linear time algorithm.
BinaryOps getOpcode() const
Wrapper around LazyValueInfo.
This is the interface for a simple mod/ref and alias analysis over globals.
Value * getCondition() const
iterator_range< IterTy > args() const
const Value * getTrueValue() const
CaseIt case_begin()
Returns a read/write iterator that points to the first case in the SwitchInst.
LLVMContext & getContext() const
All values hold a context through their type.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
bool isVectorTy() const
True if this is an instance of VectorType.
const SimplifyQuery getBestSimplifyQuery(Pass &, Function &)
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.
AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void deleteEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge deletion and update the tree.
This file contains the simple types necessary to represent the attributes associated with functions a...
InstrTy * getInstruction() const
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
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 T & getValue() const LLVM_LVALUE_FUNCTION
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the call or the callee has the given attribute.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
DominatorTree & flush()
Flushes all pending updates and block deletions.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
Value * getOperand(unsigned i) const
Class to represent pointers.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i_nocapture) const
const BasicBlock & getEntryBlock() const
Pass * createCorrelatedValuePropagationPass()
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
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.
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.
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...
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.
Interval::pred_iterator pred_end(Interval *I)
CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DeferredDominance *DDT=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
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.
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.
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 ...
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
bool isEmptySet() const
Return true if this set contains no members.
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 ...
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
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.
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.
Class to defer updates to a DominatorTree.
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
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.
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.
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
iterator_range< df_iterator< T > > depth_first(const T &G)
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
This pass computes, caches, and vends lazy value constraint information.
static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Return the largest range containing all X such that "X BinOpC Y" is guaranteed not to wrap (overflow)...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
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.
AttributeList getAttributes() const
Get the parameter attributes of the call.
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.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const