1//===- InstCombineInternal.h - InstCombine pass internals -------*- 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/// \file
10///
11/// This file provides internal interfaces used to implement the InstCombine.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
16#define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
17
18#include "llvm/ADT/PostOrderIterator.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/TargetFolder.h"
22#include "llvm/Analysis/ValueTracking.h"
23#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/InstVisitor.h"
25#include "llvm/IR/PatternMatch.h"
26#include "llvm/IR/ProfDataUtils.h"
27#include "llvm/IR/Value.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/KnownBits.h"
30#include "llvm/Support/KnownFPClass.h"
31#include "llvm/Transforms/InstCombine/InstCombiner.h"
32#include "llvm/Transforms/Utils/Local.h"
33#include <cassert>
34
35#define DEBUG_TYPE "instcombine"
36#include "llvm/Transforms/Utils/InstructionWorklist.h"
37
38// As a default, let's assume that we want to be aggressive,
39// and attempt to traverse with no limits in attempt to sink negation.
40static constexpr unsigned NegatorDefaultMaxDepth = ~0U;
41
42// Let's guesstimate that most often we will end up visiting/producing
43// fairly small number of new instructions.
44static constexpr unsigned NegatorMaxNodesSSO = 16;
45
46namespace llvm {
47
48class AAResults;
49class APInt;
50class AssumptionCache;
51class BlockFrequencyInfo;
52class DataLayout;
53class DominatorTree;
54class GEPOperator;
55class GlobalVariable;
56class OptimizationRemarkEmitter;
57class ProfileSummaryInfo;
58class TargetLibraryInfo;
59class User;
60
61/// Enum to specify how shift operations should be evaluated in
62/// canEvaluateShifted.
63/// Lossy: Allows lossy transformations
64/// Signed: Requires lossless transformation, using ashr to restore for shl,
65/// or represents ashr handling for right shifts
66/// Unsigned: Requires lossless transformation, using lshr to restore for shl,
67/// or represents lshr handling for right shifts
68enum class ShiftSemantics { Lossy, Signed, Unsigned };
69
70class LLVM_LIBRARY_VISIBILITY InstCombinerImpl final
71 : public InstCombiner,
72 public InstVisitor<InstCombinerImpl, Instruction *> {
73public:
74 InstCombinerImpl(InstructionWorklist &Worklist, Function &F, AAResults *AA,
75 AssumptionCache &AC, TargetLibraryInfo &TLI,
76 TargetTransformInfo &TTI, DominatorTree &DT,
77 OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
78 BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI,
79 const DataLayout &DL,
80 ReversePostOrderTraversal<BasicBlock *> &RPOT)
81 : InstCombiner(Worklist, F, AA, AC, TLI, TTI, DT, ORE, BFI, BPI, PSI, DL,
82 RPOT) {}
83
84 ~InstCombinerImpl() override = default;
85
86 /// Perform early cleanup and prepare the InstCombine worklist.
87 bool prepareWorklist(Function &F);
88
89 /// Run the combiner over the entire worklist until it is empty.
90 ///
91 /// \returns true if the IR is changed.
92 bool run();
93
94 // Visitation implementation - Implement instruction combining for different
95 // instruction types. The semantics are as follows:
96 // Return Value:
97 // null - No change was made
98 // I - Change was made, I is still valid, I may be dead though
99 // otherwise - Change was made, replace I with returned instruction
100 //
101 Instruction *visitFNeg(UnaryOperator &I);
102 Instruction *visitAdd(BinaryOperator &I);
103 Instruction *visitFAdd(BinaryOperator &I);
104 Value *OptimizePointerDifference(
105 Value *LHS, Value *RHS, Type *Ty, bool isNUW);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitFSub(BinaryOperator &I);
108 Instruction *visitMul(BinaryOperator &I);
109 Instruction *foldPowiReassoc(BinaryOperator &I);
110 Instruction *foldFMulReassoc(BinaryOperator &I);
111 Instruction *visitFMul(BinaryOperator &I);
112 Instruction *visitURem(BinaryOperator &I);
113 Instruction *visitSRem(BinaryOperator &I);
114 Instruction *visitFRem(BinaryOperator &I);
115 bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I);
116 Instruction *commonIDivRemTransforms(BinaryOperator &I);
117 Instruction *commonIRemTransforms(BinaryOperator &I);
118 Instruction *commonIDivTransforms(BinaryOperator &I);
119 Instruction *visitUDiv(BinaryOperator &I);
120 Instruction *visitSDiv(BinaryOperator &I);
121 Instruction *visitFDiv(BinaryOperator &I);
122 Value *simplifyRangeCheck(CmpPredicate PredL, Value *LHS0, Value *LHS1,
123 CmpPredicate PredR, Value *RHS0, Value *RHS1,
124 Instruction *CxtI, bool Inverted);
125 Instruction *FoldOrOfLogicalAnds(Value *Op0, Value *Op1);
126 Instruction *visitAnd(BinaryOperator &I);
127 Instruction *visitOr(BinaryOperator &I);
128 bool sinkNotIntoLogicalOp(Instruction &I);
129 bool sinkNotIntoOtherHandOfLogicalOp(Instruction &I);
130 Instruction *visitXor(BinaryOperator &I);
131 Instruction *visitShl(BinaryOperator &I);
132 Value *reassociateShiftAmtsOfTwoSameDirectionShifts(
133 BinaryOperator *Sh0, const SimplifyQuery &SQ,
134 bool AnalyzeForSignBitExtraction = false);
135 Instruction *canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
136 BinaryOperator &I);
137 Instruction *foldVariableSignZeroExtensionOfVariableHighBitExtract(
138 BinaryOperator &OldAShr);
139 Instruction *visitAShr(BinaryOperator &I);
140 Instruction *visitLShr(BinaryOperator &I);
141 Instruction *commonShiftTransforms(BinaryOperator &I);
142 Instruction *visitFCmpInst(FCmpInst &I);
143 CmpInst *canonicalizeICmpPredicate(CmpInst &I);
144 Instruction *visitICmpInst(ICmpInst &I);
145 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
146 BinaryOperator &I);
147 Instruction *commonCastTransforms(CastInst &CI);
148 Instruction *visitTrunc(TruncInst &CI);
149 Instruction *visitZExt(ZExtInst &Zext);
150 Instruction *visitSExt(SExtInst &Sext);
151 Instruction *visitFPTrunc(FPTruncInst &CI);
152 Instruction *visitFPExt(CastInst &CI);
153 Instruction *visitFPToUI(FPToUIInst &FI);
154 Instruction *visitFPToSI(FPToSIInst &FI);
155 Instruction *visitUIToFP(CastInst &CI);
156 Instruction *visitSIToFP(CastInst &CI);
157 Instruction *visitPtrToInt(PtrToIntInst &CI);
158 Instruction *visitPtrToAddr(PtrToAddrInst &CI);
159 Instruction *visitIntToPtr(IntToPtrInst &CI);
160 Instruction *visitBitCast(BitCastInst &CI);
161 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
162 template <typename FPToIntTy> Instruction *foldItoFPtoI(FPToIntTy &FI);
163 Instruction *visitSelectInst(SelectInst &SI);
164 Instruction *foldShuffledIntrinsicOperands(IntrinsicInst *II);
165 Value *foldReversedIntrinsicOperands(IntrinsicInst *II);
166 Instruction *visitCallInst(CallInst &CI);
167 Instruction *visitInvokeInst(InvokeInst &II);
168 Instruction *visitCallBrInst(CallBrInst &CBI);
169
170 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
171 Instruction *visitPHINode(PHINode &PN);
172 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
173 Instruction *visitGEPOfGEP(GetElementPtrInst &GEP, GEPOperator *Src);
174 Instruction *visitAllocaInst(AllocaInst &AI);
175 Instruction *visitAllocSite(Instruction &FI);
176 Instruction *visitFree(CallInst &FI, Value *FreedOp);
177 Instruction *visitLoadInst(LoadInst &LI);
178 Instruction *visitStoreInst(StoreInst &SI);
179 Instruction *visitAtomicRMWInst(AtomicRMWInst &SI);
180 Instruction *visitUncondBrInst(UncondBrInst &BI);
181 Instruction *visitCondBrInst(CondBrInst &BI);
182 Instruction *visitFenceInst(FenceInst &FI);
183 Instruction *visitSwitchInst(SwitchInst &SI);
184 Instruction *visitReturnInst(ReturnInst &RI);
185 Instruction *visitUnreachableInst(UnreachableInst &I);
186 Instruction *
187 foldAggregateConstructionIntoAggregateReuse(InsertValueInst &OrigIVI);
188 Instruction *visitInsertValueInst(InsertValueInst &IV);
189 Instruction *visitInsertElementInst(InsertElementInst &IE);
190 Instruction *visitExtractElementInst(ExtractElementInst &EI);
191 Instruction *simplifyBinOpSplats(ShuffleVectorInst &SVI);
192 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
193 Instruction *visitExtractValueInst(ExtractValueInst &EV);
194 Instruction *visitLandingPadInst(LandingPadInst &LI);
195 Instruction *visitVAEndInst(VAEndInst &I);
196 Value *pushFreezeToPreventPoisonFromPropagating(FreezeInst &FI);
197 bool freezeOtherUses(FreezeInst &FI);
198 Instruction *foldFreezeIntoRecurrence(FreezeInst &I, PHINode *PN);
199 Instruction *visitFreeze(FreezeInst &I);
200
201 /// Specify what to return for unhandled instructions.
202 Instruction *visitInstruction(Instruction &I) { return nullptr; }
203
204 /// True when DB dominates all uses of DI except UI.
205 /// UI must be in the same block as DI.
206 /// The routine checks that the DI parent and DB are different.
207 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
208 const BasicBlock *DB) const;
209
210 /// Try to replace select with select operand SIOpd in SI-ICmp sequence.
211 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
212 const unsigned SIOpd);
213
214 LoadInst *combineLoadToNewType(LoadInst &LI, Type *NewTy,
215 const Twine &Suffix = "");
216
217 /// Check if fmul \p MulVal, +0.0 will yield +0.0 (or signed zero is
218 /// ignorable).
219 bool fmulByZeroIsZero(Value *MulVal, FastMathFlags FMF,
220 const Instruction *CtxI) const;
221
222 std::optional<std::pair<Intrinsic::ID, SmallVector<Value *, 3>>>
223 convertOrOfShiftsToFunnelShift(Instruction &Or);
224
225private:
226 bool annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI);
227 bool isDesirableIntType(unsigned BitWidth) const;
228 bool shouldChangeType(unsigned FromBitWidth, unsigned ToBitWidth) const;
229 bool shouldChangeType(Type *From, Type *To) const;
230 Value *dyn_castNegVal(Value *V) const;
231
232 /// Classify whether a cast is worth optimizing.
233 ///
234 /// This is a helper to decide whether the simplification of
235 /// logic(cast(A), cast(B)) to cast(logic(A, B)) should be performed.
236 ///
237 /// \param CI The cast we are interested in.
238 ///
239 /// \return true if this cast actually results in any code being generated and
240 /// if it cannot already be eliminated by some other transformation.
241 bool shouldOptimizeCast(CastInst *CI);
242
243 /// Try to optimize a sequence of instructions checking if an operation
244 /// on LHS and RHS overflows.
245 ///
246 /// If this overflow check is done via one of the overflow check intrinsics,
247 /// then CtxI has to be the call instruction calling that intrinsic. If this
248 /// overflow check is done by arithmetic followed by a compare, then CtxI has
249 /// to be the arithmetic instruction.
250 ///
251 /// If a simplification is possible, stores the simplified result of the
252 /// operation in OperationResult and result of the overflow check in
253 /// OverflowResult, and return true. If no simplification is possible,
254 /// returns false.
255 bool OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp, bool IsSigned,
256 Value *LHS, Value *RHS,
257 Instruction &CtxI, Value *&OperationResult,
258 Constant *&OverflowResult);
259
260 Instruction *visitCallBase(CallBase &Call);
261 Instruction *tryOptimizeCall(CallInst *CI);
262 bool transformConstExprCastCall(CallBase &Call);
263 Instruction *transformCallThroughTrampoline(CallBase &Call,
264 IntrinsicInst &Tramp);
265
266 /// Try to optimize a call to the result of a ptrauth intrinsic, potentially
267 /// into the ptrauth call bundle:
268 /// - call(ptrauth.resign(p)), ["ptrauth"()] -> call p, ["ptrauth"()]
269 /// - call(ptrauth.sign(p)), ["ptrauth"()] -> call p
270 /// as long as the key/discriminator are the same in sign and auth-bundle,
271 /// and we don't change the key in the bundle (to a potentially-invalid key.)
272 Instruction *foldPtrAuthIntrinsicCallee(CallBase &Call);
273
274 /// Try to optimize a call to a ptrauth constant, into its ptrauth bundle:
275 /// call(ptrauth(f)), ["ptrauth"()] -> call f
276 /// as long as the key/discriminator are the same in constant and bundle.
277 Instruction *foldPtrAuthConstantCallee(CallBase &Call);
278
279 // Return (a, b) if (LHS, RHS) is known to be (a, b) or (b, a).
280 // Otherwise, return std::nullopt
281 // Currently it matches:
282 // - LHS = (select c, a, b), RHS = (select c, b, a)
283 // - LHS = (phi [a, BB0], [b, BB1]), RHS = (phi [b, BB0], [a, BB1])
284 // - LHS = min(a, b), RHS = max(a, b)
285 std::optional<std::pair<Value *, Value *>> matchSymmetricPair(Value *LHS,
286 Value *RHS);
287
288 Value *simplifyMaskedLoad(IntrinsicInst &II);
289 Instruction *simplifyMaskedStore(IntrinsicInst &II);
290 Instruction *simplifyMaskedGather(IntrinsicInst &II);
291 Instruction *simplifyMaskedScatter(IntrinsicInst &II);
292
293 /// Transform (zext icmp) to bitwise / integer operations in order to
294 /// eliminate it.
295 ///
296 /// \param ICI The icmp of the (zext icmp) pair we are interested in.
297 /// \parem CI The zext of the (zext icmp) pair we are interested in.
298 ///
299 /// \return null if the transformation cannot be performed. If the
300 /// transformation can be performed the new instruction that replaces the
301 /// (zext icmp) pair will be returned.
302 Instruction *transformZExtICmp(ICmpInst *Cmp, ZExtInst &Zext);
303
304 Instruction *transformSExtICmp(ICmpInst *Cmp, SExtInst &Sext);
305
306 bool willNotOverflowSignedAdd(const WithCache<const Value *> &LHS,
307 const WithCache<const Value *> &RHS,
308 const Instruction &CxtI) const {
309 return computeOverflowForSignedAdd(LHS, RHS, CxtI: &CxtI) ==
310 OverflowResult::NeverOverflows;
311 }
312
313 bool willNotOverflowUnsignedAdd(const WithCache<const Value *> &LHS,
314 const WithCache<const Value *> &RHS,
315 const Instruction &CxtI) const {
316 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI: &CxtI) ==
317 OverflowResult::NeverOverflows;
318 }
319
320 bool willNotOverflowAdd(const Value *LHS, const Value *RHS,
321 const Instruction &CxtI, bool IsSigned) const {
322 return IsSigned ? willNotOverflowSignedAdd(LHS, RHS, CxtI)
323 : willNotOverflowUnsignedAdd(LHS, RHS, CxtI);
324 }
325
326 bool willNotOverflowSignedSub(const Value *LHS, const Value *RHS,
327 const Instruction &CxtI) const {
328 return computeOverflowForSignedSub(LHS, RHS, CxtI: &CxtI) ==
329 OverflowResult::NeverOverflows;
330 }
331
332 bool willNotOverflowUnsignedSub(const Value *LHS, const Value *RHS,
333 const Instruction &CxtI) const {
334 return computeOverflowForUnsignedSub(LHS, RHS, CxtI: &CxtI) ==
335 OverflowResult::NeverOverflows;
336 }
337
338 bool willNotOverflowSub(const Value *LHS, const Value *RHS,
339 const Instruction &CxtI, bool IsSigned) const {
340 return IsSigned ? willNotOverflowSignedSub(LHS, RHS, CxtI)
341 : willNotOverflowUnsignedSub(LHS, RHS, CxtI);
342 }
343
344 bool willNotOverflowSignedMul(const Value *LHS, const Value *RHS,
345 const Instruction &CxtI) const {
346 return computeOverflowForSignedMul(LHS, RHS, CxtI: &CxtI) ==
347 OverflowResult::NeverOverflows;
348 }
349
350 bool willNotOverflowUnsignedMul(const Value *LHS, const Value *RHS,
351 const Instruction &CxtI,
352 bool IsNSW = false) const {
353 return computeOverflowForUnsignedMul(LHS, RHS, CxtI: &CxtI, IsNSW) ==
354 OverflowResult::NeverOverflows;
355 }
356
357 bool willNotOverflowMul(const Value *LHS, const Value *RHS,
358 const Instruction &CxtI, bool IsSigned) const {
359 return IsSigned ? willNotOverflowSignedMul(LHS, RHS, CxtI)
360 : willNotOverflowUnsignedMul(LHS, RHS, CxtI);
361 }
362
363 bool willNotOverflow(BinaryOperator::BinaryOps Opcode, const Value *LHS,
364 const Value *RHS, const Instruction &CxtI,
365 bool IsSigned) const {
366 switch (Opcode) {
367 case Instruction::Add: return willNotOverflowAdd(LHS, RHS, CxtI, IsSigned);
368 case Instruction::Sub: return willNotOverflowSub(LHS, RHS, CxtI, IsSigned);
369 case Instruction::Mul: return willNotOverflowMul(LHS, RHS, CxtI, IsSigned);
370 default: llvm_unreachable("Unexpected opcode for overflow query");
371 }
372 }
373
374 Value *EmitGEPOffset(GEPOperator *GEP, bool RewriteGEP = false);
375 /// Emit sum of multiple GEP offsets. The GEPs are processed in reverse
376 /// order.
377 Value *EmitGEPOffsets(ArrayRef<GEPOperator *> GEPs, GEPNoWrapFlags NW,
378 Type *IdxTy, bool RewriteGEPs);
379 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
380 Instruction *foldBitcastExtElt(ExtractElementInst &ExtElt);
381 Instruction *foldCastedBitwiseLogic(BinaryOperator &I);
382 Instruction *foldFBinOpOfIntCasts(BinaryOperator &I);
383 // Should only be called by `foldFBinOpOfIntCasts`.
384 Instruction *foldFBinOpOfIntCastsFromSign(
385 BinaryOperator &BO, bool OpsFromSigned, std::array<Value *, 2> IntOps,
386 Constant *Op1FpC, SmallVectorImpl<WithCache<const Value *>> &OpsKnown);
387 Instruction *foldBinopOfSextBoolToSelect(BinaryOperator &I);
388 Instruction *narrowBinOp(TruncInst &Trunc);
389 Instruction *narrowMaskedBinOp(BinaryOperator &And);
390 Instruction *narrowMathIfNoOverflow(BinaryOperator &I);
391 Instruction *narrowFunnelShift(TruncInst &Trunc);
392 Instruction *optimizeBitCastFromPhi(CastInst &CI, PHINode *PN);
393 Instruction *matchSAddSubSat(IntrinsicInst &MinMax1);
394 Instruction *foldNot(BinaryOperator &I);
395 Instruction *foldBinOpOfDisplacedShifts(BinaryOperator &I);
396
397 /// Determine if a pair of casts can be replaced by a single cast.
398 ///
399 /// \param CI1 The first of a pair of casts.
400 /// \param CI2 The second of a pair of casts.
401 ///
402 /// \return 0 if the cast pair cannot be eliminated, otherwise returns an
403 /// Instruction::CastOps value for a cast that can replace the pair, casting
404 /// CI1->getSrcTy() to CI2->getDstTy().
405 ///
406 /// \see CastInst::isEliminableCastPair
407 Instruction::CastOps isEliminableCastPair(const CastInst *CI1,
408 const CastInst *CI2);
409 Value *simplifyIntToPtrRoundTripCast(Value *Val);
410
411 Value *foldAndOrOfICmps(Value *LHS, Value *RHS, Instruction &I, bool IsAnd,
412 bool IsLogical = false);
413 Value *foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &Xor);
414
415 Value *foldEqOfParts(Value *Cmp0, Value *Cmp1, bool IsAnd);
416
417 Value *foldAndOrOfICmpsUsingRanges(CmpPredicate PredL, Value *LHS0,
418 Value *LHS1, bool LHSOneUse,
419 CmpPredicate PredR, Value *RHS0,
420 Value *RHS1, bool RHSOneUse, bool IsAnd);
421
422 /// Optimize (fcmp)&(fcmp) or (fcmp)|(fcmp).
423 /// NOTE: Unlike most of instcombine, this returns a Value which should
424 /// already be inserted into the function.
425 Value *foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd,
426 bool IsLogicalSelect = false);
427
428 Instruction *foldLogicOfIsFPClass(BinaryOperator &Operator, Value *LHS,
429 Value *RHS);
430
431 Value *foldBooleanAndOr(Value *LHS, Value *RHS, Instruction &I, bool IsAnd,
432 bool IsLogical);
433
434 Value *reassociateBooleanAndOr(Value *LHS, Value *X, Value *Y, Instruction &I,
435 bool IsAnd, bool RHSIsLogical);
436
437 Value *foldDisjointOr(Value *LHS, Value *RHS);
438
439 Value *reassociateDisjointOr(Value *LHS, Value *RHS);
440
441 Instruction *
442 canonicalizeConditionalNegationViaMathToSelect(BinaryOperator &i);
443
444 Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D,
445 bool InvertFalseVal = false);
446 Value *getSelectCondition(Value *A, Value *B, bool ABIsTheSame);
447
448 bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
449 ShiftSemantics Semantics, Instruction *CxtI);
450 Value *getShiftedValue(Value *V, unsigned NumBits, bool IsLeftShift,
451 ShiftSemantics Semantics);
452
453 Instruction *foldLShrOverflowBit(BinaryOperator &I);
454 Instruction *foldExtractOfOverflowIntrinsic(ExtractValueInst &EV);
455 Instruction *foldIntrinsicWithOverflowCommon(IntrinsicInst *II);
456 Instruction *foldIntrinsicIsFPClass(IntrinsicInst &II);
457 Instruction *foldFPSignBitOps(BinaryOperator &I);
458 Instruction *foldFDivConstantDivisor(BinaryOperator &I);
459
460 // Optimize one of these forms:
461 // and i1 Op, SI / select i1 Op, i1 SI, i1 false (if IsAnd = true)
462 // or i1 Op, SI / select i1 Op, i1 true, i1 SI (if IsAnd = false)
463 // into simplier select instruction using isImpliedCondition.
464 Instruction *foldAndOrOfSelectUsingImpliedCond(Value *Op, SelectInst &SI,
465 bool IsAnd);
466
467 Instruction *hoistFNegAboveFMulFDiv(Value *FNegOp, Instruction &FMFSource);
468
469 /// Simplify \p V given that it is known to be non-null.
470 /// Returns the simplified value if possible, otherwise returns nullptr.
471 /// If \p HasDereferenceable is true, the simplification will not perform
472 /// same object checks.
473 Value *simplifyNonNullOperand(Value *V, bool HasDereferenceable,
474 unsigned Depth = 0);
475
476 /// Create `select C, S1, S2`. Use only when the profile cannot be calculated
477 /// from existing profile metadata: if the Function has profiles, this will
478 /// set the profile of this select to "unknown".
479 SelectInst *
480 createSelectInstWithUnknownProfile(Value *C, Value *S1, Value *S2,
481 const Twine &NameStr = "",
482 InsertPosition InsertBefore = nullptr) {
483 auto *Sel = SelectInst::Create(C, S1, S2, NameStr, InsertBefore, MDFrom: nullptr);
484 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *Sel, DEBUG_TYPE, F: &F);
485 return Sel;
486 }
487
488public:
489 /// Create and insert the idiom we use to indicate a block is unreachable
490 /// without having to rewrite the CFG from within InstCombine.
491 void CreateNonTerminatorUnreachable(Instruction *InsertAt) {
492 auto &Ctx = InsertAt->getContext();
493 auto *SI = new StoreInst(ConstantInt::getTrue(Context&: Ctx),
494 PoisonValue::get(T: PointerType::getUnqual(C&: Ctx)),
495 /*isVolatile*/ false, Align(1));
496 InsertNewInstWith(New: SI, Old: InsertAt->getIterator());
497 }
498
499 /// Combiner aware instruction erasure.
500 ///
501 /// When dealing with an instruction that has side effects or produces a void
502 /// value, we can't rely on DCE to delete the instruction. Instead, visit
503 /// methods should return the value returned by this function.
504 Instruction *eraseInstFromFunction(Instruction &I) override {
505 LLVM_DEBUG(dbgs() << "IC: ERASE " << I << '\n');
506 assert(I.use_empty() && "Cannot erase instruction that is used!");
507 salvageDebugInfo(I);
508
509 // Make sure that we reprocess all operands now that we reduced their
510 // use counts.
511 SmallVector<Value *> Ops(I.operands());
512 Worklist.remove(I: &I);
513 DC.removeValue(V: &I);
514 I.eraseFromParent();
515 for (Value *Op : Ops)
516 Worklist.handleUseCountDecrement(V: Op);
517 MadeIRChange = true;
518 return nullptr; // Don't do anything with FI
519 }
520
521 OverflowResult computeOverflow(
522 Instruction::BinaryOps BinaryOp, bool IsSigned,
523 Value *LHS, Value *RHS, Instruction *CxtI) const;
524
525 /// Performs a few simplifications for operators which are associative
526 /// or commutative.
527 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
528
529 /// Tries to simplify binary operations which some other binary
530 /// operation distributes over.
531 ///
532 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
533 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
534 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
535 /// value, or null if it didn't simplify.
536 Value *foldUsingDistributiveLaws(BinaryOperator &I);
537
538 /// Tries to simplify add operations using the definition of remainder.
539 ///
540 /// The definition of remainder is X % C = X - (X / C ) * C. The add
541 /// expression X % C0 + (( X / C0 ) % C1) * C0 can be simplified to
542 /// X % (C0 * C1)
543 Value *SimplifyAddWithRemainder(BinaryOperator &I);
544
545 // Binary Op helper for select operations where the expression can be
546 // efficiently reorganized.
547 Value *SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS,
548 Value *RHS);
549
550 // If `I` has operand `(ctpop (not x))`, fold `I` with `(sub nuw nsw
551 // BitWidth(x), (ctpop x))`.
552 Instruction *tryFoldInstWithCtpopWithNot(Instruction *I);
553
554 // (Binop1 (Binop2 (logic_shift X, C), C1), (logic_shift Y, C))
555 // -> (logic_shift (Binop1 (Binop2 X, inv_logic_shift(C1, C)), Y), C)
556 // (Binop1 (Binop2 (logic_shift X, Amt), Mask), (logic_shift Y, Amt))
557 // -> (BinOp (logic_shift (BinOp X, Y)), Mask)
558 Instruction *foldBinOpShiftWithShift(BinaryOperator &I);
559
560 /// Tries to simplify binops of select and cast of the select condition.
561 ///
562 /// (Binop (cast C), (select C, T, F))
563 /// -> (select C, C0, C1)
564 Instruction *foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I);
565 /// Fold both forms of the div_ceil idiom:
566 /// (add (udiv X, Y), (zext (icmp ne (urem X, Y), 0)))
567 /// -> (udiv (add nuw X, Y-1), Y)
568 /// (add (zext (udiv X, Y)), (zext (icmp ne (urem X, Y), 0)))
569 /// -> (zext (udiv (add nuw X, Y-1), Y))
570 Instruction *foldDivCeil(BinaryOperator &I);
571
572 /// This tries to simplify binary operations by factorizing out common terms
573 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
574 Value *tryFactorizationFolds(BinaryOperator &I);
575
576 /// Match a select chain which produces one of three values based on whether
577 /// the LHS is less than, equal to, or greater than RHS respectively.
578 /// Return true if we matched a three way compare idiom. The LHS, RHS, Less,
579 /// Equal and Greater values are saved in the matching process and returned to
580 /// the caller.
581 bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS,
582 ConstantInt *&Less, ConstantInt *&Equal,
583 ConstantInt *&Greater);
584
585 /// Attempts to replace I with a simpler value based on the demanded
586 /// bits.
587 Value *SimplifyDemandedUseBits(Instruction *I, const APInt &DemandedMask,
588 KnownBits &Known, const SimplifyQuery &Q,
589 unsigned Depth = 0);
590 using InstCombiner::SimplifyDemandedBits;
591 bool SimplifyDemandedBits(Instruction *I, unsigned Op,
592 const APInt &DemandedMask, KnownBits &Known,
593 const SimplifyQuery &Q,
594 unsigned Depth = 0) override;
595
596 /// Helper routine of SimplifyDemandedUseBits. It computes KnownZero/KnownOne
597 /// bits. It also tries to handle simplifications that can be done based on
598 /// DemandedMask, but without modifying the Instruction.
599 Value *SimplifyMultipleUseDemandedBits(Instruction *I,
600 const APInt &DemandedMask,
601 KnownBits &Known,
602 const SimplifyQuery &Q,
603 unsigned Depth = 0);
604
605 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
606 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
607 Value *simplifyShrShlDemandedBits(
608 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
609 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known);
610
611 /// Tries to simplify operands to an integer instruction based on its
612 /// demanded bits.
613 bool SimplifyDemandedInstructionBits(Instruction &Inst);
614 bool SimplifyDemandedInstructionBits(Instruction &Inst, KnownBits &Known);
615
616 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
617 APInt &PoisonElts, unsigned Depth = 0,
618 bool AllowMultipleUsers = false) override;
619
620 /// Attempts to replace V with a simpler value based on the demanded
621 /// floating-point classes
622 Value *SimplifyDemandedUseFPClass(Instruction *I, FPClassTest DemandedMask,
623 KnownFPClass &Known, const SimplifyQuery &Q,
624 unsigned Depth = 0);
625 Value *SimplifyMultipleUseDemandedFPClass(Instruction *I,
626 FPClassTest DemandedMask,
627 KnownFPClass &Known,
628 const SimplifyQuery &Q,
629 unsigned Depth);
630
631 bool SimplifyDemandedFPClass(Instruction *I, unsigned Op,
632 FPClassTest DemandedMask, KnownFPClass &Known,
633 const SimplifyQuery &Q, unsigned Depth = 0);
634
635 bool SimplifyDemandedInstructionFPClass(Instruction &Inst);
636
637 /// Common transforms for add / disjoint or
638 Instruction *foldAddLikeCommutative(Value *LHS, Value *RHS, bool NSW,
639 bool NUW);
640
641 /// Canonicalize the position of binops relative to shufflevector.
642 Instruction *foldVectorBinop(BinaryOperator &Inst);
643 Instruction *foldVectorSelect(SelectInst &Sel);
644 Instruction *foldSelectShuffle(ShuffleVectorInst &Shuf);
645 Constant *unshuffleConstant(ArrayRef<int> ShMask, Constant *C,
646 VectorType *NewCTy);
647
648 /// Given a binary operator, cast instruction, or select which has a PHI node
649 /// as operand #0, see if we can fold the instruction into the PHI (which is
650 /// only possible if all operands to the PHI are constants).
651 Instruction *foldOpIntoPhi(Instruction &I, PHINode *PN,
652 bool AllowMultipleUses = false);
653
654 /// Try to fold binary operators whose operands are simple interleaved
655 /// recurrences to a single recurrence. This is a common pattern in reduction
656 /// operations.
657 /// Example:
658 /// %phi1 = phi [init1, %BB1], [%op1, %BB2]
659 /// %phi2 = phi [init2, %BB1], [%op2, %BB2]
660 /// %op1 = binop %phi1, constant1
661 /// %op2 = binop %phi2, constant2
662 /// %rdx = binop %op1, %op2
663 /// -->
664 /// %phi_combined = phi [init_combined, %BB1], [%op_combined, %BB2]
665 /// %rdx_combined = binop %phi_combined, constant_combined
666 Instruction *foldBinopWithRecurrence(BinaryOperator &BO);
667
668 /// For a binary operator with 2 phi operands, try to hoist the binary
669 /// operation before the phi. This can result in fewer instructions in
670 /// patterns where at least one set of phi operands simplifies.
671 /// Example:
672 /// BB3: binop (phi [X, BB1], [C1, BB2]), (phi [Y, BB1], [C2, BB2])
673 /// -->
674 /// BB1: BO = binop X, Y
675 /// BB3: phi [BO, BB1], [(binop C1, C2), BB2]
676 Instruction *foldBinopWithPhiOperands(BinaryOperator &BO);
677
678 /// Given an instruction with a select as one operand and a constant as the
679 /// other operand, try to fold the binary operator into the select arguments.
680 /// This also works for Cast instructions, which obviously do not have a
681 /// second operand.
682 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
683 bool FoldWithMultiUse = false,
684 bool SimplifyBothArms = false);
685
686 Instruction *foldBinOpSelectBinOp(BinaryOperator &Op);
687
688 /// This is a convenience wrapper function for the above two functions.
689 Instruction *foldBinOpIntoSelectOrPhi(BinaryOperator &I);
690
691 Instruction *foldAddWithConstant(BinaryOperator &Add);
692
693 Instruction *foldSquareSumInt(BinaryOperator &I);
694 Instruction *foldSquareSumFP(BinaryOperator &I);
695
696 /// Try to rotate an operation below a PHI node, using PHI nodes for
697 /// its operands.
698 Instruction *foldPHIArgOpIntoPHI(PHINode &PN);
699 Instruction *foldPHIArgBinOpIntoPHI(PHINode &PN);
700 Instruction *foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN);
701 Instruction *foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN);
702 Instruction *foldPHIArgGEPIntoPHI(PHINode &PN);
703 Instruction *foldPHIArgLoadIntoPHI(PHINode &PN);
704 Instruction *foldPHIArgZextsIntoPHI(PHINode &PN);
705 Instruction *foldPHIArgIntToPtrToPHI(PHINode &PN);
706
707 /// If the phi is within a phi web, which is formed by the def-use chain
708 /// of phis and all the phis in the web are only used in the other phis.
709 /// In this case, these phis are dead and we will remove all of them.
710 bool foldDeadPhiWeb(PHINode &PN);
711
712 /// If an integer typed PHI has only one use which is an IntToPtr operation,
713 /// replace the PHI with an existing pointer typed PHI if it exists. Otherwise
714 /// insert a new pointer typed PHI and replace the original one.
715 bool foldIntegerTypedPHI(PHINode &PN);
716
717 /// Helper function for FoldPHIArgXIntoPHI() to set debug location for the
718 /// folded operation.
719 void PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN);
720
721 Value *foldPtrToIntOrAddrOfGEP(Type *IntTy, Value *Ptr);
722 Instruction *foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond,
723 Instruction &I);
724 Instruction *foldSelectICmp(CmpPredicate Pred, SelectInst *SI, Value *RHS,
725 const ICmpInst &I);
726 bool foldAllocaCmp(AllocaInst *Alloca);
727 Instruction *foldCmpLoadFromIndexedGlobal(LoadInst *LI,
728 GetElementPtrInst *GEP,
729 CmpInst &ICI,
730 ConstantInt *AndCst = nullptr);
731 Instruction *foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
732 Constant *RHSC);
733 Instruction *foldICmpAddOpConst(Value *X, const APInt &C, CmpPredicate Pred);
734 Instruction *foldCmpSelectOfConstants(CmpInst &I);
735 Instruction *foldICmpWithCastOp(ICmpInst &ICmp);
736 Instruction *foldICmpWithZextOrSext(ICmpInst &ICmp);
737
738 Instruction *foldICmpUsingKnownBits(ICmpInst &Cmp);
739 Instruction *foldICmpWithDominatingICmp(ICmpInst &Cmp);
740 Instruction *foldICmpWithConstant(ICmpInst &Cmp);
741 Instruction *foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp);
742 Instruction *foldICmpUsingBoolRange(ICmpInst &I);
743 Instruction *foldICmpInstWithConstant(ICmpInst &Cmp);
744 Instruction *foldICmpInstWithConstantNotInt(ICmpInst &Cmp);
745 Instruction *foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,
746 const APInt &C);
747 Instruction *foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ);
748 Instruction *foldICmpWithMinMax(Instruction &I, MinMaxIntrinsic *MinMax,
749 Value *Z, CmpPredicate Pred);
750 Instruction *foldICmpWithClamp(ICmpInst &Cmp, Value *X, MinMaxIntrinsic *Min);
751 Instruction *foldICmpEquality(ICmpInst &Cmp);
752 Instruction *foldIRemByPowerOfTwoToBitTest(ICmpInst &I);
753 Instruction *foldSignBitTest(ICmpInst &I);
754 Instruction *foldICmpWithZero(ICmpInst &Cmp);
755
756 Value *foldMultiplicationOverflowCheck(ICmpInst &Cmp);
757
758 Instruction *foldICmpBinOpWithConstant(ICmpInst &Cmp, BinaryOperator *BO,
759 const APInt &C);
760 Instruction *foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select,
761 ConstantInt *C);
762 Instruction *foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc,
763 const APInt &C);
764 Instruction *foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
765 const SimplifyQuery &Q);
766 Instruction *foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And,
767 const APInt &C);
768 Instruction *foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor,
769 const APInt &C);
770 Instruction *foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
771 const APInt &C);
772 Instruction *foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul,
773 const APInt &C);
774 Instruction *foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl,
775 const APInt &C);
776 Instruction *foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr,
777 const APInt &C);
778 Instruction *foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
779 const APInt &C);
780 Instruction *foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
781 const APInt &C);
782 Instruction *foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div,
783 const APInt &C);
784 Instruction *foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub,
785 const APInt &C);
786 Instruction *foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add,
787 const APInt &C);
788 Instruction *foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And,
789 const APInt &C1);
790 Instruction *foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
791 const APInt &C1, const APInt &C2);
792 Instruction *foldICmpXorShiftConst(ICmpInst &Cmp, BinaryOperator *Xor,
793 const APInt &C);
794 Instruction *foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
795 const APInt &C2);
796 Instruction *foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
797 const APInt &C2);
798
799 Instruction *foldICmpBinOpWithConstantViaTruthTable(ICmpInst &Cmp,
800 BinaryOperator *BO,
801 const APInt &C);
802 Instruction *foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
803 BinaryOperator *BO,
804 const APInt &C);
805 Instruction *foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
806 const APInt &C);
807 Instruction *foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
808 const APInt &C);
809 Instruction *foldICmpBitCast(ICmpInst &Cmp);
810 Instruction *foldICmpWithTrunc(ICmpInst &Cmp);
811 Instruction *foldICmpCommutative(CmpPredicate Pred, Value *Op0, Value *Op1,
812 ICmpInst &CxtI);
813
814 // Helpers of visitSelectInst().
815 Instruction *foldSelectOfBools(SelectInst &SI);
816 Instruction *foldSelectToCmp(SelectInst &SI);
817 Instruction *foldSelectExtConst(SelectInst &Sel);
818 Instruction *foldSelectEqualityTest(SelectInst &SI);
819 Instruction *foldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
820 Instruction *foldSelectIntrinsic(SelectInst &SI);
821 Instruction *foldSelectIntoOp(SelectInst &SI, Value *, Value *);
822 Instruction *foldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
823 Value *A, Value *B, Instruction &Outer,
824 SelectPatternFlavor SPF2, Value *C);
825 Instruction *foldSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
826 Value *foldSelectWithConstOpToBinOp(ICmpInst *Cmp, Value *TrueVal,
827 Value *FalseVal);
828 Instruction *foldSelectValueEquivalence(SelectInst &SI, CmpInst &CI);
829
830 Instruction *foldExtractionOfVectorDeinterleave(ZExtInst &RootZExt);
831
832 bool replaceInInstruction(Value *V, Value *Old, Value *New,
833 unsigned Depth = 0);
834
835 Value *insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
836 bool isSigned, bool Inside);
837 bool mergeStoreIntoSuccessor(StoreInst &SI);
838
839 /// Given an initial instruction, check to see if it is the root of a
840 /// bswap/bitreverse idiom. If so, return the equivalent bswap/bitreverse
841 /// intrinsic.
842 Instruction *matchBSwapOrBitReverse(Instruction &I, bool MatchBSwaps,
843 bool MatchBitReversals);
844
845 Instruction *SimplifyAnyMemTransfer(AnyMemTransferInst *MI);
846 Instruction *SimplifyAnyMemSet(AnyMemSetInst *MI);
847
848 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
849
850 bool tryToSinkInstruction(Instruction *I, BasicBlock *DestBlock);
851 void tryToSinkInstructionDbgVariableRecords(
852 Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
853 BasicBlock *DestBlock, SmallVectorImpl<DbgVariableRecord *> &DPUsers);
854
855 bool removeInstructionsBeforeUnreachable(Instruction &I);
856 void addDeadEdge(BasicBlock *From, BasicBlock *To,
857 SmallVectorImpl<BasicBlock *> &Worklist);
858 void handleUnreachableFrom(Instruction *I,
859 SmallVectorImpl<BasicBlock *> &Worklist);
860 void handlePotentiallyDeadBlocks(SmallVectorImpl<BasicBlock *> &Worklist);
861 void handlePotentiallyDeadSuccessors(BasicBlock *BB, BasicBlock *LiveSucc);
862 void freelyInvertAllUsersOf(Value *V, Value *IgnoredUser = nullptr);
863
864 /// Take the exact integer log2 of the value. If DoFold is true, create the
865 /// actual instructions, otherwise return a non-null dummy value. Return
866 /// nullptr on failure. Note, if DoFold is true the caller must ensure that
867 /// takeLog2 will succeed, otherwise it may create stray instructions.
868 Value *takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero, bool DoFold);
869
870 Value *tryGetLog2(Value *Op, bool AssumeNonZero) {
871 if (takeLog2(Op, /*Depth=*/Depth: 0, AssumeNonZero, /*DoFold=*/DoFold: false))
872 return takeLog2(Op, /*Depth=*/Depth: 0, AssumeNonZero, /*DoFold=*/DoFold: true);
873 return nullptr;
874 }
875};
876
877class Negator final {
878 /// Top-to-bottom, def-to-use negated instruction tree we produced.
879 SmallVector<Instruction *, NegatorMaxNodesSSO> NewInstructions;
880
881 using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
882 BuilderTy Builder;
883
884 const DominatorTree &DT;
885
886 const bool IsTrulyNegation;
887
888 SmallDenseMap<Value *, Value *> NegationsCache;
889
890 Negator(LLVMContext &C, const DataLayout &DL, const DominatorTree &DT,
891 bool IsTrulyNegation);
892
893#if LLVM_ENABLE_STATS
894 unsigned NumValuesVisitedInThisNegator = 0;
895 ~Negator();
896#endif
897
898 using Result = std::pair<ArrayRef<Instruction *> /*NewInstructions*/,
899 Value * /*NegatedRoot*/>;
900
901 std::array<Value *, 2> getSortedOperandsOfBinOp(Instruction *I);
902
903 [[nodiscard]] Value *visitImpl(Value *V, bool IsNSW, unsigned Depth);
904
905 [[nodiscard]] Value *negate(Value *V, bool IsNSW, unsigned Depth);
906
907 /// Recurse depth-first and attempt to sink the negation.
908 /// FIXME: use worklist?
909 [[nodiscard]] std::optional<Result> run(Value *Root, bool IsNSW);
910
911 Negator(const Negator &) = delete;
912 Negator(Negator &&) = delete;
913 Negator &operator=(const Negator &) = delete;
914 Negator &operator=(Negator &&) = delete;
915
916public:
917 /// Attempt to negate \p Root. Retuns nullptr if negation can't be performed,
918 /// otherwise returns negated value.
919 [[nodiscard]] static Value *Negate(bool LHSIsZero, bool IsNSW, Value *Root,
920 InstCombinerImpl &IC);
921};
922
923struct CommonPointerBase {
924 /// Common base pointer.
925 Value *Ptr = nullptr;
926 /// LHS GEPs until common base.
927 SmallVector<GEPOperator *> LHSGEPs;
928 /// RHS GEPs until common base.
929 SmallVector<GEPOperator *> RHSGEPs;
930 /// LHS GEP NoWrapFlags until common base.
931 GEPNoWrapFlags LHSNW = GEPNoWrapFlags::all();
932 /// RHS GEP NoWrapFlags until common base.
933 GEPNoWrapFlags RHSNW = GEPNoWrapFlags::all();
934
935 static CommonPointerBase compute(Value *LHS, Value *RHS);
936
937 /// Whether expanding the GEP chains is expensive.
938 bool isExpensive() const;
939};
940
941} // end namespace llvm
942
943#undef DEBUG_TYPE
944
945#endif // LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
946