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(NumOverflows,
"Number of overflow checks removed");
95 "Value Propagation",
false,
false)
103 return new CorrelatedValuePropagation();
108 if (isa<Constant>(S->
getOperand(0)))
return false;
111 if (!C)
return false;
114 if (!CI)
return false;
144 Value *CommonValue =
nullptr;
147 if (
auto *IncomingConstant = dyn_cast<Constant>(Incoming)) {
148 IncomingConstants.
push_back(std::make_pair(IncomingConstant, i));
149 }
else if (!CommonValue) {
151 CommonValue = Incoming;
152 }
else if (Incoming != CommonValue) {
158 if (!CommonValue || IncomingConstants.
empty())
163 if (
auto *CommonInst = dyn_cast<Instruction>(CommonValue))
170 for (
auto &IncomingConstant : IncomingConstants) {
187 bool Changed =
false;
192 if (isa<Constant>(Incoming))
continue;
208 if (
C->isOneValue()) {
210 }
else if (
C->isZeroValue()) {
256 Value *Pointer =
nullptr;
257 if (
LoadInst *L = dyn_cast<LoadInst>(I))
258 Pointer = L->getPointerOperand();
262 if (isa<Constant>(Pointer))
return false;
265 if (!C)
return false;
318 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->
getParent() == BB)
323 if (PB == PE)
return false;
326 bool Changed =
false;
329 SuccessorsCount[Succ]++;
357 if (Value != State) {
376 if (--SuccessorsCount[Succ] == 0)
409 BinOp, RRange, NoWrapKind);
425 return NoWrap(Instruction::Sub, OBO::NoUnsignedWrap);
427 return NoWrap(Instruction::Sub, OBO::NoSignedWrap);
434 Value *NewOp =
nullptr;
508 Instr->
getOpcode() == Instruction::URem);
521 unsigned NewWidth = std::max<unsigned>(
525 if (NewWidth >= OrigWidth)
531 auto *LHS =
B.CreateTruncOrBitCast(Instr->
getOperand(0), TruncTy,
532 Instr->
getName() +
".lhs.trunc");
533 auto *RHS =
B.CreateTruncOrBitCast(Instr->
getOperand(1), TruncTy,
534 Instr->
getName() +
".rhs.trunc");
536 auto *Zext =
B.CreateZExt(BO, Instr->
getType(), Instr->
getName() +
".zext");
537 if (
auto *BinOp = dyn_cast<BinaryOperator>(BO))
538 if (BinOp->getOpcode() == Instruction::UDiv)
539 BinOp->setIsExact(Instr->
isExact());
576 BO->setIsExact(SDI->
isExact());
599 BO->setIsExact(SDI->
isExact());
631 auto LazyRRange = [&] () {
637 bool Changed =
false;
642 bool NewNUW = NUWRange.
contains(LazyRRange());
651 bool NewNSW = NSWRange.
contains(LazyRRange());
667 if (!
C)
return nullptr;
671 if (!Op1)
return nullptr;
685 bool FnChanged =
false;
692 bool BBChanged =
false;
699 case Instruction::PHI:
700 BBChanged |=
processPHI(cast<PHINode>(II), LVI, DT, SQ);
702 case Instruction::ICmp:
703 case Instruction::FCmp:
704 BBChanged |=
processCmp(cast<CmpInst>(II), LVI);
711 case Instruction::Invoke:
714 case Instruction::SRem:
715 BBChanged |=
processSRem(cast<BinaryOperator>(II), LVI);
717 case Instruction::SDiv:
718 BBChanged |=
processSDiv(cast<BinaryOperator>(II), LVI);
720 case Instruction::UDiv:
721 case Instruction::URem:
724 case Instruction::AShr:
725 BBChanged |=
processAShr(cast<BinaryOperator>(II), LVI);
728 BBChanged |=
processAdd(cast<BinaryOperator>(II), LVI);
735 case Instruction::Switch:
739 auto *RI = cast<ReturnInst>(Term);
743 auto *RetVal = RI->getReturnValue();
745 if (isa<Constant>(RetVal))
break;
748 RI->replaceUsesOfWith(RetVal,
C);
754 FnChanged |= BBChanged;
764 LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
765 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.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
static IntegerType * getInt1Ty(LLVMContext &C)
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.
This class represents lattice values for constants.
BinaryOps getOpcode() const
Wrapper around LazyValueInfo.
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 push_back(const T &Elt)
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.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
InstrTy * getInstruction() const
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
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.
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.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
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.
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.
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...
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.
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.
void deleteEdge(BasicBlock *From, BasicBlock *To)
Notify all available trees on an edge deletion.
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.
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.
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(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.
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