LLVM 20.0.0git
InstCombineNegator.cpp
Go to the documentation of this file.
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"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.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"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Use.h"
34#include "llvm/IR/User.h"
35#include "llvm/IR/Value.h"
43#include <cassert>
44#include <cstdint>
45#include <functional>
46#include <type_traits>
47#include <utility>
48
49using namespace llvm;
50using namespace llvm::PatternMatch;
51
52#define DEBUG_TYPE "instcombine"
53
54STATISTIC(NegatorTotalNegationsAttempted,
55 "Negator: Number of negations attempted to be sinked");
56STATISTIC(NegatorNumTreesNegated,
57 "Negator: Number of negations successfully sinked");
58STATISTIC(NegatorMaxDepthVisited, "Negator: Maximal traversal depth ever "
59 "reached while attempting to sink negation");
60STATISTIC(NegatorTimesDepthLimitReached,
61 "Negator: How many times did the traversal depth limit was reached "
62 "during sinking");
64 NegatorNumValuesVisited,
65 "Negator: Total number of values visited during attempts to sink negation");
66STATISTIC(NegatorNumNegationsFoundInCache,
67 "Negator: How many negations did we retrieve/reuse from cache");
68STATISTIC(NegatorMaxTotalValuesVisited,
69 "Negator: Maximal number of values ever visited while attempting to "
70 "sink negation");
71STATISTIC(NegatorNumInstructionsCreatedTotal,
72 "Negator: Number of new negated instructions created, total");
73STATISTIC(NegatorMaxInstructionsCreated,
74 "Negator: Maximal number of new instructions created during negation "
75 "attempt");
76STATISTIC(NegatorNumInstructionsNegatedSuccess,
77 "Negator: Number of new negated instructions created in successful "
78 "negation sinking attempts");
79
80DEBUG_COUNTER(NegatorCounter, "instcombine-negator",
81 "Controls Negator transformations in InstCombine pass");
82
83static cl::opt<bool>
84 NegatorEnabled("instcombine-negator-enabled", cl::init(true),
85 cl::desc("Should we attempt to sink negations?"));
86
88 NegatorMaxDepth("instcombine-negator-max-depth",
90 cl::desc("What is the maximal lookup depth when trying to "
91 "check for viability of negation sinking."));
92
93Negator::Negator(LLVMContext &C, const DataLayout &DL, const DominatorTree &DT_,
94 bool IsTrulyNegation_)
95 : Builder(C, TargetFolder(DL),
97 ++NegatorNumInstructionsCreatedTotal;
98 NewInstructions.push_back(I);
99 })),
100 DT(DT_), IsTrulyNegation(IsTrulyNegation_) {}
101
102#if LLVM_ENABLE_STATS
103Negator::~Negator() {
104 NegatorMaxTotalValuesVisited.updateMax(NumValuesVisitedInThisNegator);
105}
106#endif
107
108// Due to the InstCombine's worklist management, there are no guarantees that
109// each instruction we'll encounter has been visited by InstCombine already.
110// In particular, most importantly for us, that means we have to canonicalize
111// constants to RHS ourselves, since that is helpful sometimes.
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)};
115 if (I->isCommutative() && InstCombiner::getComplexity(I->getOperand(0)) <
116 InstCombiner::getComplexity(I->getOperand(1)))
117 std::swap(Ops[0], Ops[1]);
118 return Ops;
119}
120
121// FIXME: can this be reworked into a worklist-based algorithm while preserving
122// the depth-first, early bailout traversal?
123[[nodiscard]] Value *Negator::visitImpl(Value *V, bool IsNSW, unsigned Depth) {
124 // -(undef) -> undef.
125 if (match(V, m_Undef()))
126 return V;
127
128 // In i1, negation can simply be ignored.
129 if (V->getType()->isIntOrIntVectorTy(1))
130 return V;
131
132 Value *X;
133
134 // -(-(X)) -> X.
135 if (match(V, m_Neg(m_Value(X))))
136 return X;
137
138 // Integral constants can be freely negated.
140 return ConstantExpr::getNeg(cast<Constant>(V),
141 /*HasNSW=*/false);
142
143 // If we have a non-instruction, then give up.
144 if (!isa<Instruction>(V))
145 return nullptr;
146
147 // If we have started with a true negation (i.e. `sub 0, %y`), then if we've
148 // got instruction that does not require recursive reasoning, we can still
149 // negate it even if it has other uses, without increasing instruction count.
150 if (!V->hasOneUse() && !IsTrulyNegation)
151 return nullptr;
152
153 auto *I = cast<Instruction>(V);
154 unsigned BitWidth = I->getType()->getScalarSizeInBits();
155
156 // We must preserve the insertion point and debug info that is set in the
157 // builder at the time this function is called.
159 // And since we are trying to negate instruction I, that tells us about the
160 // insertion point and the debug info that we need to keep.
161 Builder.SetInsertPoint(I);
162
163 // In some cases we can give the answer without further recursion.
164 switch (I->getOpcode()) {
165 case Instruction::Add: {
166 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
167 // `inc` is always negatible.
168 if (match(Ops[1], m_One()))
169 return Builder.CreateNot(Ops[0], I->getName() + ".neg");
170 break;
171 }
172 case Instruction::Xor:
173 // `not` is always negatible.
174 if (match(I, m_Not(m_Value(X))))
175 return Builder.CreateAdd(X, ConstantInt::get(X->getType(), 1),
176 I->getName() + ".neg");
177 break;
178 case Instruction::AShr:
179 case Instruction::LShr: {
180 // Right-shift sign bit smear is negatible.
181 const APInt *Op1Val;
182 if (match(I->getOperand(1), m_APInt(Op1Val)) && *Op1Val == BitWidth - 1) {
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");
189 }
190 return BO;
191 }
192 // While we could negate exact arithmetic shift:
193 // ashr exact %x, C --> sdiv exact i8 %x, -1<<C
194 // iff C != 0 and C u< bitwidth(%x), we don't want to,
195 // because division is *THAT* much worse than a shift.
196 break;
197 }
198 case Instruction::SExt:
199 case Instruction::ZExt:
200 // `*ext` of i1 is always negatible
201 if (I->getOperand(0)->getType()->isIntOrIntVectorTy(1))
202 return I->getOpcode() == Instruction::SExt
203 ? Builder.CreateZExt(I->getOperand(0), I->getType(),
204 I->getName() + ".neg")
205 : Builder.CreateSExt(I->getOperand(0), I->getType(),
206 I->getName() + ".neg");
207 break;
208 case Instruction::Select: {
209 // If both arms of the select are constants, we don't need to recurse.
210 // Therefore, this transform is not limited by uses.
211 auto *Sel = cast<SelectInst>(I);
212 Constant *TrueC, *FalseC;
213 if (match(Sel->getTrueValue(), m_ImmConstant(TrueC)) &&
214 match(Sel->getFalseValue(), m_ImmConstant(FalseC))) {
215 Constant *NegTrueC = ConstantExpr::getNeg(TrueC);
216 Constant *NegFalseC = ConstantExpr::getNeg(FalseC);
217 return Builder.CreateSelect(Sel->getCondition(), NegTrueC, NegFalseC,
218 I->getName() + ".neg", /*MDFrom=*/I);
219 }
220 break;
221 }
222 case Instruction::Call:
223 if (auto *CI = dyn_cast<CmpIntrinsic>(I); CI && CI->hasOneUse())
224 return Builder.CreateIntrinsic(CI->getType(), CI->getIntrinsicID(),
225 {CI->getRHS(), CI->getLHS()});
226 break;
227 default:
228 break; // Other instructions require recursive reasoning.
229 }
230
231 if (I->getOpcode() == Instruction::Sub &&
232 (I->hasOneUse() || match(I->getOperand(0), m_ImmConstant()))) {
233 // `sub` is always negatible.
234 // However, only do this either if the old `sub` doesn't stick around, or
235 // it was subtracting from a constant. Otherwise, this isn't profitable.
236 return Builder.CreateSub(I->getOperand(1), I->getOperand(0),
237 I->getName() + ".neg", /* HasNUW */ false,
238 IsNSW && I->hasNoSignedWrap());
239 }
240
241 // Some other cases, while still don't require recursion,
242 // are restricted to the one-use case.
243 if (!V->hasOneUse())
244 return nullptr;
245
246 switch (I->getOpcode()) {
247 case Instruction::ZExt: {
248 // Negation of zext of signbit is signbit splat:
249 // 0 - (zext (i8 X u>> 7) to iN) --> sext (i8 X s>> 7) to iN
250 Value *SrcOp = I->getOperand(0);
251 unsigned SrcWidth = SrcOp->getType()->getScalarSizeInBits();
252 const APInt &FullShift = APInt(SrcWidth, SrcWidth - 1);
253 if (IsTrulyNegation &&
255 Value *Ashr = Builder.CreateAShr(X, FullShift);
256 return Builder.CreateSExt(Ashr, I->getType());
257 }
258 break;
259 }
260 case Instruction::And: {
261 Constant *ShAmt;
262 // sub(y,and(lshr(x,C),1)) --> add(ashr(shl(x,(BW-1)-C),BW-1),y)
264 m_LShr(m_Value(X), m_ImmConstant(ShAmt)))),
265 m_One()))) {
266 unsigned BW = X->getType()->getScalarSizeInBits();
267 Constant *BWMinusOne = ConstantInt::get(X->getType(), BW - 1);
268 Value *R = Builder.CreateShl(X, Builder.CreateSub(BWMinusOne, ShAmt));
269 R = Builder.CreateAShr(R, BWMinusOne);
270 return Builder.CreateTruncOrBitCast(R, I->getType());
271 }
272 break;
273 }
274 case Instruction::SDiv:
275 // `sdiv` is negatible if divisor is not undef/INT_MIN/1.
276 // While this is normally not behind a use-check,
277 // let's consider division to be special since it's costly.
278 if (auto *Op1C = dyn_cast<Constant>(I->getOperand(1))) {
279 if (!Op1C->containsUndefOrPoisonElement() &&
280 Op1C->isNotMinSignedValue() && Op1C->isNotOneValue()) {
281 Value *BO =
282 Builder.CreateSDiv(I->getOperand(0), ConstantExpr::getNeg(Op1C),
283 I->getName() + ".neg");
284 if (auto *NewInstr = dyn_cast<Instruction>(BO))
285 NewInstr->setIsExact(I->isExact());
286 return BO;
287 }
288 }
289 break;
290 }
291
292 // Rest of the logic is recursive, so if it's time to give up then it's time.
293 if (Depth > NegatorMaxDepth) {
294 LLVM_DEBUG(dbgs() << "Negator: reached maximal allowed traversal depth in "
295 << *V << ". Giving up.\n");
296 ++NegatorTimesDepthLimitReached;
297 return nullptr;
298 }
299
300 switch (I->getOpcode()) {
301 case Instruction::Freeze: {
302 // `freeze` is negatible if its operand is negatible.
303 Value *NegOp = negate(I->getOperand(0), IsNSW, Depth + 1);
304 if (!NegOp) // Early return.
305 return nullptr;
306 return Builder.CreateFreeze(NegOp, I->getName() + ".neg");
307 }
308 case Instruction::PHI: {
309 // `phi` is negatible if all the incoming values are negatible.
310 auto *PHI = cast<PHINode>(I);
311 SmallVector<Value *, 4> NegatedIncomingValues(PHI->getNumOperands());
312 for (auto I : zip(PHI->incoming_values(), NegatedIncomingValues)) {
313 // Don't negate indvars to avoid infinite loops.
314 if (DT.dominates(PHI->getParent(), std::get<0>(I)))
315 return nullptr;
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 Builder.Insert(NewSelect);
338 return NewSelect;
339 }
340 // `select` is negatible if both hands of `select` are negatible.
341 Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1);
342 if (!NegOp1) // Early return.
343 return nullptr;
344 Value *NegOp2 = negate(I->getOperand(2), IsNSW, Depth + 1);
345 if (!NegOp2)
346 return nullptr;
347 // Do preserve the metadata!
348 return Builder.CreateSelect(I->getOperand(0), NegOp1, NegOp2,
349 I->getName() + ".neg", /*MDFrom=*/I);
350 }
351 case Instruction::ShuffleVector: {
352 // `shufflevector` is negatible if both operands are negatible.
353 auto *Shuf = cast<ShuffleVectorInst>(I);
354 Value *NegOp0 = negate(I->getOperand(0), IsNSW, Depth + 1);
355 if (!NegOp0) // Early return.
356 return nullptr;
357 Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1);
358 if (!NegOp1)
359 return nullptr;
360 return Builder.CreateShuffleVector(NegOp0, NegOp1, Shuf->getShuffleMask(),
361 I->getName() + ".neg");
362 }
363 case Instruction::ExtractElement: {
364 // `extractelement` is negatible if source operand is negatible.
365 auto *EEI = cast<ExtractElementInst>(I);
366 Value *NegVector = negate(EEI->getVectorOperand(), IsNSW, Depth + 1);
367 if (!NegVector) // Early return.
368 return nullptr;
369 return Builder.CreateExtractElement(NegVector, EEI->getIndexOperand(),
370 I->getName() + ".neg");
371 }
372 case Instruction::InsertElement: {
373 // `insertelement` is negatible if both the source vector and
374 // element-to-be-inserted are negatible.
375 auto *IEI = cast<InsertElementInst>(I);
376 Value *NegVector = negate(IEI->getOperand(0), IsNSW, Depth + 1);
377 if (!NegVector) // Early return.
378 return nullptr;
379 Value *NegNewElt = negate(IEI->getOperand(1), IsNSW, Depth + 1);
380 if (!NegNewElt) // Early return.
381 return nullptr;
382 return Builder.CreateInsertElement(NegVector, NegNewElt, IEI->getOperand(2),
383 I->getName() + ".neg");
384 }
385 case Instruction::Trunc: {
386 // `trunc` is negatible if its operand is negatible.
387 Value *NegOp = negate(I->getOperand(0), /* IsNSW */ false, Depth + 1);
388 if (!NegOp) // Early return.
389 return nullptr;
390 return Builder.CreateTrunc(NegOp, I->getType(), I->getName() + ".neg");
391 }
392 case Instruction::Shl: {
393 // `shl` is negatible if the first operand is negatible.
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",
397 /* HasNUW */ false, IsNSW);
398 // Otherwise, `shl %x, C` can be interpreted as `mul %x, 1<<C`.
399 Constant *Op1C;
400 if (!match(I->getOperand(1), m_ImmConstant(Op1C)) || !IsTrulyNegation)
401 return nullptr;
402 return Builder.CreateMul(
403 I->getOperand(0),
404 Builder.CreateShl(Constant::getAllOnesValue(Op1C->getType()), Op1C),
405 I->getName() + ".neg", /* HasNUW */ false, IsNSW);
406 }
407 case Instruction::Or: {
408 if (!cast<PossiblyDisjointInst>(I)->isDisjoint())
409 return nullptr; // Don't know how to handle `or` in general.
410 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
411 // `or`/`add` are interchangeable when operands have no common bits set.
412 // `inc` is always negatible.
413 if (match(Ops[1], m_One()))
414 return Builder.CreateNot(Ops[0], I->getName() + ".neg");
415 // Else, just defer to Instruction::Add handling.
416 [[fallthrough]];
417 }
418 case Instruction::Add: {
419 // `add` is negatible if both of its operands are negatible.
420 SmallVector<Value *, 2> NegatedOps, NonNegatedOps;
421 for (Value *Op : I->operands()) {
422 // Can we sink the negation into this operand?
423 if (Value *NegOp = negate(Op, /* IsNSW */ false, Depth + 1)) {
424 NegatedOps.emplace_back(NegOp); // Successfully negated operand!
425 continue;
426 }
427 // Failed to sink negation into this operand. IFF we started from negation
428 // and we manage to sink negation into one operand, we can still do this.
429 if (!IsTrulyNegation)
430 return nullptr;
431 NonNegatedOps.emplace_back(Op); // Just record which operand that was.
432 }
433 assert((NegatedOps.size() + NonNegatedOps.size()) == 2 &&
434 "Internal consistency check failed.");
435 // Did we manage to sink negation into both of the operands?
436 if (NegatedOps.size() == 2) // Then we get to keep the `add`!
437 return Builder.CreateAdd(NegatedOps[0], NegatedOps[1],
438 I->getName() + ".neg");
439 assert(IsTrulyNegation && "We should have early-exited then.");
440 // Completely failed to sink negation?
441 if (NonNegatedOps.size() == 2)
442 return nullptr;
443 // 0-(a+b) --> (-a)-b
444 return Builder.CreateSub(NegatedOps[0], NonNegatedOps[0],
445 I->getName() + ".neg");
446 }
447 case Instruction::Xor: {
448 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
449 // `xor` is negatible if one of its operands is invertible.
450 // FIXME: InstCombineInverter? But how to connect Inverter and Negator?
451 if (auto *C = dyn_cast<Constant>(Ops[1])) {
452 if (IsTrulyNegation) {
453 Value *Xor = Builder.CreateXor(Ops[0], ConstantExpr::getNot(C));
454 return Builder.CreateAdd(Xor, ConstantInt::get(Xor->getType(), 1),
455 I->getName() + ".neg");
456 }
457 }
458 return nullptr;
459 }
460 case Instruction::Mul: {
461 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
462 // `mul` is negatible if one of its operands is negatible.
463 Value *NegatedOp, *OtherOp;
464 // First try the second operand, in case it's a constant it will be best to
465 // just invert it instead of sinking the `neg` deeper.
466 if (Value *NegOp1 = negate(Ops[1], /* IsNSW */ false, Depth + 1)) {
467 NegatedOp = NegOp1;
468 OtherOp = Ops[0];
469 } else if (Value *NegOp0 = negate(Ops[0], /* IsNSW */ false, Depth + 1)) {
470 NegatedOp = NegOp0;
471 OtherOp = Ops[1];
472 } else
473 // Can't negate either of them.
474 return nullptr;
475 return Builder.CreateMul(NegatedOp, OtherOp, I->getName() + ".neg",
476 /* HasNUW */ false, IsNSW && I->hasNoSignedWrap());
477 }
478 default:
479 return nullptr; // Don't know, likely not negatible for free.
480 }
481
482 llvm_unreachable("Can't get here. We always return from switch.");
483}
484
485[[nodiscard]] Value *Negator::negate(Value *V, bool IsNSW, unsigned Depth) {
486 NegatorMaxDepthVisited.updateMax(Depth);
487 ++NegatorNumValuesVisited;
488
489#if LLVM_ENABLE_STATS
490 ++NumValuesVisitedInThisNegator;
491#endif
492
493#ifndef NDEBUG
494 // We can't ever have a Value with such an address.
495 Value *Placeholder = reinterpret_cast<Value *>(static_cast<uintptr_t>(-1));
496#endif
497
498 // Did we already try to negate this value?
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.");
504 return NegatedV;
505 }
506
507#ifndef NDEBUG
508 // We did not find a cached result for negation of V. While there,
509 // let's temporairly cache a placeholder value, with the idea that if later
510 // during negation we fetch it from cache, we'll know we're in a cycle.
511 NegationsCache[V] = Placeholder;
512#endif
513
514 // No luck. Try negating it for real.
515 Value *NegatedV = visitImpl(V, IsNSW, Depth);
516 // And cache the (real) result for the future.
517 NegationsCache[V] = NegatedV;
518
519 return NegatedV;
520}
521
522[[nodiscard]] std::optional<Negator::Result> Negator::run(Value *Root,
523 bool IsNSW) {
524 Value *Negated = negate(Root, IsNSW, /*Depth=*/0);
525 if (!Negated) {
526 // We must cleanup newly-inserted instructions, to avoid any potential
527 // endless combine looping.
528 for (Instruction *I : llvm::reverse(NewInstructions))
529 I->eraseFromParent();
530 return std::nullopt;
531 }
532 return std::make_pair(ArrayRef<Instruction *>(NewInstructions), Negated);
533}
534
535[[nodiscard]] Value *Negator::Negate(bool LHSIsZero, bool IsNSW, Value *Root,
536 InstCombinerImpl &IC) {
537 ++NegatorTotalNegationsAttempted;
538 LLVM_DEBUG(dbgs() << "Negator: attempting to sink negation into " << *Root
539 << "\n");
540
541 if (!NegatorEnabled || !DebugCounter::shouldExecute(NegatorCounter))
542 return nullptr;
543
545 LHSIsZero);
546 std::optional<Result> Res = N.run(Root, IsNSW);
547 if (!Res) { // Negation failed.
548 LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root
549 << "\n");
550 return nullptr;
551 }
552
553 LLVM_DEBUG(dbgs() << "Negator: successfully sunk negation into " << *Root
554 << "\n NEW: " << *Res->second << "\n");
555 ++NegatorNumTreesNegated;
556
557 // We must temporarily unset the 'current' insertion point and DebugLoc of the
558 // InstCombine's IRBuilder so that it won't interfere with the ones we have
559 // already specified when producing negated instructions.
563
564 // And finally, we must add newly-created instructions into the InstCombine's
565 // worklist (in a proper order!) so it can attempt to combine them.
566 LLVM_DEBUG(dbgs() << "Negator: Propagating " << Res->first.size()
567 << " instrs to InstCombine\n");
568 NegatorMaxInstructionsCreated.updateMax(Res->first.size());
569 NegatorNumInstructionsNegatedSuccess += Res->first.size();
570
571 // They are in def-use order, so nothing fancy, just insert them in order.
572 for (Instruction *I : Res->first)
573 IC.Builder.Insert(I, I->getName());
574
575 // And return the new root.
576 return Res->second;
577}
Rewrite undef for PHI
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)
Definition: DebugCounter.h:190
#define LLVM_DEBUG(X)
Definition: Debug.h:101
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.
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
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)
Definition: Statistic.h:166
Class for arbitrary precision integers.
Definition: APInt.h:78
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2605
static Constant * getNeg(Constant *C, bool HasNSW=false)
Definition: Constants.cpp:2599
This is an important base class in LLVM.
Definition: Constant.h:42
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
static bool shouldExecute(unsigned CounterName)
Definition: DebugCounter.h:87
A debug info location.
Definition: DebugLoc.h:33
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2492
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2480
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.
Definition: IRBuilder.cpp:933
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1091
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2053
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2555
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1454
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:217
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2417
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1766
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:142
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1361
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1433
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2041
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2514
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1344
Value * CreateSDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1408
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2027
void ClearInsertionPoint()
Clear the insertion point: created instructions will not be inserted into a block.
Definition: IRBuilder.h:166
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1473
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1536
Value * CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2173
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1378
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition: IRBuilder.h:74
const DataLayout & getDataLayout() const
Definition: InstCombiner.h:341
DominatorTree & getDominatorTree() const
Definition: InstCombiner.h:340
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
Definition: InstCombiner.h:139
BuilderTy & Builder
Definition: InstCombiner.h:60
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
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.
size_t size() const
Definition: SmallVector.h:91
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
TargetFolder - Create constants with target dependent folding.
Definition: TargetFolder.h:34
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
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)
Definition: PatternMatch.h:49
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
Definition: PatternMatch.h:980
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:592
cst_pred_ty< is_any_apint > m_AnyIntegralConstant()
Match an integer or vector with any integral constant.
Definition: PatternMatch.h:507
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
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.
Definition: PatternMatch.h:854
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
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)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition: STLExtras.h:853
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
@ Xor
Bitwise or logical XOR of integers.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
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.
Definition: BitVector.h:860
#define N