49 #define DEBUG_TYPE "reassociate"
51 STATISTIC(NumChanged,
"Number of insts reassociated");
52 STATISTIC(NumAnnihil,
"Number of expr tree annihilated");
53 STATISTIC(NumFactor ,
"Number of multiplies factored");
61 << *Ops[0].
Op->getType() <<
'\t';
62 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
64 Ops[i].Op->printAsOperand(
dbgs(),
false, M);
65 dbgs() <<
", #" << Ops[i].Rank <<
"] ";
82 bool isInvalid()
const {
return SymbolicPart ==
nullptr; }
96 unsigned SymbolicRank;
101 assert(!isa<ConstantInt>(V) &&
"No ConstantInt");
106 if (I && (I->
getOpcode() == Instruction::Or ||
117 isOr = (I->
getOpcode() == Instruction::Or);
131 if (V->
hasOneUse() && isa<Instruction>(V) &&
132 cast<Instruction>(V)->getOpcode() == Opcode &&
133 (!isa<FPMathOperator>(V) ||
134 cast<Instruction>(V)->hasUnsafeAlgebra()))
135 return cast<BinaryOperator>(V);
141 if (V->
hasOneUse() && isa<Instruction>(V) &&
142 (cast<Instruction>(V)->getOpcode() == Opcode1 ||
143 cast<Instruction>(V)->getOpcode() == Opcode2) &&
144 (!isa<FPMathOperator>(V) ||
145 cast<Instruction>(V)->hasUnsafeAlgebra()))
146 return cast<BinaryOperator>(V);
150 void ReassociatePass::BuildRankMap(
Function &
F,
156 ValueRankMap[&*
I] = ++i;
157 DEBUG(
dbgs() <<
"Calculated Rank[" <<
I->getName() <<
"] = " << i <<
"\n");
162 unsigned BBRank = RankMap[BB] = ++i << 16;
169 ValueRankMap[&
I] = ++BBRank;
173 unsigned ReassociatePass::getRank(
Value *V) {
176 if (isa<Argument>(V))
return ValueRankMap[V];
180 if (
unsigned Rank = ValueRankMap[I])
187 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
188 for (
unsigned i = 0, e = I->getNumOperands();
189 i != e && Rank != MaxRank; ++i)
190 Rank =
std::max(Rank, getRank(I->getOperand(i)));
198 DEBUG(
dbgs() <<
"Calculated Rank[" << V->
getName() <<
"] = " << Rank <<
"\n");
200 return ValueRankMap[
I] = Rank;
204 void ReassociatePass::canonicalizeOperands(
Instruction *I) {
205 assert(isa<BinaryOperator>(I) &&
"Expected binary operator.");
210 unsigned LHSRank = getRank(LHS);
211 unsigned RHSRank = getRank(RHS);
213 if (isa<Constant>(RHS))
216 if (isa<Constant>(LHS) || RHSRank < LHSRank)
217 cast<BinaryOperator>(
I)->swapOperands();
226 BinaryOperator::CreateFAdd(S1, S2, Name, InsertBefore);
238 BinaryOperator::CreateFMul(S1, S2, Name, InsertBefore);
264 Neg->replaceAllUsesWith(Res);
309 assert(LHS == 1 && RHS == 1 &&
"Weights not reduced!");
314 assert(LHS == 1 && RHS == 1 &&
"Weights not reduced!");
324 assert((Opcode == Instruction::Mul || Opcode == Instruction::FMul) &&
325 "Unknown associative operation!");
341 assert(LHS.
ult(Threshold) && RHS.
ult(Threshold) &&
"Weights not reduced!");
344 while (LHS.uge(Threshold))
352 "Weights not reduced!");
354 while (Total >= Threshold)
438 DEBUG(
dbgs() <<
"LINEARIZE: " << *I <<
'\n');
442 "Expected an associative and commutative operation!");
456 bool Changed =
false;
480 while (!Worklist.empty()) {
481 std::pair<BinaryOperator*, APInt>
P = Worklist.pop_back_val();
484 for (
unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) {
486 APInt Weight = P.second;
487 DEBUG(
dbgs() <<
"OPERAND: " << *Op <<
" (" << Weight <<
")\n");
493 assert(Visited.
insert(Op).second &&
"Not first visit!");
494 DEBUG(
dbgs() <<
"DIRECT ADD: " << *Op <<
" (" << Weight <<
")\n");
495 Worklist.push_back(std::make_pair(BO, Weight));
500 LeafMap::iterator It = Leaves.find(Op);
501 if (It == Leaves.end()) {
503 assert(Visited.
insert(Op).second &&
"Not first visit!");
507 DEBUG(
dbgs() <<
"ADD USES LEAF: " << *Op <<
" (" << Weight <<
")\n");
516 "In leaf map but not visited!");
521 #if 0 // TODO: Re-enable once PR13021 is fixed.
533 DEBUG(
dbgs() <<
"UNLEAF: " << *Op <<
" (" << It->second <<
")\n");
534 Worklist.push_back(std::make_pair(BO, It->second));
554 assert((!isa<Instruction>(Op) ||
555 cast<Instruction>(Op)->getOpcode() != Opcode
556 || (isa<FPMathOperator>(Op) &&
557 !cast<Instruction>(Op)->hasUnsafeAlgebra())) &&
558 "Should have been handled above!");
566 DEBUG(
dbgs() <<
"MORPH LEAF: " << *Op <<
" (" << Weight <<
") TO ");
569 Worklist.push_back(std::make_pair(BO, Weight));
576 DEBUG(
dbgs() <<
"ADD LEAF: " << *Op <<
" (" << Weight <<
")\n");
585 for (
unsigned i = 0, e = LeafOrder.
size(); i != e; ++i) {
586 Value *V = LeafOrder[i];
587 LeafMap::iterator It = Leaves.find(V);
588 if (It == Leaves.end())
592 APInt Weight = It->second;
598 Ops.
push_back(std::make_pair(V, Weight));
606 assert(Identity &&
"Associative operation without identity!");
617 assert(Ops.
size() > 1 &&
"Single values should be used directly!");
645 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
646 NotRewritable.
insert(Ops[i].Op);
652 for (
unsigned i = 0; ; ++i) {
656 if (i+2 == Ops.
size()) {
657 Value *NewLHS = Ops[i].Op;
658 Value *NewRHS = Ops[i+1].Op;
662 if (NewLHS == OldLHS && NewRHS == OldRHS)
666 if (NewLHS == OldRHS && NewRHS == OldLHS) {
679 if (NewLHS != OldLHS) {
681 if (BO && !NotRewritable.
count(BO))
682 NodesToRewrite.push_back(BO);
685 if (NewRHS != OldRHS) {
687 if (BO && !NotRewritable.
count(BO))
688 NodesToRewrite.push_back(BO);
693 ExpressionChanged =
Op;
702 Value *NewRHS = Ops[i].Op;
712 if (BO && !NotRewritable.
count(BO))
713 NodesToRewrite.push_back(BO);
715 ExpressionChanged =
Op;
726 if (BO && !NotRewritable.
count(BO)) {
739 if (NodesToRewrite.empty()) {
742 Undef, Undef,
"", I);
743 if (NewOp->getType()->isFPOrFPVectorTy())
746 NewOp = NodesToRewrite.pop_back_val();
752 ExpressionChanged =
Op;
762 if (ExpressionChanged)
765 if (isa<FPMathOperator>(I)) {
772 if (ExpressionChanged == I)
775 ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->
user_begin());
779 for (
unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
780 RedoInsts.insert(NodesToRewrite[i]);
792 if (
Constant *
C = dyn_cast<Constant>(V)) {
793 if (
C->getType()->isFPOrFPVectorTy()) {
850 if (
Instruction *InstInput = dyn_cast<Instruction>(V)) {
851 if (
InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
852 InsertPt = II->getNormalDest()->begin();
854 InsertPt = ++InstInput->getIterator();
856 while (isa<PHINode>(InsertPt)) ++InsertPt;
861 if (TheNeg->
getOpcode() == Instruction::Sub) {
867 ToRedo.insert(TheNeg);
874 ToRedo.insert(NewNeg);
924 Sub->replaceAllUsesWith(New);
925 New->setDebugLoc(Sub->getDebugLoc());
927 DEBUG(
dbgs() <<
"Negated: " << *New <<
'\n');
949 bool NSW = cast<BinaryOperator>(Shl)->hasNoSignedWrap();
950 bool NUW = cast<BinaryOperator>(Shl)->hasNoUnsignedWrap();
962 unsigned XRank = Ops[i].Rank;
963 unsigned e = Ops.
size();
964 for (
unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) {
967 if (
Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
969 if (I1->isIdenticalTo(I2))
973 for (
unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) {
976 if (
Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
978 if (I1->isIdenticalTo(I2))
988 if (Ops.
size() == 1)
return Ops.
back();
1008 for (
unsigned i = 0, e = Tree.
size(); i != e; ++i) {
1010 Factors.
append(E.second.getZExtValue(),
1014 bool FoundFactor =
false;
1015 bool NeedsNegate =
false;
1016 for (
unsigned i = 0, e = Factors.
size(); i != e; ++i) {
1017 if (Factors[i].Op == Factor) {
1024 if (
ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor)) {
1025 if (
ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
1026 if (FC1->getValue() == -FC2->getValue()) {
1027 FoundFactor = NeedsNegate =
true;
1031 }
else if (
ConstantFP *FC1 = dyn_cast<ConstantFP>(Factor)) {
1032 if (
ConstantFP *FC2 = dyn_cast<ConstantFP>(Factors[i].Op)) {
1033 const APFloat &F1 = FC1->getValueAPF();
1034 APFloat F2(FC2->getValueAPF());
1037 FoundFactor = NeedsNegate =
true;
1047 RewriteExprTree(BO, Factors);
1055 if (Factors.
size() == 1) {
1056 RedoInsts.insert(BO);
1059 RewriteExprTree(BO, Factors);
1064 V =
CreateNeg(V,
"neg", &*InsertPt, BO);
1093 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1100 if (Opcode == Instruction::And)
1103 if (Opcode == Instruction::Or)
1111 if (i+1 != Ops.
size() && Ops[i+1].Op == Ops[i].Op) {
1112 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
1121 assert(Opcode == Instruction::Xor);
1140 const APInt &ConstOpnd) {
1174 if (C1 != ConstOpnd)
1183 RedoInsts.insert(
T);
1204 int DeadInstNum = 1;
1222 APInt C3((~C1) ^ C2);
1225 if (!C3.isNullValue() && !C3.isAllOnesValue()) {
1227 if (NewInstNum > DeadInstNum)
1244 if (NewInstNum > DeadInstNum)
1262 RedoInsts.insert(
T);
1264 RedoInsts.insert(
T);
1277 if (Ops.
size() == 1)
1282 Type *Ty = Ops[0].Op->getType();
1286 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1287 Value *V = Ops[i].Op;
1294 O.setSymbolicRank(getRank(O.getSymbolicPart()));
1304 for (
unsigned i = 0, e = Opnds.
size(); i != e; ++i)
1320 std::stable_sort(OpndPtrs.
begin(), OpndPtrs.
end(),
1327 bool Changed =
false;
1328 for (
unsigned i = 0, e = Opnds.
size(); i < e; i++) {
1329 XorOpnd *CurrOpnd = OpndPtrs[i];
1335 CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
1345 if (!PrevOpnd || CurrOpnd->
getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
1346 PrevOpnd = CurrOpnd;
1353 if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
1358 PrevOpnd = CurrOpnd;
1370 for (
unsigned int i = 0, e = Opnds.
size(); i < e; i++) {
1382 unsigned Sz = Ops.
size();
1404 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1405 Value *TheOp = Ops[i].Op;
1409 if (i+1 != Ops.
size() && Ops[i+1].Op == TheOp) {
1411 unsigned NumFound = 0;
1415 }
while (i != Ops.
size() && Ops[i].Op == TheOp);
1417 DEBUG(
dbgs() <<
"\nFACTORING [" << NumFound <<
"]: " << *TheOp <<
'\n');
1429 RedoInsts.insert(Mul);
1461 if (Ops.
size() == 2 &&
1496 unsigned MaxOcc = 0;
1497 Value *MaxOccVal =
nullptr;
1498 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1507 assert(Factors.
size() > 1 &&
"Bad linearize!");
1511 for (
unsigned i = 0, e = Factors.
size(); i != e; ++i) {
1512 Value *Factor = Factors[i];
1513 if (!Duplicates.insert(Factor).second)
1516 unsigned Occ = ++FactorOccurrences[Factor];
1525 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Factor)) {
1526 if (CI->isNegative() && !CI->isMinValue(
true)) {
1528 if (!Duplicates.insert(Factor).second)
1530 unsigned Occ = ++FactorOccurrences[Factor];
1536 }
else if (
ConstantFP *CF = dyn_cast<ConstantFP>(Factor)) {
1537 if (CF->isNegative()) {
1541 if (!Duplicates.insert(Factor).second)
1543 unsigned Occ = ++FactorOccurrences[Factor];
1555 DEBUG(
dbgs() <<
"\nFACTORING [" << MaxOcc <<
"]: " << *MaxOccVal <<
'\n');
1568 for (
unsigned i = 0; i != Ops.
size(); ++i) {
1575 if (
Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
1578 for (
unsigned j = Ops.
size(); j != i;) {
1580 if (Ops[j].Op == Ops[i].Op) {
1592 unsigned NumAddedValues = NewMulOps.
size();
1598 assert(NumAddedValues > 1 &&
"Each occurrence should contribute a value");
1599 (void)NumAddedValues;
1601 RedoInsts.insert(
VI);
1608 RedoInsts.insert(V2);
1639 unsigned FactorPowerSum = 0;
1640 for (
unsigned Idx = 1,
Size = Ops.
size(); Idx <
Size; ++Idx) {
1641 Value *Op = Ops[Idx-1].Op;
1645 for (; Idx < Size && Ops[Idx].Op ==
Op; ++Idx)
1649 FactorPowerSum += Count;
1656 if (FactorPowerSum < 4)
1661 for (
unsigned Idx = 1; Idx < Ops.
size(); ++Idx) {
1662 Value *Op = Ops[Idx-1].Op;
1666 for (; Idx < Ops.
size() && Ops[Idx].Op ==
Op; ++Idx)
1673 FactorPowerSum += Count;
1680 assert(FactorPowerSum >= 4);
1682 std::stable_sort(Factors.
begin(), Factors.
end(),
1683 [](
const Factor &LHS,
const Factor &RHS) {
1684 return LHS.
Power > RHS.Power;
1692 if (Ops.
size() == 1)
1701 }
while (!Ops.
empty());
1713 ReassociatePass::buildMinimalMultiplyDAG(
IRBuilder<> &Builder,
1715 assert(Factors[0].Power);
1717 for (
unsigned LastIdx = 0, Idx = 1,
Size = Factors.
size();
1718 Idx <
Size && Factors[Idx].Power > 0; ++Idx) {
1719 if (Factors[Idx].Power != Factors[LastIdx].Power) {
1730 InnerProduct.
push_back(Factors[Idx].Base);
1732 }
while (Idx <
Size && Factors[Idx].Power == Factors[LastIdx].Power);
1738 RedoInsts.insert(
MI);
1745 [](
const Factor &LHS,
const Factor &RHS) {
1746 return LHS.
Power == RHS.Power;
1753 for (
unsigned Idx = 0,
Size = Factors.
size(); Idx !=
Size; ++Idx) {
1754 if (Factors[Idx].Power & 1)
1755 OuterProduct.
push_back(Factors[Idx].Base);
1756 Factors[Idx].Power >>= 1;
1758 if (Factors[0].Power) {
1759 Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1763 if (OuterProduct.
size() == 1)
1764 return OuterProduct.
front();
1788 if (
auto FPI = dyn_cast<FPMathOperator>(I))
1791 Value *V = buildMinimalMultiplyDAG(Builder, Factors);
1796 Ops.
insert(std::lower_bound(Ops.
begin(), Ops.
end(), NewEntry), NewEntry);
1806 while (!Ops.
empty() && isa<Constant>(Ops.
back().
Op)) {
1823 if (Ops.
size() == 1)
return Ops[0].Op;
1827 unsigned NumOps = Ops.
size();
1830 case Instruction::And:
1831 case Instruction::Or:
1836 case Instruction::Xor:
1837 if (
Value *Result = OptimizeXor(I, Ops))
1842 case Instruction::FAdd:
1843 if (
Value *Result = OptimizeAdd(I, Ops))
1847 case Instruction::Mul:
1848 case Instruction::FMul:
1849 if (
Value *Result = OptimizeMul(I, Ops))
1854 if (Ops.
size() != NumOps)
1855 return OptimizeExpression(I, Ops);
1861 void ReassociatePass::RecursivelyEraseDeadInsts(
1865 ValueRankMap.
erase(I);
1867 RedoInsts.remove(I);
1870 if (
Instruction *OpInst = dyn_cast<Instruction>(Op))
1871 if (OpInst->use_empty())
1882 ValueRankMap.
erase(I);
1883 RedoInsts.remove(I);
1887 for (
unsigned i = 0, e = Ops.size(); i != e; ++i)
1888 if (
Instruction *Op = dyn_cast<Instruction>(Ops[i])) {
1891 unsigned Opcode = Op->getOpcode();
1892 while (Op->hasOneUse() && Op->user_back()->getOpcode() == Opcode &&
1893 Visited.
insert(Op).second)
1894 Op = Op->user_back();
1895 RedoInsts.insert(Op);
1910 if (Opcode != Instruction::FMul && Opcode != Instruction::FDiv)
1932 if (!isa<BinaryOperator>(User) || User->
use_empty())
1935 unsigned UserOpcode = User->
getOpcode();
1936 if (UserOpcode != Instruction::FAdd && UserOpcode != Instruction::FSub)
1958 cast<BinaryOperator>(User)->swapOperands();
1963 switch (UserOpcode) {
1966 case Instruction::FAdd:
1967 NI = BinaryOperator::CreateFSub(Op0, Op1);
1970 case Instruction::FSub:
1971 NI = BinaryOperator::CreateFAdd(Op0, Op1);
1980 RedoInsts.insert(I);
1987 void ReassociatePass::OptimizeInst(
Instruction *I) {
1989 if (!isa<BinaryOperator>(I))
2000 RedoInsts.insert(I);
2006 if (
Instruction *Res = canonicalizeNegConstExpr(I))
2013 canonicalizeOperands(I);
2030 if (I->
getOpcode() == Instruction::Sub) {
2033 RedoInsts.insert(I);
2045 for (User *U : NI->
users()) {
2047 RedoInsts.insert(Tmp);
2049 RedoInsts.insert(I);
2054 }
else if (I->
getOpcode() == Instruction::FSub) {
2057 RedoInsts.insert(I);
2069 for (User *U : NI->
users()) {
2071 RedoInsts.insert(Tmp);
2073 RedoInsts.insert(I);
2100 cast<Instruction>(BO->
user_back())->getOpcode() == Instruction::Sub)
2103 cast<Instruction>(BO->
user_back())->getOpcode() == Instruction::FSub)
2106 ReassociateExpression(BO);
2116 for (
unsigned i = 0, e = Tree.
size(); i != e; ++i) {
2118 Ops.
append(E.second.getZExtValue(),
2130 std::stable_sort(Ops.
begin(), Ops.
end());
2134 if (
Value *V = OptimizeExpression(I, Ops)) {
2140 DEBUG(
dbgs() <<
"Reassoc to scalar: " << *V <<
'\n');
2144 RedoInsts.insert(I);
2154 if (I->
getOpcode() == Instruction::Mul &&
2156 isa<ConstantInt>(Ops.
back().
Op) &&
2157 cast<ConstantInt>(Ops.
back().
Op)->isMinusOne()) {
2160 }
else if (I->
getOpcode() == Instruction::FMul &&
2161 cast<Instruction>(I->
user_back())->getOpcode() ==
2162 Instruction::FAdd &&
2163 isa<ConstantFP>(Ops.
back().
Op) &&
2164 cast<ConstantFP>(Ops.
back().
Op)->isExactlyValue(-1.0)) {
2172 if (Ops.
size() == 1) {
2180 if (
Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
2182 RedoInsts.insert(I);
2188 RewriteExprTree(I, Ops);
2199 BuildRankMap(F, RPOT);
2204 assert(RankMap.count(&*BI) &&
"BB should be ranked.");
2211 assert(II->getParent() == &*BI &&
"Moved to a different block!");
2222 while (!ToRedo.
empty()) {
2225 RecursivelyEraseDeadInsts(I, ToRedo);
2232 while (!RedoInsts.empty()) {
2243 ValueRankMap.clear();
2264 bool runOnFunction(
Function &F)
override {
2265 if (skipFunction(F))
2269 auto PA = Impl.run(F, DummyFAM);
2270 return !PA.areAllPreserved();
2282 "Reassociate expressions",
false,
false)
2286 return new ReassociateLegacyPass();
Legacy wrapper pass to provide the GlobalsAAResult object.
static void FindSingleUseMultiplyFactors(Value *V, SmallVectorImpl< Value * > &Factors)
If V is a single-use multiply, recursively add its operands as factors, otherwise add V to the list o...
bool isNilpotent() const
Return true if the instruction is nilpotent:
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
uint64_t getZExtValue() const
Get zero extended value.
STATISTIC(NumFunctions,"Total number of functions")
LLVM_NODISCARD T pop_back_val()
static BinaryOperator * LowerNegateToMultiply(Instruction *Neg)
Replace 0-X with X*-1.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
Utility class representing a non-constant Xor-operand.
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty)
Return the identity for the given binary operation, i.e.
Utility class representing a base and exponent pair which form one factor of some product...
void deleteValue()
Delete a pointer to a generic Value.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
const Function * getParent() const
Return the enclosing method, or null if none.
static unsigned FindInOperandList(const SmallVectorImpl< ValueEntry > &Ops, unsigned i, Value *X)
Scan backwards and forwards among values with the same rank as element i to see if X exists...
void reserve(size_type N)
Reassociate commutative expressions.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
bool swapOperands()
Exchange the two operands to this instruction.
bool match(Val *V, const Pattern &P)
static const Value * getNegArgument(const Value *BinOp)
Helper functions to extract the unary argument of a NEG, FNEG or NOT operation implemented via Sub...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
static bool collectMultiplyFactors(SmallVectorImpl< ValueEntry > &Ops, SmallVectorImpl< Factor > &Factors)
Build up a vector of value/power pairs factoring a product.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
FunctionPass * createReassociatePass()
static BinaryOperator * BreakUpSubtract(Instruction *Sub, SetVector< AssertingVH< Instruction >> &ToRedo)
If we have (X-Y), and if either X is an add, or if this is only used by an add, transform this into (...
void setName(const Twine &Name)
Change the name of the value.
LLVM_NODISCARD bool empty() const
bool getBoolValue() const
Convert APInt to a boolean value.
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
static Value * OptimizeAndOrXor(unsigned Opcode, SmallVectorImpl< ValueEntry > &Ops)
Optimize a series of operands to an 'and', 'or', or 'xor' instruction.
std::pair< Value *, APInt > RepeatedValue
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
bool hasUnsafeAlgebra() const
Determine whether the unsafe-algebra flag is set.
bool empty() const
Determine if the SetVector is empty or not.
static Value * createAndInstr(Instruction *InsertBefore, Value *Opnd, const APInt &ConstOpnd)
Helper function of CombineXorOpnd().
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
const char * getOpcodeName() const
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
static const Value * getNotArgument(const Value *BinOp)
Value * getSymbolicPart() const
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
static Constant * getFNeg(Constant *C)
A set of analyses that are preserved following a run of a transformation pass.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
static Value * buildMultiplyTree(IRBuilder<> &Builder, SmallVectorImpl< Value * > &Ops)
Build a tree of multiplies, computing the product of Ops.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
bool isVectorTy() const
True if this is an instance of VectorType.
static Value * EmitAddTreeOfValues(Instruction *I, SmallVectorImpl< WeakTrackingVH > &Ops)
Emit a tree of add instructions, summing Ops together and returning the result.
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
This file contains the declarations for the subclasses of Constant, which represent the different fla...
ConstantFP - Floating Point Values [float, double].
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
Represent the analysis usage information of a pass.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
Analysis pass providing a never-invalidated alias analysis result.
unsigned getBitWidth() const
Return the number of bits in the APInt.
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
bool isCommutative() const
Return true if the instruction is commutative:
static bool isNot(const Value *V)
self_iterator getIterator()
static Constant * getAllOnesValue(Type *Ty)
Get the all ones value.
NUW NUW NUW NUW Exact static Exact BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVMContext & getContext() const
All values hold a context through their type.
static unsigned CarmichaelShift(unsigned Bitwidth)
Returns k such that lambda(2^Bitwidth) = 2^k, where lambda is the Carmichael function.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void dump() const
Support for debugging, callable in GDB: V->dump()
unsigned getSymbolicRank() const
BinaryOps getOpcode() const
static BinaryOperator * CreateFNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
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.
INITIALIZE_PASS(ReassociateLegacyPass,"reassociate","Reassociate expressions", false, false) FunctionPass *llvm
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.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static Value * NegateValue(Value *V, Instruction *BI, SetVector< AssertingVH< Instruction >> &ToRedo)
Insert instructions before the instruction pointed to by BI, that computes the negative version of th...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
const APInt & getConstPart() const
LLVM_NODISCARD T pop_back_val()
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.
void setSymbolicRank(unsigned R)
void setPreservesCFG()
This function should be called by the pass, iff they do not:
const BasicBlock & getEntryBlock() const
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Value handle that asserts if the Value is deleted.
void setOperand(unsigned i, Value *Val)
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.
static bool isNeg(const Value *V)
Check if the given Value is a NEG, FNeg, or NOT instruction.
Class for arbitrary precision integers.
bool isIntegerTy() const
True if this is an instance of IntegerType.
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()
Represents analyses that only rely on functions' control flow.
iterator insert(iterator I, T &&Elt)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
bool isMinValue() const
Determine if this is the smallest unsigned value.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
static std::vector< std::string > Flags
bool isAllOnesValue() const
Determine if all bits are set.
bool isNegative() const
Return true if the sign bit is set.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
iterator insert(iterator where, pointer New)
void emplace_back(ArgTypes &&...Args)
bool mayBeMemoryDependent(const Instruction &I)
Returns true if the result or effects of the given instructions I depend on or influence global memor...
static bool isFNeg(const Value *V, bool IgnoreZeroSign=false)
void preserveSet()
Mark an analysis set as preserved.
bool isIdempotent() const
Return true if the instruction is idempotent:
static void PrintOps(Instruction *I, const SmallVectorImpl< ValueEntry > &Ops)
Print out the expression identified in the Ops list.
static void IncorporateWeight(APInt &LHS, const APInt &RHS, unsigned Opcode)
Add the extra weight 'RHS' to the existing weight 'LHS', reducing the combined weight using any speci...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
void preserve()
Mark an analysis as preserved.
static BinaryOperator * CreateNeg(Value *S1, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
const APFloat & getValueAPF() const
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
static BinaryOperator * ConvertShiftToMul(Instruction *Shl)
If this is a shift of a reassociable multiply or is used by one, change this into a multiply by a con...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
void initializeReassociateLegacyPassPass(PassRegistry &)
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
A vector that has set insertion semantics.
void clearSubclassOptionalData()
Clear the optional flags contained in this value.
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
static BinaryOperator * isReassociableOp(Value *V, unsigned Opcode)
Return true if V is an instruction of the specified opcode and if it only has one use...
cmpResult compare(const APFloat &RHS) const
Convenience struct for specifying and reasoning about fast-math flags.
A container for analyses that lazily runs them and caches their results.
bool isNullValue() const
Determine if all bits are clear.
static bool ShouldBreakUpSubtract(Instruction *Sub)
Return true if we should break up this subtract of X-Y into (X + -Y).
static APInt getNullValue(unsigned numBits)
Get the '0' value.
static BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
Value * CreateFMul(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
static Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty)
Return the absorbing element for the given binary operation, i.e.
static bool LinearizeExprTree(BinaryOperator *I, SmallVectorImpl< RepeatedValue > &Ops)
Given an associative binary expression, return the leaf nodes in Ops along with their weights (how ma...
const BasicBlock * getParent() const
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)