xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp (revision f3087bef11543b42e0d69b708f367097a4118d24)
1 //===- InstCombineNegator.cpp -----------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements sinking of negation into expression trees,
10 // as long as that can be done without increasing instruction count.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/TargetFolder.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/Constant.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/Use.h"
34 #include "llvm/IR/User.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/DebugCounter.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/InstCombine/InstCombiner.h"
43 #include <cassert>
44 #include <cstdint>
45 #include <functional>
46 #include <type_traits>
47 #include <utility>
48 
49 namespace llvm {
50 class DataLayout;
51 class LLVMContext;
52 } // namespace llvm
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "instcombine"
57 
58 STATISTIC(NegatorTotalNegationsAttempted,
59           "Negator: Number of negations attempted to be sinked");
60 STATISTIC(NegatorNumTreesNegated,
61           "Negator: Number of negations successfully sinked");
62 STATISTIC(NegatorMaxDepthVisited, "Negator: Maximal traversal depth ever "
63                                   "reached while attempting to sink negation");
64 STATISTIC(NegatorTimesDepthLimitReached,
65           "Negator: How many times did the traversal depth limit was reached "
66           "during sinking");
67 STATISTIC(
68     NegatorNumValuesVisited,
69     "Negator: Total number of values visited during attempts to sink negation");
70 STATISTIC(NegatorNumNegationsFoundInCache,
71           "Negator: How many negations did we retrieve/reuse from cache");
72 STATISTIC(NegatorMaxTotalValuesVisited,
73           "Negator: Maximal number of values ever visited while attempting to "
74           "sink negation");
75 STATISTIC(NegatorNumInstructionsCreatedTotal,
76           "Negator: Number of new negated instructions created, total");
77 STATISTIC(NegatorMaxInstructionsCreated,
78           "Negator: Maximal number of new instructions created during negation "
79           "attempt");
80 STATISTIC(NegatorNumInstructionsNegatedSuccess,
81           "Negator: Number of new negated instructions created in successful "
82           "negation sinking attempts");
83 
84 DEBUG_COUNTER(NegatorCounter, "instcombine-negator",
85               "Controls Negator transformations in InstCombine pass");
86 
87 static cl::opt<bool>
88     NegatorEnabled("instcombine-negator-enabled", cl::init(true),
89                    cl::desc("Should we attempt to sink negations?"));
90 
91 static cl::opt<unsigned>
92     NegatorMaxDepth("instcombine-negator-max-depth",
93                     cl::init(NegatorDefaultMaxDepth),
94                     cl::desc("What is the maximal lookup depth when trying to "
95                              "check for viability of negation sinking."));
96 
97 Negator::Negator(LLVMContext &C, const DataLayout &DL, bool IsTrulyNegation_)
98     : Builder(C, TargetFolder(DL),
99               IRBuilderCallbackInserter([&](Instruction *I) {
100                 ++NegatorNumInstructionsCreatedTotal;
101                 NewInstructions.push_back(I);
102               })),
103       IsTrulyNegation(IsTrulyNegation_) {}
104 
105 #if LLVM_ENABLE_STATS
106 Negator::~Negator() {
107   NegatorMaxTotalValuesVisited.updateMax(NumValuesVisitedInThisNegator);
108 }
109 #endif
110 
111 // Due to the InstCombine's worklist management, there are no guarantees that
112 // each instruction we'll encounter has been visited by InstCombine already.
113 // In particular, most importantly for us, that means we have to canonicalize
114 // constants to RHS ourselves, since that is helpful sometimes.
115 std::array<Value *, 2> Negator::getSortedOperandsOfBinOp(Instruction *I) {
116   assert(I->getNumOperands() == 2 && "Only for binops!");
117   std::array<Value *, 2> Ops{I->getOperand(0), I->getOperand(1)};
118   if (I->isCommutative() && InstCombiner::getComplexity(I->getOperand(0)) <
119                                 InstCombiner::getComplexity(I->getOperand(1)))
120     std::swap(Ops[0], Ops[1]);
121   return Ops;
122 }
123 
124 // FIXME: can this be reworked into a worklist-based algorithm while preserving
125 // the depth-first, early bailout traversal?
126 [[nodiscard]] Value *Negator::visitImpl(Value *V, bool IsNSW, unsigned Depth) {
127   // -(undef) -> undef.
128   if (match(V, m_Undef()))
129     return V;
130 
131   // In i1, negation can simply be ignored.
132   if (V->getType()->isIntOrIntVectorTy(1))
133     return V;
134 
135   Value *X;
136 
137   // -(-(X)) -> X.
138   if (match(V, m_Neg(m_Value(X))))
139     return X;
140 
141   // Integral constants can be freely negated.
142   if (match(V, m_AnyIntegralConstant()))
143     return ConstantExpr::getNeg(cast<Constant>(V),
144                                 /*HasNSW=*/false);
145 
146   // If we have a non-instruction, then give up.
147   if (!isa<Instruction>(V))
148     return nullptr;
149 
150   // If we have started with a true negation (i.e. `sub 0, %y`), then if we've
151   // got instruction that does not require recursive reasoning, we can still
152   // negate it even if it has other uses, without increasing instruction count.
153   if (!V->hasOneUse() && !IsTrulyNegation)
154     return nullptr;
155 
156   auto *I = cast<Instruction>(V);
157   unsigned BitWidth = I->getType()->getScalarSizeInBits();
158 
159   // We must preserve the insertion point and debug info that is set in the
160   // builder at the time this function is called.
161   InstCombiner::BuilderTy::InsertPointGuard Guard(Builder);
162   // And since we are trying to negate instruction I, that tells us about the
163   // insertion point and the debug info that we need to keep.
164   Builder.SetInsertPoint(I);
165 
166   // In some cases we can give the answer without further recursion.
167   switch (I->getOpcode()) {
168   case Instruction::Add: {
169     std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
170     // `inc` is always negatible.
171     if (match(Ops[1], m_One()))
172       return Builder.CreateNot(Ops[0], I->getName() + ".neg");
173     break;
174   }
175   case Instruction::Xor:
176     // `not` is always negatible.
177     if (match(I, m_Not(m_Value(X))))
178       return Builder.CreateAdd(X, ConstantInt::get(X->getType(), 1),
179                                I->getName() + ".neg");
180     break;
181   case Instruction::AShr:
182   case Instruction::LShr: {
183     // Right-shift sign bit smear is negatible.
184     const APInt *Op1Val;
185     if (match(I->getOperand(1), m_APInt(Op1Val)) && *Op1Val == BitWidth - 1) {
186       Value *BO = I->getOpcode() == Instruction::AShr
187                       ? Builder.CreateLShr(I->getOperand(0), I->getOperand(1))
188                       : Builder.CreateAShr(I->getOperand(0), I->getOperand(1));
189       if (auto *NewInstr = dyn_cast<Instruction>(BO)) {
190         NewInstr->copyIRFlags(I);
191         NewInstr->setName(I->getName() + ".neg");
192       }
193       return BO;
194     }
195     // While we could negate exact arithmetic shift:
196     //   ashr exact %x, C  -->   sdiv exact i8 %x, -1<<C
197     // iff C != 0 and C u< bitwidth(%x), we don't want to,
198     // because division is *THAT* much worse than a shift.
199     break;
200   }
201   case Instruction::SExt:
202   case Instruction::ZExt:
203     // `*ext` of i1 is always negatible
204     if (I->getOperand(0)->getType()->isIntOrIntVectorTy(1))
205       return I->getOpcode() == Instruction::SExt
206                  ? Builder.CreateZExt(I->getOperand(0), I->getType(),
207                                       I->getName() + ".neg")
208                  : Builder.CreateSExt(I->getOperand(0), I->getType(),
209                                       I->getName() + ".neg");
210     break;
211   case Instruction::Select: {
212     // If both arms of the select are constants, we don't need to recurse.
213     // Therefore, this transform is not limited by uses.
214     auto *Sel = cast<SelectInst>(I);
215     Constant *TrueC, *FalseC;
216     if (match(Sel->getTrueValue(), m_ImmConstant(TrueC)) &&
217         match(Sel->getFalseValue(), m_ImmConstant(FalseC))) {
218       Constant *NegTrueC = ConstantExpr::getNeg(TrueC);
219       Constant *NegFalseC = ConstantExpr::getNeg(FalseC);
220       return Builder.CreateSelect(Sel->getCondition(), NegTrueC, NegFalseC,
221                                   I->getName() + ".neg", /*MDFrom=*/I);
222     }
223     break;
224   }
225   case Instruction::Call:
226     if (auto *CI = dyn_cast<CmpIntrinsic>(I); CI && CI->hasOneUse())
227       return Builder.CreateIntrinsic(CI->getType(), CI->getIntrinsicID(),
228                                      {CI->getRHS(), CI->getLHS()});
229     break;
230   default:
231     break; // Other instructions require recursive reasoning.
232   }
233 
234   if (I->getOpcode() == Instruction::Sub &&
235       (I->hasOneUse() || match(I->getOperand(0), m_ImmConstant()))) {
236     // `sub` is always negatible.
237     // However, only do this either if the old `sub` doesn't stick around, or
238     // it was subtracting from a constant. Otherwise, this isn't profitable.
239     return Builder.CreateSub(I->getOperand(1), I->getOperand(0),
240                              I->getName() + ".neg", /* HasNUW */ false,
241                              IsNSW && I->hasNoSignedWrap());
242   }
243 
244   // Some other cases, while still don't require recursion,
245   // are restricted to the one-use case.
246   if (!V->hasOneUse())
247     return nullptr;
248 
249   switch (I->getOpcode()) {
250   case Instruction::ZExt: {
251     // Negation of zext of signbit is signbit splat:
252     // 0 - (zext (i8 X u>> 7) to iN) --> sext (i8 X s>> 7) to iN
253     Value *SrcOp = I->getOperand(0);
254     unsigned SrcWidth = SrcOp->getType()->getScalarSizeInBits();
255     const APInt &FullShift = APInt(SrcWidth, SrcWidth - 1);
256     if (IsTrulyNegation &&
257         match(SrcOp, m_LShr(m_Value(X), m_SpecificIntAllowPoison(FullShift)))) {
258       Value *Ashr = Builder.CreateAShr(X, FullShift);
259       return Builder.CreateSExt(Ashr, I->getType());
260     }
261     break;
262   }
263   case Instruction::And: {
264     Constant *ShAmt;
265     // sub(y,and(lshr(x,C),1)) --> add(ashr(shl(x,(BW-1)-C),BW-1),y)
266     if (match(I, m_And(m_OneUse(m_TruncOrSelf(
267                            m_LShr(m_Value(X), m_ImmConstant(ShAmt)))),
268                        m_One()))) {
269       unsigned BW = X->getType()->getScalarSizeInBits();
270       Constant *BWMinusOne = ConstantInt::get(X->getType(), BW - 1);
271       Value *R = Builder.CreateShl(X, Builder.CreateSub(BWMinusOne, ShAmt));
272       R = Builder.CreateAShr(R, BWMinusOne);
273       return Builder.CreateTruncOrBitCast(R, I->getType());
274     }
275     break;
276   }
277   case Instruction::SDiv:
278     // `sdiv` is negatible if divisor is not undef/INT_MIN/1.
279     // While this is normally not behind a use-check,
280     // let's consider division to be special since it's costly.
281     if (auto *Op1C = dyn_cast<Constant>(I->getOperand(1))) {
282       if (!Op1C->containsUndefOrPoisonElement() &&
283           Op1C->isNotMinSignedValue() && Op1C->isNotOneValue()) {
284         Value *BO =
285             Builder.CreateSDiv(I->getOperand(0), ConstantExpr::getNeg(Op1C),
286                                I->getName() + ".neg");
287         if (auto *NewInstr = dyn_cast<Instruction>(BO))
288           NewInstr->setIsExact(I->isExact());
289         return BO;
290       }
291     }
292     break;
293   }
294 
295   // Rest of the logic is recursive, so if it's time to give up then it's time.
296   if (Depth > NegatorMaxDepth) {
297     LLVM_DEBUG(dbgs() << "Negator: reached maximal allowed traversal depth in "
298                       << *V << ". Giving up.\n");
299     ++NegatorTimesDepthLimitReached;
300     return nullptr;
301   }
302 
303   switch (I->getOpcode()) {
304   case Instruction::Freeze: {
305     // `freeze` is negatible if its operand is negatible.
306     Value *NegOp = negate(I->getOperand(0), IsNSW, Depth + 1);
307     if (!NegOp) // Early return.
308       return nullptr;
309     return Builder.CreateFreeze(NegOp, I->getName() + ".neg");
310   }
311   case Instruction::PHI: {
312     // `phi` is negatible if all the incoming values are negatible.
313     auto *PHI = cast<PHINode>(I);
314     SmallVector<Value *, 4> NegatedIncomingValues(PHI->getNumOperands());
315     for (auto I : zip(PHI->incoming_values(), NegatedIncomingValues)) {
316       if (!(std::get<1>(I) =
317                 negate(std::get<0>(I), IsNSW, Depth + 1))) // Early return.
318         return nullptr;
319     }
320     // All incoming values are indeed negatible. Create negated PHI node.
321     PHINode *NegatedPHI = Builder.CreatePHI(
322         PHI->getType(), PHI->getNumOperands(), PHI->getName() + ".neg");
323     for (auto I : zip(NegatedIncomingValues, PHI->blocks()))
324       NegatedPHI->addIncoming(std::get<0>(I), std::get<1>(I));
325     return NegatedPHI;
326   }
327   case Instruction::Select: {
328     if (isKnownNegation(I->getOperand(1), I->getOperand(2), /*NeedNSW=*/false,
329                         /*AllowPoison=*/false)) {
330       // Of one hand of select is known to be negation of another hand,
331       // just swap the hands around.
332       auto *NewSelect = cast<SelectInst>(I->clone());
333       // Just swap the operands of the select.
334       NewSelect->swapValues();
335       // Don't swap prof metadata, we didn't change the branch behavior.
336       NewSelect->setName(I->getName() + ".neg");
337       // Poison-generating flags should be dropped
338       Value *TV = NewSelect->getTrueValue();
339       Value *FV = NewSelect->getFalseValue();
340       if (match(TV, m_Neg(m_Specific(FV))))
341         cast<Instruction>(TV)->dropPoisonGeneratingFlags();
342       else if (match(FV, m_Neg(m_Specific(TV))))
343         cast<Instruction>(FV)->dropPoisonGeneratingFlags();
344       else {
345         cast<Instruction>(TV)->dropPoisonGeneratingFlags();
346         cast<Instruction>(FV)->dropPoisonGeneratingFlags();
347       }
348       Builder.Insert(NewSelect);
349       return NewSelect;
350     }
351     // `select` is negatible if both hands of `select` are negatible.
352     Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1);
353     if (!NegOp1) // Early return.
354       return nullptr;
355     Value *NegOp2 = negate(I->getOperand(2), IsNSW, Depth + 1);
356     if (!NegOp2)
357       return nullptr;
358     // Do preserve the metadata!
359     return Builder.CreateSelect(I->getOperand(0), NegOp1, NegOp2,
360                                 I->getName() + ".neg", /*MDFrom=*/I);
361   }
362   case Instruction::ShuffleVector: {
363     // `shufflevector` is negatible if both operands are negatible.
364     auto *Shuf = cast<ShuffleVectorInst>(I);
365     Value *NegOp0 = negate(I->getOperand(0), IsNSW, Depth + 1);
366     if (!NegOp0) // Early return.
367       return nullptr;
368     Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1);
369     if (!NegOp1)
370       return nullptr;
371     return Builder.CreateShuffleVector(NegOp0, NegOp1, Shuf->getShuffleMask(),
372                                        I->getName() + ".neg");
373   }
374   case Instruction::ExtractElement: {
375     // `extractelement` is negatible if source operand is negatible.
376     auto *EEI = cast<ExtractElementInst>(I);
377     Value *NegVector = negate(EEI->getVectorOperand(), IsNSW, Depth + 1);
378     if (!NegVector) // Early return.
379       return nullptr;
380     return Builder.CreateExtractElement(NegVector, EEI->getIndexOperand(),
381                                         I->getName() + ".neg");
382   }
383   case Instruction::InsertElement: {
384     // `insertelement` is negatible if both the source vector and
385     // element-to-be-inserted are negatible.
386     auto *IEI = cast<InsertElementInst>(I);
387     Value *NegVector = negate(IEI->getOperand(0), IsNSW, Depth + 1);
388     if (!NegVector) // Early return.
389       return nullptr;
390     Value *NegNewElt = negate(IEI->getOperand(1), IsNSW, Depth + 1);
391     if (!NegNewElt) // Early return.
392       return nullptr;
393     return Builder.CreateInsertElement(NegVector, NegNewElt, IEI->getOperand(2),
394                                        I->getName() + ".neg");
395   }
396   case Instruction::Trunc: {
397     // `trunc` is negatible if its operand is negatible.
398     Value *NegOp = negate(I->getOperand(0), /* IsNSW */ false, Depth + 1);
399     if (!NegOp) // Early return.
400       return nullptr;
401     return Builder.CreateTrunc(NegOp, I->getType(), I->getName() + ".neg");
402   }
403   case Instruction::Shl: {
404     // `shl` is negatible if the first operand is negatible.
405     IsNSW &= I->hasNoSignedWrap();
406     if (Value *NegOp0 = negate(I->getOperand(0), IsNSW, Depth + 1))
407       return Builder.CreateShl(NegOp0, I->getOperand(1), I->getName() + ".neg",
408                                /* HasNUW */ false, IsNSW);
409     // Otherwise, `shl %x, C` can be interpreted as `mul %x, 1<<C`.
410     Constant *Op1C;
411     if (!match(I->getOperand(1), m_ImmConstant(Op1C)) || !IsTrulyNegation)
412       return nullptr;
413     return Builder.CreateMul(
414         I->getOperand(0),
415         Builder.CreateShl(Constant::getAllOnesValue(Op1C->getType()), Op1C),
416         I->getName() + ".neg", /* HasNUW */ false, IsNSW);
417   }
418   case Instruction::Or: {
419     if (!cast<PossiblyDisjointInst>(I)->isDisjoint())
420       return nullptr; // Don't know how to handle `or` in general.
421     std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
422     // `or`/`add` are interchangeable when operands have no common bits set.
423     // `inc` is always negatible.
424     if (match(Ops[1], m_One()))
425       return Builder.CreateNot(Ops[0], I->getName() + ".neg");
426     // Else, just defer to Instruction::Add handling.
427     [[fallthrough]];
428   }
429   case Instruction::Add: {
430     // `add` is negatible if both of its operands are negatible.
431     SmallVector<Value *, 2> NegatedOps, NonNegatedOps;
432     for (Value *Op : I->operands()) {
433       // Can we sink the negation into this operand?
434       if (Value *NegOp = negate(Op, /* IsNSW */ false, Depth + 1)) {
435         NegatedOps.emplace_back(NegOp); // Successfully negated operand!
436         continue;
437       }
438       // Failed to sink negation into this operand. IFF we started from negation
439       // and we manage to sink negation into one operand, we can still do this.
440       if (!IsTrulyNegation)
441         return nullptr;
442       NonNegatedOps.emplace_back(Op); // Just record which operand that was.
443     }
444     assert((NegatedOps.size() + NonNegatedOps.size()) == 2 &&
445            "Internal consistency check failed.");
446     // Did we manage to sink negation into both of the operands?
447     if (NegatedOps.size() == 2) // Then we get to keep the `add`!
448       return Builder.CreateAdd(NegatedOps[0], NegatedOps[1],
449                                I->getName() + ".neg");
450     assert(IsTrulyNegation && "We should have early-exited then.");
451     // Completely failed to sink negation?
452     if (NonNegatedOps.size() == 2)
453       return nullptr;
454     // 0-(a+b) --> (-a)-b
455     return Builder.CreateSub(NegatedOps[0], NonNegatedOps[0],
456                              I->getName() + ".neg");
457   }
458   case Instruction::Xor: {
459     std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
460     // `xor` is negatible if one of its operands is invertible.
461     // FIXME: InstCombineInverter? But how to connect Inverter and Negator?
462     if (auto *C = dyn_cast<Constant>(Ops[1])) {
463       if (IsTrulyNegation) {
464         Value *Xor = Builder.CreateXor(Ops[0], ConstantExpr::getNot(C));
465         return Builder.CreateAdd(Xor, ConstantInt::get(Xor->getType(), 1),
466                                  I->getName() + ".neg");
467       }
468     }
469     return nullptr;
470   }
471   case Instruction::Mul: {
472     std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
473     // `mul` is negatible if one of its operands is negatible.
474     Value *NegatedOp, *OtherOp;
475     // First try the second operand, in case it's a constant it will be best to
476     // just invert it instead of sinking the `neg` deeper.
477     if (Value *NegOp1 = negate(Ops[1], /* IsNSW */ false, Depth + 1)) {
478       NegatedOp = NegOp1;
479       OtherOp = Ops[0];
480     } else if (Value *NegOp0 = negate(Ops[0], /* IsNSW */ false, Depth + 1)) {
481       NegatedOp = NegOp0;
482       OtherOp = Ops[1];
483     } else
484       // Can't negate either of them.
485       return nullptr;
486     return Builder.CreateMul(NegatedOp, OtherOp, I->getName() + ".neg",
487                              /* HasNUW */ false, IsNSW && I->hasNoSignedWrap());
488   }
489   default:
490     return nullptr; // Don't know, likely not negatible for free.
491   }
492 
493   llvm_unreachable("Can't get here. We always return from switch.");
494 }
495 
496 [[nodiscard]] Value *Negator::negate(Value *V, bool IsNSW, unsigned Depth) {
497   NegatorMaxDepthVisited.updateMax(Depth);
498   ++NegatorNumValuesVisited;
499 
500 #if LLVM_ENABLE_STATS
501   ++NumValuesVisitedInThisNegator;
502 #endif
503 
504 #ifndef NDEBUG
505   // We can't ever have a Value with such an address.
506   Value *Placeholder = reinterpret_cast<Value *>(static_cast<uintptr_t>(-1));
507 #endif
508 
509   // Did we already try to negate this value?
510   auto NegationsCacheIterator = NegationsCache.find(V);
511   if (NegationsCacheIterator != NegationsCache.end()) {
512     ++NegatorNumNegationsFoundInCache;
513     Value *NegatedV = NegationsCacheIterator->second;
514     assert(NegatedV != Placeholder && "Encountered a cycle during negation.");
515     return NegatedV;
516   }
517 
518 #ifndef NDEBUG
519   // We did not find a cached result for negation of V. While there,
520   // let's temporairly cache a placeholder value, with the idea that if later
521   // during negation we fetch it from cache, we'll know we're in a cycle.
522   NegationsCache[V] = Placeholder;
523 #endif
524 
525   // No luck. Try negating it for real.
526   Value *NegatedV = visitImpl(V, IsNSW, Depth);
527   // And cache the (real) result for the future.
528   NegationsCache[V] = NegatedV;
529 
530   return NegatedV;
531 }
532 
533 [[nodiscard]] std::optional<Negator::Result> Negator::run(Value *Root,
534                                                           bool IsNSW) {
535   Value *Negated = negate(Root, IsNSW, /*Depth=*/0);
536   if (!Negated) {
537     // We must cleanup newly-inserted instructions, to avoid any potential
538     // endless combine looping.
539     for (Instruction *I : llvm::reverse(NewInstructions))
540       I->eraseFromParent();
541     return std::nullopt;
542   }
543   return std::make_pair(ArrayRef<Instruction *>(NewInstructions), Negated);
544 }
545 
546 [[nodiscard]] Value *Negator::Negate(bool LHSIsZero, bool IsNSW, Value *Root,
547                                      InstCombinerImpl &IC) {
548   ++NegatorTotalNegationsAttempted;
549   LLVM_DEBUG(dbgs() << "Negator: attempting to sink negation into " << *Root
550                     << "\n");
551 
552   if (!NegatorEnabled || !DebugCounter::shouldExecute(NegatorCounter))
553     return nullptr;
554 
555   Negator N(Root->getContext(), IC.getDataLayout(), LHSIsZero);
556   std::optional<Result> Res = N.run(Root, IsNSW);
557   if (!Res) { // Negation failed.
558     LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root
559                       << "\n");
560     return nullptr;
561   }
562 
563   LLVM_DEBUG(dbgs() << "Negator: successfully sunk negation into " << *Root
564                     << "\n         NEW: " << *Res->second << "\n");
565   ++NegatorNumTreesNegated;
566 
567   // We must temporarily unset the 'current' insertion point and DebugLoc of the
568   // InstCombine's IRBuilder so that it won't interfere with the ones we have
569   // already specified when producing negated instructions.
570   InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
571   IC.Builder.ClearInsertionPoint();
572   IC.Builder.SetCurrentDebugLocation(DebugLoc());
573 
574   // And finally, we must add newly-created instructions into the InstCombine's
575   // worklist (in a proper order!) so it can attempt to combine them.
576   LLVM_DEBUG(dbgs() << "Negator: Propagating " << Res->first.size()
577                     << " instrs to InstCombine\n");
578   NegatorMaxInstructionsCreated.updateMax(Res->first.size());
579   NegatorNumInstructionsNegatedSuccess += Res->first.size();
580 
581   // They are in def-use order, so nothing fancy, just insert them in order.
582   for (Instruction *I : Res->first)
583     IC.Builder.Insert(I, I->getName());
584 
585   // And return the new root.
586   return Res->second;
587 }
588