LLVM 18.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"
26#include "llvm/IR/Constant.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DebugLoc.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/Use.h"
35#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
44#include <cassert>
45#include <cstdint>
46#include <functional>
47#include <tuple>
48#include <type_traits>
49#include <utility>
50
51namespace llvm {
52class AssumptionCache;
53class DataLayout;
54class DominatorTree;
55class LLVMContext;
56} // namespace llvm
57
58using namespace llvm;
59
60#define DEBUG_TYPE "instcombine"
61
62STATISTIC(NegatorTotalNegationsAttempted,
63 "Negator: Number of negations attempted to be sinked");
64STATISTIC(NegatorNumTreesNegated,
65 "Negator: Number of negations successfully sinked");
66STATISTIC(NegatorMaxDepthVisited, "Negator: Maximal traversal depth ever "
67 "reached while attempting to sink negation");
68STATISTIC(NegatorTimesDepthLimitReached,
69 "Negator: How many times did the traversal depth limit was reached "
70 "during sinking");
72 NegatorNumValuesVisited,
73 "Negator: Total number of values visited during attempts to sink negation");
74STATISTIC(NegatorNumNegationsFoundInCache,
75 "Negator: How many negations did we retrieve/reuse from cache");
76STATISTIC(NegatorMaxTotalValuesVisited,
77 "Negator: Maximal number of values ever visited while attempting to "
78 "sink negation");
79STATISTIC(NegatorNumInstructionsCreatedTotal,
80 "Negator: Number of new negated instructions created, total");
81STATISTIC(NegatorMaxInstructionsCreated,
82 "Negator: Maximal number of new instructions created during negation "
83 "attempt");
84STATISTIC(NegatorNumInstructionsNegatedSuccess,
85 "Negator: Number of new negated instructions created in successful "
86 "negation sinking attempts");
87
88DEBUG_COUNTER(NegatorCounter, "instcombine-negator",
89 "Controls Negator transformations in InstCombine pass");
90
91static cl::opt<bool>
92 NegatorEnabled("instcombine-negator-enabled", cl::init(true),
93 cl::desc("Should we attempt to sink negations?"));
94
96 NegatorMaxDepth("instcombine-negator-max-depth",
98 cl::desc("What is the maximal lookup depth when trying to "
99 "check for viability of negation sinking."));
100
101Negator::Negator(LLVMContext &C, const DataLayout &DL_, AssumptionCache &AC_,
102 const DominatorTree &DT_, bool IsTrulyNegation_)
103 : Builder(C, TargetFolder(DL_),
105 ++NegatorNumInstructionsCreatedTotal;
106 NewInstructions.push_back(I);
107 })),
108 DL(DL_), AC(AC_), DT(DT_), IsTrulyNegation(IsTrulyNegation_) {}
109
110#if LLVM_ENABLE_STATS
111Negator::~Negator() {
112 NegatorMaxTotalValuesVisited.updateMax(NumValuesVisitedInThisNegator);
113}
114#endif
115
116// Due to the InstCombine's worklist management, there are no guarantees that
117// each instruction we'll encounter has been visited by InstCombine already.
118// In particular, most importantly for us, that means we have to canonicalize
119// constants to RHS ourselves, since that is helpful sometimes.
120std::array<Value *, 2> Negator::getSortedOperandsOfBinOp(Instruction *I) {
121 assert(I->getNumOperands() == 2 && "Only for binops!");
122 std::array<Value *, 2> Ops{I->getOperand(0), I->getOperand(1)};
123 if (I->isCommutative() && InstCombiner::getComplexity(I->getOperand(0)) <
124 InstCombiner::getComplexity(I->getOperand(1)))
125 std::swap(Ops[0], Ops[1]);
126 return Ops;
127}
128
129// FIXME: can this be reworked into a worklist-based algorithm while preserving
130// the depth-first, early bailout traversal?
131[[nodiscard]] Value *Negator::visitImpl(Value *V, bool IsNSW, unsigned Depth) {
132 // -(undef) -> undef.
133 if (match(V, m_Undef()))
134 return V;
135
136 // In i1, negation can simply be ignored.
137 if (V->getType()->isIntOrIntVectorTy(1))
138 return V;
139
140 Value *X;
141
142 // -(-(X)) -> X.
143 if (match(V, m_Neg(m_Value(X))))
144 return X;
145
146 // Integral constants can be freely negated.
148 return ConstantExpr::getNeg(cast<Constant>(V), /*HasNUW=*/false,
149 /*HasNSW=*/false);
150
151 // If we have a non-instruction, then give up.
152 if (!isa<Instruction>(V))
153 return nullptr;
154
155 // If we have started with a true negation (i.e. `sub 0, %y`), then if we've
156 // got instruction that does not require recursive reasoning, we can still
157 // negate it even if it has other uses, without increasing instruction count.
158 if (!V->hasOneUse() && !IsTrulyNegation)
159 return nullptr;
160
161 auto *I = cast<Instruction>(V);
162 unsigned BitWidth = I->getType()->getScalarSizeInBits();
163
164 // We must preserve the insertion point and debug info that is set in the
165 // builder at the time this function is called.
167 // And since we are trying to negate instruction I, that tells us about the
168 // insertion point and the debug info that we need to keep.
169 Builder.SetInsertPoint(I);
170
171 // In some cases we can give the answer without further recursion.
172 switch (I->getOpcode()) {
173 case Instruction::Add: {
174 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
175 // `inc` is always negatible.
176 if (match(Ops[1], m_One()))
177 return Builder.CreateNot(Ops[0], I->getName() + ".neg");
178 break;
179 }
180 case Instruction::Xor:
181 // `not` is always negatible.
182 if (match(I, m_Not(m_Value(X))))
183 return Builder.CreateAdd(X, ConstantInt::get(X->getType(), 1),
184 I->getName() + ".neg");
185 break;
186 case Instruction::AShr:
187 case Instruction::LShr: {
188 // Right-shift sign bit smear is negatible.
189 const APInt *Op1Val;
190 if (match(I->getOperand(1), m_APInt(Op1Val)) && *Op1Val == BitWidth - 1) {
191 Value *BO = I->getOpcode() == Instruction::AShr
192 ? Builder.CreateLShr(I->getOperand(0), I->getOperand(1))
193 : Builder.CreateAShr(I->getOperand(0), I->getOperand(1));
194 if (auto *NewInstr = dyn_cast<Instruction>(BO)) {
195 NewInstr->copyIRFlags(I);
196 NewInstr->setName(I->getName() + ".neg");
197 }
198 return BO;
199 }
200 // While we could negate exact arithmetic shift:
201 // ashr exact %x, C --> sdiv exact i8 %x, -1<<C
202 // iff C != 0 and C u< bitwidth(%x), we don't want to,
203 // because division is *THAT* much worse than a shift.
204 break;
205 }
206 case Instruction::SExt:
207 case Instruction::ZExt:
208 // `*ext` of i1 is always negatible
209 if (I->getOperand(0)->getType()->isIntOrIntVectorTy(1))
210 return I->getOpcode() == Instruction::SExt
211 ? Builder.CreateZExt(I->getOperand(0), I->getType(),
212 I->getName() + ".neg")
213 : Builder.CreateSExt(I->getOperand(0), I->getType(),
214 I->getName() + ".neg");
215 break;
216 case Instruction::Select: {
217 // If both arms of the select are constants, we don't need to recurse.
218 // Therefore, this transform is not limited by uses.
219 auto *Sel = cast<SelectInst>(I);
220 Constant *TrueC, *FalseC;
221 if (match(Sel->getTrueValue(), m_ImmConstant(TrueC)) &&
222 match(Sel->getFalseValue(), m_ImmConstant(FalseC))) {
223 Constant *NegTrueC = ConstantExpr::getNeg(TrueC);
224 Constant *NegFalseC = ConstantExpr::getNeg(FalseC);
225 return Builder.CreateSelect(Sel->getCondition(), NegTrueC, NegFalseC,
226 I->getName() + ".neg", /*MDFrom=*/I);
227 }
228 break;
229 }
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 &&
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)
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))) {
329 // Of one hand of select is known to be negation of another hand,
330 // just swap the hands around.
331 auto *NewSelect = cast<SelectInst>(I->clone());
332 // Just swap the operands of the select.
333 NewSelect->swapValues();
334 // Don't swap prof metadata, we didn't change the branch behavior.
335 NewSelect->setName(I->getName() + ".neg");
336 Builder.Insert(NewSelect);
337 return NewSelect;
338 }
339 // `select` is negatible if both hands of `select` are negatible.
340 Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1);
341 if (!NegOp1) // Early return.
342 return nullptr;
343 Value *NegOp2 = negate(I->getOperand(2), IsNSW, Depth + 1);
344 if (!NegOp2)
345 return nullptr;
346 // Do preserve the metadata!
347 return Builder.CreateSelect(I->getOperand(0), NegOp1, NegOp2,
348 I->getName() + ".neg", /*MDFrom=*/I);
349 }
350 case Instruction::ShuffleVector: {
351 // `shufflevector` is negatible if both operands are negatible.
352 auto *Shuf = cast<ShuffleVectorInst>(I);
353 Value *NegOp0 = negate(I->getOperand(0), IsNSW, Depth + 1);
354 if (!NegOp0) // Early return.
355 return nullptr;
356 Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1);
357 if (!NegOp1)
358 return nullptr;
359 return Builder.CreateShuffleVector(NegOp0, NegOp1, Shuf->getShuffleMask(),
360 I->getName() + ".neg");
361 }
362 case Instruction::ExtractElement: {
363 // `extractelement` is negatible if source operand is negatible.
364 auto *EEI = cast<ExtractElementInst>(I);
365 Value *NegVector = negate(EEI->getVectorOperand(), IsNSW, Depth + 1);
366 if (!NegVector) // Early return.
367 return nullptr;
368 return Builder.CreateExtractElement(NegVector, EEI->getIndexOperand(),
369 I->getName() + ".neg");
370 }
371 case Instruction::InsertElement: {
372 // `insertelement` is negatible if both the source vector and
373 // element-to-be-inserted are negatible.
374 auto *IEI = cast<InsertElementInst>(I);
375 Value *NegVector = negate(IEI->getOperand(0), IsNSW, Depth + 1);
376 if (!NegVector) // Early return.
377 return nullptr;
378 Value *NegNewElt = negate(IEI->getOperand(1), IsNSW, Depth + 1);
379 if (!NegNewElt) // Early return.
380 return nullptr;
381 return Builder.CreateInsertElement(NegVector, NegNewElt, IEI->getOperand(2),
382 I->getName() + ".neg");
383 }
384 case Instruction::Trunc: {
385 // `trunc` is negatible if its operand is negatible.
386 Value *NegOp = negate(I->getOperand(0), /* IsNSW */ false, Depth + 1);
387 if (!NegOp) // Early return.
388 return nullptr;
389 return Builder.CreateTrunc(NegOp, I->getType(), I->getName() + ".neg");
390 }
391 case Instruction::Shl: {
392 // `shl` is negatible if the first operand is negatible.
393 IsNSW &= I->hasNoSignedWrap();
394 if (Value *NegOp0 = negate(I->getOperand(0), IsNSW, Depth + 1))
395 return Builder.CreateShl(NegOp0, I->getOperand(1), I->getName() + ".neg",
396 /* HasNUW */ false, IsNSW);
397 // Otherwise, `shl %x, C` can be interpreted as `mul %x, 1<<C`.
398 auto *Op1C = dyn_cast<Constant>(I->getOperand(1));
399 if (!Op1C || !IsTrulyNegation)
400 return nullptr;
401 return Builder.CreateMul(
402 I->getOperand(0),
403 ConstantExpr::getShl(Constant::getAllOnesValue(Op1C->getType()), Op1C),
404 I->getName() + ".neg", /* HasNUW */ false, IsNSW);
405 }
406 case Instruction::Or: {
407 if (!haveNoCommonBitsSet(I->getOperand(0), I->getOperand(1), DL, &AC, I,
408 &DT))
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 Value *Xor = Builder.CreateXor(Ops[0], ConstantExpr::getNot(C));
453 return Builder.CreateAdd(Xor, ConstantInt::get(Xor->getType(), 1),
454 I->getName() + ".neg");
455 }
456 return nullptr;
457 }
458 case Instruction::Mul: {
459 std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
460 // `mul` is negatible if one of its operands is negatible.
461 Value *NegatedOp, *OtherOp;
462 // First try the second operand, in case it's a constant it will be best to
463 // just invert it instead of sinking the `neg` deeper.
464 if (Value *NegOp1 = negate(Ops[1], /* IsNSW */ false, Depth + 1)) {
465 NegatedOp = NegOp1;
466 OtherOp = Ops[0];
467 } else if (Value *NegOp0 = negate(Ops[0], /* IsNSW */ false, Depth + 1)) {
468 NegatedOp = NegOp0;
469 OtherOp = Ops[1];
470 } else
471 // Can't negate either of them.
472 return nullptr;
473 return Builder.CreateMul(NegatedOp, OtherOp, I->getName() + ".neg",
474 /* HasNUW */ false, IsNSW && I->hasNoSignedWrap());
475 }
476 default:
477 return nullptr; // Don't know, likely not negatible for free.
478 }
479
480 llvm_unreachable("Can't get here. We always return from switch.");
481}
482
483[[nodiscard]] Value *Negator::negate(Value *V, bool IsNSW, unsigned Depth) {
484 NegatorMaxDepthVisited.updateMax(Depth);
485 ++NegatorNumValuesVisited;
486
487#if LLVM_ENABLE_STATS
488 ++NumValuesVisitedInThisNegator;
489#endif
490
491#ifndef NDEBUG
492 // We can't ever have a Value with such an address.
493 Value *Placeholder = reinterpret_cast<Value *>(static_cast<uintptr_t>(-1));
494#endif
495
496 // Did we already try to negate this value?
497 auto NegationsCacheIterator = NegationsCache.find(V);
498 if (NegationsCacheIterator != NegationsCache.end()) {
499 ++NegatorNumNegationsFoundInCache;
500 Value *NegatedV = NegationsCacheIterator->second;
501 assert(NegatedV != Placeholder && "Encountered a cycle during negation.");
502 return NegatedV;
503 }
504
505#ifndef NDEBUG
506 // We did not find a cached result for negation of V. While there,
507 // let's temporairly cache a placeholder value, with the idea that if later
508 // during negation we fetch it from cache, we'll know we're in a cycle.
509 NegationsCache[V] = Placeholder;
510#endif
511
512 // No luck. Try negating it for real.
513 Value *NegatedV = visitImpl(V, IsNSW, Depth);
514 // And cache the (real) result for the future.
515 NegationsCache[V] = NegatedV;
516
517 return NegatedV;
518}
519
520[[nodiscard]] std::optional<Negator::Result> Negator::run(Value *Root,
521 bool IsNSW) {
522 Value *Negated = negate(Root, IsNSW, /*Depth=*/0);
523 if (!Negated) {
524 // We must cleanup newly-inserted instructions, to avoid any potential
525 // endless combine looping.
526 for (Instruction *I : llvm::reverse(NewInstructions))
527 I->eraseFromParent();
528 return std::nullopt;
529 }
530 return std::make_pair(ArrayRef<Instruction *>(NewInstructions), Negated);
531}
532
533[[nodiscard]] Value *Negator::Negate(bool LHSIsZero, bool IsNSW, Value *Root,
534 InstCombinerImpl &IC) {
535 ++NegatorTotalNegationsAttempted;
536 LLVM_DEBUG(dbgs() << "Negator: attempting to sink negation into " << *Root
537 << "\n");
538
539 if (!NegatorEnabled || !DebugCounter::shouldExecute(NegatorCounter))
540 return nullptr;
541
543 IC.getDominatorTree(), LHSIsZero);
544 std::optional<Result> Res = N.run(Root, IsNSW);
545 if (!Res) { // Negation failed.
546 LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root
547 << "\n");
548 return nullptr;
549 }
550
551 LLVM_DEBUG(dbgs() << "Negator: successfully sunk negation into " << *Root
552 << "\n NEW: " << *Res->second << "\n");
553 ++NegatorNumTreesNegated;
554
555 // We must temporarily unset the 'current' insertion point and DebugLoc of the
556 // InstCombine's IRBuilder so that it won't interfere with the ones we have
557 // already specified when producing negated instructions.
561
562 // And finally, we must add newly-created instructions into the InstCombine's
563 // worklist (in a proper order!) so it can attempt to combine them.
564 LLVM_DEBUG(dbgs() << "Negator: Propagating " << Res->first.size()
565 << " instrs to InstCombine\n");
566 NegatorMaxInstructionsCreated.updateMax(Res->first.size());
567 NegatorNumInstructionsNegatedSuccess += Res->first.size();
568
569 // They are in def-use order, so nothing fancy, just insert them in order.
570 for (Instruction *I : Res->first)
571 IC.Builder.Insert(I, I->getName());
572
573 // And return the new root.
574 return Res->second;
575}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
assume Assume Builder
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:182
#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 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:167
This defines the Use class.
Class for arbitrary precision integers.
Definition: APInt.h:76
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A cache of @llvm.assume calls within a function.
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2560
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2591
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2554
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.
Definition: Constants.cpp:888
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:403
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:110
static bool shouldExecute(unsigned CounterName)
Definition: DebugCounter.h:72
A debug info location.
Definition: DebugLoc.h:33
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1993
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2431
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2419
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1119
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2001
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2494
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1428
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:212
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1997
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2356
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1745
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:145
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1335
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1407
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2453
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1318
Value * CreateSDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1382
void ClearInsertionPoint()
Clear the insertion point: created instructions will not be inserted into a block.
Definition: IRBuilder.h:169
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1447
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1510
Value * CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2115
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1352
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition: IRBuilder.h:76
const DataLayout & getDataLayout() const
Definition: InstCombiner.h:379
DominatorTree & getDominatorTree() const
Definition: InstCombiner.h:378
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
Definition: InstCombiner.h:134
BuilderTy & Builder
Definition: InstCombiner.h:59
AssumptionCache & getAssumptionCache() const
Definition: InstCombiner.h:376
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:941
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
TargetFolder - Create constants with target dependent folding.
Definition: TargetFolder.h:34
LLVM Value Representation.
Definition: Value.h:74
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:378
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1069
This provides a very simple, boring adaptor for a begin and end iterator into a range 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.
Definition: CallingConv.h:34
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:525
cst_pred_ty< is_any_apint > m_AnyIntegralConstant()
Match an integer or vector with any integral constant.
Definition: PatternMatch.h:444
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:759
match_combine_or< CastClass_match< OpTy, Instruction::Trunc >, OpTy > m_TruncOrSelf(const OpTy &Op)
specific_intval< true > m_SpecificIntAllowUndef(APInt V)
Definition: PatternMatch.h:870
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:278
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:76
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:136
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:445
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:863
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false)
Return true if the two given values are negation.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:429
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if LHS and RHS have no common bits set.
@ Xor
Bitwise or logical XOR of integers.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:184
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define N