52#define DEBUG_TYPE "instcombine"
55 "Negator: Number of negations attempted to be sinked");
57 "Negator: Number of negations successfully sinked");
58STATISTIC(NegatorMaxDepthVisited,
"Negator: Maximal traversal depth ever "
59 "reached while attempting to sink negation");
61 "Negator: How many times did the traversal depth limit was reached "
64 NegatorNumValuesVisited,
65 "Negator: Total number of values visited during attempts to sink negation");
67 "Negator: How many negations did we retrieve/reuse from cache");
69 "Negator: Maximal number of values ever visited while attempting to "
72 "Negator: Number of new negated instructions created, total");
74 "Negator: Maximal number of new instructions created during negation "
77 "Negator: Number of new negated instructions created in successful "
78 "negation sinking attempts");
81 "Controls Negator transformations in InstCombine pass");
85 cl::desc(
"Should we attempt to sink negations?"));
90 cl::desc(
"What is the maximal lookup depth when trying to "
91 "check for viability of negation sinking."));
94 bool IsTrulyNegation_)
97 ++NegatorNumInstructionsCreatedTotal;
98 NewInstructions.push_back(
I);
100 DT(DT_), IsTrulyNegation(IsTrulyNegation_) {}
104 NegatorMaxTotalValuesVisited.updateMax(NumValuesVisitedInThisNegator);
112std::array<Value *, 2> Negator::getSortedOperandsOfBinOp(
Instruction *
I) {
113 assert(
I->getNumOperands() == 2 &&
"Only for binops!");
114 std::array<Value *, 2> Ops{
I->getOperand(0),
I->getOperand(1)};
123[[nodiscard]]
Value *Negator::visitImpl(
Value *V,
bool IsNSW,
unsigned Depth) {
129 if (
V->getType()->isIntOrIntVectorTy(1))
144 if (!isa<Instruction>(V))
150 if (!
V->hasOneUse() && !IsTrulyNegation)
153 auto *
I = cast<Instruction>(V);
154 unsigned BitWidth =
I->getType()->getScalarSizeInBits();
164 switch (
I->getOpcode()) {
165 case Instruction::Add: {
166 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(
I);
169 return Builder.
CreateNot(Ops[0],
I->getName() +
".neg");
172 case Instruction::Xor:
175 return Builder.
CreateAdd(
X, ConstantInt::get(
X->getType(), 1),
176 I->getName() +
".neg");
178 case Instruction::AShr:
179 case Instruction::LShr: {
183 Value *BO =
I->getOpcode() == Instruction::AShr
184 ? Builder.
CreateLShr(
I->getOperand(0),
I->getOperand(1))
185 : Builder.
CreateAShr(
I->getOperand(0),
I->getOperand(1));
186 if (
auto *NewInstr = dyn_cast<Instruction>(BO)) {
187 NewInstr->copyIRFlags(
I);
188 NewInstr->
setName(
I->getName() +
".neg");
198 case Instruction::SExt:
199 case Instruction::ZExt:
201 if (
I->getOperand(0)->getType()->isIntOrIntVectorTy(1))
202 return I->getOpcode() == Instruction::SExt
204 I->getName() +
".neg")
206 I->getName() +
".neg");
208 case Instruction::Select: {
211 auto *Sel = cast<SelectInst>(
I);
217 return Builder.
CreateSelect(Sel->getCondition(), NegTrueC, NegFalseC,
218 I->getName() +
".neg",
I);
222 case Instruction::Call:
223 if (
auto *CI = dyn_cast<CmpIntrinsic>(
I); CI && CI->hasOneUse())
225 {CI->getRHS(), CI->getLHS()});
231 if (
I->getOpcode() == Instruction::Sub &&
236 return Builder.
CreateSub(
I->getOperand(1),
I->getOperand(0),
237 I->getName() +
".neg",
false,
238 IsNSW &&
I->hasNoSignedWrap());
246 switch (
I->getOpcode()) {
247 case Instruction::ZExt: {
251 unsigned SrcWidth =
SrcOp->getType()->getScalarSizeInBits();
252 const APInt &FullShift =
APInt(SrcWidth, SrcWidth - 1);
253 if (IsTrulyNegation &&
260 case Instruction::And: {
266 unsigned BW =
X->getType()->getScalarSizeInBits();
267 Constant *BWMinusOne = ConstantInt::get(
X->getType(), BW - 1);
274 case Instruction::SDiv:
278 if (
auto *Op1C = dyn_cast<Constant>(
I->getOperand(1))) {
279 if (!Op1C->containsUndefOrPoisonElement() &&
280 Op1C->isNotMinSignedValue() && Op1C->isNotOneValue()) {
283 I->getName() +
".neg");
284 if (
auto *NewInstr = dyn_cast<Instruction>(BO))
285 NewInstr->setIsExact(
I->isExact());
294 LLVM_DEBUG(
dbgs() <<
"Negator: reached maximal allowed traversal depth in "
295 << *V <<
". Giving up.\n");
296 ++NegatorTimesDepthLimitReached;
300 switch (
I->getOpcode()) {
301 case Instruction::Freeze: {
303 Value *NegOp = negate(
I->getOperand(0), IsNSW,
Depth + 1);
308 case Instruction::PHI: {
310 auto *
PHI = cast<PHINode>(
I);
312 for (
auto I :
zip(
PHI->incoming_values(), NegatedIncomingValues)) {
316 if (!(std::get<1>(
I) =
317 negate(std::get<0>(
I), IsNSW,
Depth + 1)))
322 PHI->getType(),
PHI->getNumOperands(),
PHI->getName() +
".neg");
323 for (
auto I :
zip(NegatedIncomingValues,
PHI->blocks()))
327 case Instruction::Select: {
332 auto *NewSelect = cast<SelectInst>(
I->clone());
334 NewSelect->swapValues();
336 NewSelect->setName(
I->getName() +
".neg");
337 Builder.
Insert(NewSelect);
341 Value *NegOp1 = negate(
I->getOperand(1), IsNSW,
Depth + 1);
344 Value *NegOp2 = negate(
I->getOperand(2), IsNSW,
Depth + 1);
348 return Builder.
CreateSelect(
I->getOperand(0), NegOp1, NegOp2,
349 I->getName() +
".neg",
I);
351 case Instruction::ShuffleVector: {
353 auto *Shuf = cast<ShuffleVectorInst>(
I);
354 Value *NegOp0 = negate(
I->getOperand(0), IsNSW,
Depth + 1);
357 Value *NegOp1 = negate(
I->getOperand(1), IsNSW,
Depth + 1);
361 I->getName() +
".neg");
363 case Instruction::ExtractElement: {
365 auto *EEI = cast<ExtractElementInst>(
I);
366 Value *NegVector = negate(EEI->getVectorOperand(), IsNSW,
Depth + 1);
370 I->getName() +
".neg");
372 case Instruction::InsertElement: {
375 auto *IEI = cast<InsertElementInst>(
I);
376 Value *NegVector = negate(IEI->getOperand(0), IsNSW,
Depth + 1);
379 Value *NegNewElt = negate(IEI->getOperand(1), IsNSW,
Depth + 1);
383 I->getName() +
".neg");
385 case Instruction::Trunc: {
387 Value *NegOp = negate(
I->getOperand(0),
false,
Depth + 1);
390 return Builder.
CreateTrunc(NegOp,
I->getType(),
I->getName() +
".neg");
392 case Instruction::Shl: {
394 IsNSW &=
I->hasNoSignedWrap();
395 if (
Value *NegOp0 = negate(
I->getOperand(0), IsNSW,
Depth + 1))
396 return Builder.
CreateShl(NegOp0,
I->getOperand(1),
I->getName() +
".neg",
405 I->getName() +
".neg",
false, IsNSW);
407 case Instruction::Or: {
408 if (!cast<PossiblyDisjointInst>(
I)->isDisjoint())
410 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(
I);
414 return Builder.
CreateNot(Ops[0],
I->getName() +
".neg");
418 case Instruction::Add: {
429 if (!IsTrulyNegation)
434 "Internal consistency check failed.");
436 if (NegatedOps.
size() == 2)
437 return Builder.
CreateAdd(NegatedOps[0], NegatedOps[1],
438 I->getName() +
".neg");
439 assert(IsTrulyNegation &&
"We should have early-exited then.");
441 if (NonNegatedOps.
size() == 2)
444 return Builder.
CreateSub(NegatedOps[0], NonNegatedOps[0],
445 I->getName() +
".neg");
447 case Instruction::Xor: {
448 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(
I);
451 if (
auto *
C = dyn_cast<Constant>(Ops[1])) {
452 if (IsTrulyNegation) {
455 I->getName() +
".neg");
460 case Instruction::Mul: {
461 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(
I);
463 Value *NegatedOp, *OtherOp;
466 if (
Value *NegOp1 = negate(Ops[1],
false,
Depth + 1)) {
469 }
else if (
Value *NegOp0 = negate(Ops[0],
false,
Depth + 1)) {
475 return Builder.
CreateMul(NegatedOp, OtherOp,
I->getName() +
".neg",
476 false, IsNSW &&
I->hasNoSignedWrap());
485[[nodiscard]]
Value *Negator::negate(
Value *V,
bool IsNSW,
unsigned Depth) {
486 NegatorMaxDepthVisited.updateMax(
Depth);
487 ++NegatorNumValuesVisited;
490 ++NumValuesVisitedInThisNegator;
495 Value *Placeholder =
reinterpret_cast<Value *
>(
static_cast<uintptr_t
>(-1));
499 auto NegationsCacheIterator = NegationsCache.find(V);
500 if (NegationsCacheIterator != NegationsCache.end()) {
501 ++NegatorNumNegationsFoundInCache;
502 Value *NegatedV = NegationsCacheIterator->second;
503 assert(NegatedV != Placeholder &&
"Encountered a cycle during negation.");
511 NegationsCache[
V] = Placeholder;
517 NegationsCache[
V] = NegatedV;
522[[nodiscard]] std::optional<Negator::Result> Negator::run(
Value *Root,
524 Value *Negated = negate(Root, IsNSW, 0);
529 I->eraseFromParent();
537 ++NegatorTotalNegationsAttempted;
538 LLVM_DEBUG(
dbgs() <<
"Negator: attempting to sink negation into " << *Root
546 std::optional<Result> Res =
N.run(Root, IsNSW);
548 LLVM_DEBUG(
dbgs() <<
"Negator: failed to sink negation into " << *Root
553 LLVM_DEBUG(
dbgs() <<
"Negator: successfully sunk negation into " << *Root
554 <<
"\n NEW: " << *Res->second <<
"\n");
555 ++NegatorNumTreesNegated;
567 <<
" instrs to InstCombine\n");
568 NegatorMaxInstructionsCreated.updateMax(Res->first.size());
569 NegatorNumInstructionsNegatedSuccess += Res->first.size();
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines the DenseMap class.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This defines the Use class.
This file provides internal interfaces used to implement the InstCombine.
static constexpr unsigned NegatorDefaultMaxDepth
static cl::opt< bool > NegatorEnabled("instcombine-negator-enabled", cl::init(true), cl::desc("Should we attempt to sink negations?"))
static cl::opt< unsigned > NegatorMaxDepth("instcombine-negator-max-depth", cl::init(NegatorDefaultMaxDepth), cl::desc("What is the maximal lookup depth when trying to " "check for viability of negation sinking."))
This file provides the interface for the instcombine pass implementation.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Class for arbitrary precision integers.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
static Constant * getNot(Constant *C)
static Constant * getNeg(Constant *C, bool HasNSW=false)
This is an important base class in LLVM.
static Constant * getAllOnesValue(Type *Ty)
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
static bool shouldExecute(unsigned CounterName)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateFreeze(Value *V, const Twine &Name="")
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateNot(Value *V, const Twine &Name="")
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateSDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
void ClearInsertionPoint()
Clear the insertion point: created instructions will not be inserted into a block.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
const DataLayout & getDataLayout() const
DominatorTree & getDominatorTree() const
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
This is an important class for using LLVM in a threaded context.
static Value * Negate(bool LHSIsZero, bool IsNSW, Value *Root, InstCombinerImpl &IC)
Attempt to negate Root.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
reference emplace_back(ArgTypes &&... Args)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetFolder - Create constants with target dependent folding.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void setName(const Twine &Name)
Change the name of the value.
LLVMContext & getContext() const
All values hold a context through their type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
cst_pred_ty< is_any_apint > m_AnyIntegralConstant()
Match an integer or vector with any integral constant.
OneUse_match< T > m_OneUse(const T &SubPattern)
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
match_combine_and< class_match< Constant >, match_unless< constantexpr_match > > m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
auto reverse(ContainerTy &&C)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
@ Xor
Bitwise or logical XOR of integers.
constexpr unsigned BitWidth
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.