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/Statistic.h"
19#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/TargetFolder.h"
21#include "llvm/Analysis/ValueTracking.h"
22#include "llvm/IR/IRBuilder.h"
23#include "llvm/IR/InstVisitor.h"
24#include "llvm/IR/PatternMatch.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/KnownBits.h"
27#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
28#include "llvm/Transforms/InstCombine/InstCombiner.h"
29#include "llvm/Transforms/Utils/Local.h"
30#include <cassert>
31
32#define DEBUG_TYPE "instcombine"
33
34using namespace llvm::PatternMatch;
35
36// As a default, let's assume that we want to be aggressive,
37// and attempt to traverse with no limits in attempt to sink negation.
38static constexpr unsigned NegatorDefaultMaxDepth = ~0U;
39
40// Let's guesstimate that most often we will end up visiting/producing
41// fairly small number of new instructions.
42static constexpr unsigned NegatorMaxNodesSSO = 16;
43
44namespace llvm {
45
46class AAResults;
47class APInt;
48class AssumptionCache;
49class BlockFrequencyInfo;
50class DataLayout;
51class DominatorTree;
52class GEPOperator;
53class GlobalVariable;
54class LoopInfo;
55class OptimizationRemarkEmitter;
56class ProfileSummaryInfo;
57class TargetLibraryInfo;
58class User;
59
60class LLVM_LIBRARY_VISIBILITY InstCombinerImpl final
61    : public InstCombiner,
62      public InstVisitor<InstCombinerImpl, Instruction *> {
63public:
64  InstCombinerImpl(InstCombineWorklist &Worklist, BuilderTy &Builder,
65                   bool MinimizeSize, AAResults *AA, AssumptionCache &AC,
66                   TargetLibraryInfo &TLI, TargetTransformInfo &TTI,
67                   DominatorTree &DT, OptimizationRemarkEmitter &ORE,
68                   BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
69                   const DataLayout &DL, LoopInfo *LI)
70      : InstCombiner(Worklist, Builder, MinimizeSize, AA, AC, TLI, TTI, DT, ORE,
71                     BFI, PSI, DL, LI) {}
72
73  virtual ~InstCombinerImpl() {}
74
75  /// Run the combiner over the entire worklist until it is empty.
76  ///
77  /// \returns true if the IR is changed.
78  bool run();
79
80  // Visitation implementation - Implement instruction combining for different
81  // instruction types.  The semantics are as follows:
82  // Return Value:
83  //    null        - No change was made
84  //     I          - Change was made, I is still valid, I may be dead though
85  //   otherwise    - Change was made, replace I with returned instruction
86  //
87  Instruction *visitFNeg(UnaryOperator &I);
88  Instruction *visitAdd(BinaryOperator &I);
89  Instruction *visitFAdd(BinaryOperator &I);
90  Value *OptimizePointerDifference(
91      Value *LHS, Value *RHS, Type *Ty, bool isNUW);
92  Instruction *visitSub(BinaryOperator &I);
93  Instruction *visitFSub(BinaryOperator &I);
94  Instruction *visitMul(BinaryOperator &I);
95  Instruction *visitFMul(BinaryOperator &I);
96  Instruction *visitURem(BinaryOperator &I);
97  Instruction *visitSRem(BinaryOperator &I);
98  Instruction *visitFRem(BinaryOperator &I);
99  bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I);
100  Instruction *commonIRemTransforms(BinaryOperator &I);
101  Instruction *commonIDivTransforms(BinaryOperator &I);
102  Instruction *visitUDiv(BinaryOperator &I);
103  Instruction *visitSDiv(BinaryOperator &I);
104  Instruction *visitFDiv(BinaryOperator &I);
105  Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
106  Instruction *visitAnd(BinaryOperator &I);
107  Instruction *visitOr(BinaryOperator &I);
108  bool sinkNotIntoOtherHandOfAndOrOr(BinaryOperator &I);
109  Instruction *visitXor(BinaryOperator &I);
110  Instruction *visitShl(BinaryOperator &I);
111  Value *reassociateShiftAmtsOfTwoSameDirectionShifts(
112      BinaryOperator *Sh0, const SimplifyQuery &SQ,
113      bool AnalyzeForSignBitExtraction = false);
114  Instruction *canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
115      BinaryOperator &I);
116  Instruction *foldVariableSignZeroExtensionOfVariableHighBitExtract(
117      BinaryOperator &OldAShr);
118  Instruction *visitAShr(BinaryOperator &I);
119  Instruction *visitLShr(BinaryOperator &I);
120  Instruction *commonShiftTransforms(BinaryOperator &I);
121  Instruction *visitFCmpInst(FCmpInst &I);
122  CmpInst *canonicalizeICmpPredicate(CmpInst &I);
123  Instruction *visitICmpInst(ICmpInst &I);
124  Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
125                                   BinaryOperator &I);
126  Instruction *commonCastTransforms(CastInst &CI);
127  Instruction *commonPointerCastTransforms(CastInst &CI);
128  Instruction *visitTrunc(TruncInst &CI);
129  Instruction *visitZExt(ZExtInst &CI);
130  Instruction *visitSExt(SExtInst &CI);
131  Instruction *visitFPTrunc(FPTruncInst &CI);
132  Instruction *visitFPExt(CastInst &CI);
133  Instruction *visitFPToUI(FPToUIInst &FI);
134  Instruction *visitFPToSI(FPToSIInst &FI);
135  Instruction *visitUIToFP(CastInst &CI);
136  Instruction *visitSIToFP(CastInst &CI);
137  Instruction *visitPtrToInt(PtrToIntInst &CI);
138  Instruction *visitIntToPtr(IntToPtrInst &CI);
139  Instruction *visitBitCast(BitCastInst &CI);
140  Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
141  Instruction *foldItoFPtoI(CastInst &FI);
142  Instruction *visitSelectInst(SelectInst &SI);
143  Instruction *visitCallInst(CallInst &CI);
144  Instruction *visitInvokeInst(InvokeInst &II);
145  Instruction *visitCallBrInst(CallBrInst &CBI);
146
147  Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
148  Instruction *visitPHINode(PHINode &PN);
149  Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
150  Instruction *visitAllocaInst(AllocaInst &AI);
151  Instruction *visitAllocSite(Instruction &FI);
152  Instruction *visitFree(CallInst &FI);
153  Instruction *visitLoadInst(LoadInst &LI);
154  Instruction *visitStoreInst(StoreInst &SI);
155  Instruction *visitAtomicRMWInst(AtomicRMWInst &SI);
156  Instruction *visitUnconditionalBranchInst(BranchInst &BI);
157  Instruction *visitBranchInst(BranchInst &BI);
158  Instruction *visitFenceInst(FenceInst &FI);
159  Instruction *visitSwitchInst(SwitchInst &SI);
160  Instruction *visitReturnInst(ReturnInst &RI);
161  Instruction *visitUnreachableInst(UnreachableInst &I);
162  Instruction *
163  foldAggregateConstructionIntoAggregateReuse(InsertValueInst &OrigIVI);
164  Instruction *visitInsertValueInst(InsertValueInst &IV);
165  Instruction *visitInsertElementInst(InsertElementInst &IE);
166  Instruction *visitExtractElementInst(ExtractElementInst &EI);
167  Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
168  Instruction *visitExtractValueInst(ExtractValueInst &EV);
169  Instruction *visitLandingPadInst(LandingPadInst &LI);
170  Instruction *visitVAEndInst(VAEndInst &I);
171  Instruction *visitFreeze(FreezeInst &I);
172
173  /// Specify what to return for unhandled instructions.
174  Instruction *visitInstruction(Instruction &I) { return nullptr; }
175
176  /// True when DB dominates all uses of DI except UI.
177  /// UI must be in the same block as DI.
178  /// The routine checks that the DI parent and DB are different.
179  bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
180                        const BasicBlock *DB) const;
181
182  /// Try to replace select with select operand SIOpd in SI-ICmp sequence.
183  bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
184                                 const unsigned SIOpd);
185
186  LoadInst *combineLoadToNewType(LoadInst &LI, Type *NewTy,
187                                 const Twine &Suffix = "");
188
189private:
190  void annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI);
191  bool shouldChangeType(unsigned FromBitWidth, unsigned ToBitWidth) const;
192  bool shouldChangeType(Type *From, Type *To) const;
193  Value *dyn_castNegVal(Value *V) const;
194  Type *FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
195                            SmallVectorImpl<Value *> &NewIndices);
196
197  /// Classify whether a cast is worth optimizing.
198  ///
199  /// This is a helper to decide whether the simplification of
200  /// logic(cast(A), cast(B)) to cast(logic(A, B)) should be performed.
201  ///
202  /// \param CI The cast we are interested in.
203  ///
204  /// \return true if this cast actually results in any code being generated and
205  /// if it cannot already be eliminated by some other transformation.
206  bool shouldOptimizeCast(CastInst *CI);
207
208  /// Try to optimize a sequence of instructions checking if an operation
209  /// on LHS and RHS overflows.
210  ///
211  /// If this overflow check is done via one of the overflow check intrinsics,
212  /// then CtxI has to be the call instruction calling that intrinsic.  If this
213  /// overflow check is done by arithmetic followed by a compare, then CtxI has
214  /// to be the arithmetic instruction.
215  ///
216  /// If a simplification is possible, stores the simplified result of the
217  /// operation in OperationResult and result of the overflow check in
218  /// OverflowResult, and return true.  If no simplification is possible,
219  /// returns false.
220  bool OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp, bool IsSigned,
221                             Value *LHS, Value *RHS,
222                             Instruction &CtxI, Value *&OperationResult,
223                             Constant *&OverflowResult);
224
225  Instruction *visitCallBase(CallBase &Call);
226  Instruction *tryOptimizeCall(CallInst *CI);
227  bool transformConstExprCastCall(CallBase &Call);
228  Instruction *transformCallThroughTrampoline(CallBase &Call,
229                                              IntrinsicInst &Tramp);
230
231  Value *simplifyMaskedLoad(IntrinsicInst &II);
232  Instruction *simplifyMaskedStore(IntrinsicInst &II);
233  Instruction *simplifyMaskedGather(IntrinsicInst &II);
234  Instruction *simplifyMaskedScatter(IntrinsicInst &II);
235
236  /// Transform (zext icmp) to bitwise / integer operations in order to
237  /// eliminate it.
238  ///
239  /// \param ICI The icmp of the (zext icmp) pair we are interested in.
240  /// \parem CI The zext of the (zext icmp) pair we are interested in.
241  /// \param DoTransform Pass false to just test whether the given (zext icmp)
242  /// would be transformed. Pass true to actually perform the transformation.
243  ///
244  /// \return null if the transformation cannot be performed. If the
245  /// transformation can be performed the new instruction that replaces the
246  /// (zext icmp) pair will be returned (if \p DoTransform is false the
247  /// unmodified \p ICI will be returned in this case).
248  Instruction *transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
249                                 bool DoTransform = true);
250
251  Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
252
253  bool willNotOverflowSignedAdd(const Value *LHS, const Value *RHS,
254                                const Instruction &CxtI) const {
255    return computeOverflowForSignedAdd(LHS, RHS, &CxtI) ==
256           OverflowResult::NeverOverflows;
257  }
258
259  bool willNotOverflowUnsignedAdd(const Value *LHS, const Value *RHS,
260                                  const Instruction &CxtI) const {
261    return computeOverflowForUnsignedAdd(LHS, RHS, &CxtI) ==
262           OverflowResult::NeverOverflows;
263  }
264
265  bool willNotOverflowAdd(const Value *LHS, const Value *RHS,
266                          const Instruction &CxtI, bool IsSigned) const {
267    return IsSigned ? willNotOverflowSignedAdd(LHS, RHS, CxtI)
268                    : willNotOverflowUnsignedAdd(LHS, RHS, CxtI);
269  }
270
271  bool willNotOverflowSignedSub(const Value *LHS, const Value *RHS,
272                                const Instruction &CxtI) const {
273    return computeOverflowForSignedSub(LHS, RHS, &CxtI) ==
274           OverflowResult::NeverOverflows;
275  }
276
277  bool willNotOverflowUnsignedSub(const Value *LHS, const Value *RHS,
278                                  const Instruction &CxtI) const {
279    return computeOverflowForUnsignedSub(LHS, RHS, &CxtI) ==
280           OverflowResult::NeverOverflows;
281  }
282
283  bool willNotOverflowSub(const Value *LHS, const Value *RHS,
284                          const Instruction &CxtI, bool IsSigned) const {
285    return IsSigned ? willNotOverflowSignedSub(LHS, RHS, CxtI)
286                    : willNotOverflowUnsignedSub(LHS, RHS, CxtI);
287  }
288
289  bool willNotOverflowSignedMul(const Value *LHS, const Value *RHS,
290                                const Instruction &CxtI) const {
291    return computeOverflowForSignedMul(LHS, RHS, &CxtI) ==
292           OverflowResult::NeverOverflows;
293  }
294
295  bool willNotOverflowUnsignedMul(const Value *LHS, const Value *RHS,
296                                  const Instruction &CxtI) const {
297    return computeOverflowForUnsignedMul(LHS, RHS, &CxtI) ==
298           OverflowResult::NeverOverflows;
299  }
300
301  bool willNotOverflowMul(const Value *LHS, const Value *RHS,
302                          const Instruction &CxtI, bool IsSigned) const {
303    return IsSigned ? willNotOverflowSignedMul(LHS, RHS, CxtI)
304                    : willNotOverflowUnsignedMul(LHS, RHS, CxtI);
305  }
306
307  bool willNotOverflow(BinaryOperator::BinaryOps Opcode, const Value *LHS,
308                       const Value *RHS, const Instruction &CxtI,
309                       bool IsSigned) const {
310    switch (Opcode) {
311    case Instruction::Add: return willNotOverflowAdd(LHS, RHS, CxtI, IsSigned);
312    case Instruction::Sub: return willNotOverflowSub(LHS, RHS, CxtI, IsSigned);
313    case Instruction::Mul: return willNotOverflowMul(LHS, RHS, CxtI, IsSigned);
314    default: llvm_unreachable("Unexpected opcode for overflow query");
315    }
316  }
317
318  Value *EmitGEPOffset(User *GEP);
319  Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
320  Instruction *foldCastedBitwiseLogic(BinaryOperator &I);
321  Instruction *narrowBinOp(TruncInst &Trunc);
322  Instruction *narrowMaskedBinOp(BinaryOperator &And);
323  Instruction *narrowMathIfNoOverflow(BinaryOperator &I);
324  Instruction *narrowFunnelShift(TruncInst &Trunc);
325  Instruction *optimizeBitCastFromPhi(CastInst &CI, PHINode *PN);
326  Instruction *matchSAddSubSat(SelectInst &MinMax1);
327
328  void freelyInvertAllUsersOf(Value *V);
329
330  /// Determine if a pair of casts can be replaced by a single cast.
331  ///
332  /// \param CI1 The first of a pair of casts.
333  /// \param CI2 The second of a pair of casts.
334  ///
335  /// \return 0 if the cast pair cannot be eliminated, otherwise returns an
336  /// Instruction::CastOps value for a cast that can replace the pair, casting
337  /// CI1->getSrcTy() to CI2->getDstTy().
338  ///
339  /// \see CastInst::isEliminableCastPair
340  Instruction::CastOps isEliminableCastPair(const CastInst *CI1,
341                                            const CastInst *CI2);
342
343  Value *foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &And);
344  Value *foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &Or);
345  Value *foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &Xor);
346
347  /// Optimize (fcmp)&(fcmp) or (fcmp)|(fcmp).
348  /// NOTE: Unlike most of instcombine, this returns a Value which should
349  /// already be inserted into the function.
350  Value *foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd);
351
352  Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
353                                       Instruction *CxtI, bool IsAnd,
354                                       bool IsLogical = false);
355  Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D);
356  Value *getSelectCondition(Value *A, Value *B);
357
358  Instruction *foldIntrinsicWithOverflowCommon(IntrinsicInst *II);
359  Instruction *foldFPSignBitOps(BinaryOperator &I);
360
361  // Optimize one of these forms:
362  //   and i1 Op, SI / select i1 Op, i1 SI, i1 false (if IsAnd = true)
363  //   or i1 Op, SI  / select i1 Op, i1 true, i1 SI  (if IsAnd = false)
364  // into simplier select instruction using isImpliedCondition.
365  Instruction *foldAndOrOfSelectUsingImpliedCond(Value *Op, SelectInst &SI,
366                                                 bool IsAnd);
367
368public:
369  /// Inserts an instruction \p New before instruction \p Old
370  ///
371  /// Also adds the new instruction to the worklist and returns \p New so that
372  /// it is suitable for use as the return from the visitation patterns.
373  Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
374    assert(New && !New->getParent() &&
375           "New instruction already inserted into a basic block!");
376    BasicBlock *BB = Old.getParent();
377    BB->getInstList().insert(Old.getIterator(), New); // Insert inst
378    Worklist.add(New);
379    return New;
380  }
381
382  /// Same as InsertNewInstBefore, but also sets the debug loc.
383  Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
384    New->setDebugLoc(Old.getDebugLoc());
385    return InsertNewInstBefore(New, Old);
386  }
387
388  /// A combiner-aware RAUW-like routine.
389  ///
390  /// This method is to be used when an instruction is found to be dead,
391  /// replaceable with another preexisting expression. Here we add all uses of
392  /// I to the worklist, replace all uses of I with the new value, then return
393  /// I, so that the inst combiner will know that I was modified.
394  Instruction *replaceInstUsesWith(Instruction &I, Value *V) {
395    // If there are no uses to replace, then we return nullptr to indicate that
396    // no changes were made to the program.
397    if (I.use_empty()) return nullptr;
398
399    Worklist.pushUsersToWorkList(I); // Add all modified instrs to worklist.
400
401    // If we are replacing the instruction with itself, this must be in a
402    // segment of unreachable code, so just clobber the instruction.
403    if (&I == V)
404      V = UndefValue::get(I.getType());
405
406    LLVM_DEBUG(dbgs() << "IC: Replacing " << I << "\n"
407                      << "    with " << *V << '\n');
408
409    I.replaceAllUsesWith(V);
410    MadeIRChange = true;
411    return &I;
412  }
413
414  /// Replace operand of instruction and add old operand to the worklist.
415  Instruction *replaceOperand(Instruction &I, unsigned OpNum, Value *V) {
416    Worklist.addValue(I.getOperand(OpNum));
417    I.setOperand(OpNum, V);
418    return &I;
419  }
420
421  /// Replace use and add the previously used value to the worklist.
422  void replaceUse(Use &U, Value *NewValue) {
423    Worklist.addValue(U);
424    U = NewValue;
425  }
426
427  /// Creates a result tuple for an overflow intrinsic \p II with a given
428  /// \p Result and a constant \p Overflow value.
429  Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
430                                   Constant *Overflow) {
431    Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
432    StructType *ST = cast<StructType>(II->getType());
433    Constant *Struct = ConstantStruct::get(ST, V);
434    return InsertValueInst::Create(Struct, Result, 0);
435  }
436
437  /// Create and insert the idiom we use to indicate a block is unreachable
438  /// without having to rewrite the CFG from within InstCombine.
439  void CreateNonTerminatorUnreachable(Instruction *InsertAt) {
440    auto &Ctx = InsertAt->getContext();
441    new StoreInst(ConstantInt::getTrue(Ctx),
442                  UndefValue::get(Type::getInt1PtrTy(Ctx)),
443                  InsertAt);
444  }
445
446
447  /// Combiner aware instruction erasure.
448  ///
449  /// When dealing with an instruction that has side effects or produces a void
450  /// value, we can't rely on DCE to delete the instruction. Instead, visit
451  /// methods should return the value returned by this function.
452  Instruction *eraseInstFromFunction(Instruction &I) override {
453    LLVM_DEBUG(dbgs() << "IC: ERASE " << I << '\n');
454    assert(I.use_empty() && "Cannot erase instruction that is used!");
455    salvageDebugInfo(I);
456
457    // Make sure that we reprocess all operands now that we reduced their
458    // use counts.
459    for (Use &Operand : I.operands())
460      if (auto *Inst = dyn_cast<Instruction>(Operand))
461        Worklist.add(Inst);
462
463    Worklist.remove(&I);
464    I.eraseFromParent();
465    MadeIRChange = true;
466    return nullptr; // Don't do anything with FI
467  }
468
469  void computeKnownBits(const Value *V, KnownBits &Known,
470                        unsigned Depth, const Instruction *CxtI) const {
471    llvm::computeKnownBits(V, Known, DL, Depth, &AC, CxtI, &DT);
472  }
473
474  KnownBits computeKnownBits(const Value *V, unsigned Depth,
475                             const Instruction *CxtI) const {
476    return llvm::computeKnownBits(V, DL, Depth, &AC, CxtI, &DT);
477  }
478
479  bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero = false,
480                              unsigned Depth = 0,
481                              const Instruction *CxtI = nullptr) {
482    return llvm::isKnownToBeAPowerOfTwo(V, DL, OrZero, Depth, &AC, CxtI, &DT);
483  }
484
485  bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth = 0,
486                         const Instruction *CxtI = nullptr) const {
487    return llvm::MaskedValueIsZero(V, Mask, DL, Depth, &AC, CxtI, &DT);
488  }
489
490  unsigned ComputeNumSignBits(const Value *Op, unsigned Depth = 0,
491                              const Instruction *CxtI = nullptr) const {
492    return llvm::ComputeNumSignBits(Op, DL, Depth, &AC, CxtI, &DT);
493  }
494
495  OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
496                                               const Value *RHS,
497                                               const Instruction *CxtI) const {
498    return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
499  }
500
501  OverflowResult computeOverflowForSignedMul(const Value *LHS,
502                                             const Value *RHS,
503                                             const Instruction *CxtI) const {
504    return llvm::computeOverflowForSignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
505  }
506
507  OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
508                                               const Value *RHS,
509                                               const Instruction *CxtI) const {
510    return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
511  }
512
513  OverflowResult computeOverflowForSignedAdd(const Value *LHS,
514                                             const Value *RHS,
515                                             const Instruction *CxtI) const {
516    return llvm::computeOverflowForSignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
517  }
518
519  OverflowResult computeOverflowForUnsignedSub(const Value *LHS,
520                                               const Value *RHS,
521                                               const Instruction *CxtI) const {
522    return llvm::computeOverflowForUnsignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
523  }
524
525  OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
526                                             const Instruction *CxtI) const {
527    return llvm::computeOverflowForSignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
528  }
529
530  OverflowResult computeOverflow(
531      Instruction::BinaryOps BinaryOp, bool IsSigned,
532      Value *LHS, Value *RHS, Instruction *CxtI) const;
533
534  /// Performs a few simplifications for operators which are associative
535  /// or commutative.
536  bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
537
538  /// Tries to simplify binary operations which some other binary
539  /// operation distributes over.
540  ///
541  /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
542  /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
543  /// & (B | C) -> (A&B) | (A&C)" if this is a win).  Returns the simplified
544  /// value, or null if it didn't simplify.
545  Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
546
547  /// Tries to simplify add operations using the definition of remainder.
548  ///
549  /// The definition of remainder is X % C = X - (X / C ) * C. The add
550  /// expression X % C0 + (( X / C0 ) % C1) * C0 can be simplified to
551  /// X % (C0 * C1)
552  Value *SimplifyAddWithRemainder(BinaryOperator &I);
553
554  // Binary Op helper for select operations where the expression can be
555  // efficiently reorganized.
556  Value *SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS,
557                                        Value *RHS);
558
559  /// This tries to simplify binary operations by factorizing out common terms
560  /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
561  Value *tryFactorization(BinaryOperator &, Instruction::BinaryOps, Value *,
562                          Value *, Value *, Value *);
563
564  /// Match a select chain which produces one of three values based on whether
565  /// the LHS is less than, equal to, or greater than RHS respectively.
566  /// Return true if we matched a three way compare idiom. The LHS, RHS, Less,
567  /// Equal and Greater values are saved in the matching process and returned to
568  /// the caller.
569  bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS,
570                               ConstantInt *&Less, ConstantInt *&Equal,
571                               ConstantInt *&Greater);
572
573  /// Attempts to replace V with a simpler value based on the demanded
574  /// bits.
575  Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, KnownBits &Known,
576                                 unsigned Depth, Instruction *CxtI);
577  bool SimplifyDemandedBits(Instruction *I, unsigned Op,
578                            const APInt &DemandedMask, KnownBits &Known,
579                            unsigned Depth = 0) override;
580
581  /// Helper routine of SimplifyDemandedUseBits. It computes KnownZero/KnownOne
582  /// bits. It also tries to handle simplifications that can be done based on
583  /// DemandedMask, but without modifying the Instruction.
584  Value *SimplifyMultipleUseDemandedBits(Instruction *I,
585                                         const APInt &DemandedMask,
586                                         KnownBits &Known,
587                                         unsigned Depth, Instruction *CxtI);
588
589  /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
590  /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
591  Value *simplifyShrShlDemandedBits(
592      Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
593      const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known);
594
595  /// Tries to simplify operands to an integer instruction based on its
596  /// demanded bits.
597  bool SimplifyDemandedInstructionBits(Instruction &Inst);
598
599  virtual Value *
600  SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &UndefElts,
601                             unsigned Depth = 0,
602                             bool AllowMultipleUsers = false) override;
603
604  /// Canonicalize the position of binops relative to shufflevector.
605  Instruction *foldVectorBinop(BinaryOperator &Inst);
606  Instruction *foldVectorSelect(SelectInst &Sel);
607
608  /// Given a binary operator, cast instruction, or select which has a PHI node
609  /// as operand #0, see if we can fold the instruction into the PHI (which is
610  /// only possible if all operands to the PHI are constants).
611  Instruction *foldOpIntoPhi(Instruction &I, PHINode *PN);
612
613  /// Given an instruction with a select as one operand and a constant as the
614  /// other operand, try to fold the binary operator into the select arguments.
615  /// This also works for Cast instructions, which obviously do not have a
616  /// second operand.
617  Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
618
619  /// This is a convenience wrapper function for the above two functions.
620  Instruction *foldBinOpIntoSelectOrPhi(BinaryOperator &I);
621
622  Instruction *foldAddWithConstant(BinaryOperator &Add);
623
624  /// Try to rotate an operation below a PHI node, using PHI nodes for
625  /// its operands.
626  Instruction *foldPHIArgOpIntoPHI(PHINode &PN);
627  Instruction *foldPHIArgBinOpIntoPHI(PHINode &PN);
628  Instruction *foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN);
629  Instruction *foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN);
630  Instruction *foldPHIArgGEPIntoPHI(PHINode &PN);
631  Instruction *foldPHIArgLoadIntoPHI(PHINode &PN);
632  Instruction *foldPHIArgZextsIntoPHI(PHINode &PN);
633
634  /// If an integer typed PHI has only one use which is an IntToPtr operation,
635  /// replace the PHI with an existing pointer typed PHI if it exists. Otherwise
636  /// insert a new pointer typed PHI and replace the original one.
637  Instruction *foldIntegerTypedPHI(PHINode &PN);
638
639  /// Helper function for FoldPHIArgXIntoPHI() to set debug location for the
640  /// folded operation.
641  void PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN);
642
643  Instruction *foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
644                           ICmpInst::Predicate Cond, Instruction &I);
645  Instruction *foldAllocaCmp(ICmpInst &ICI, const AllocaInst *Alloca,
646                             const Value *Other);
647  Instruction *foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
648                                            GlobalVariable *GV, CmpInst &ICI,
649                                            ConstantInt *AndCst = nullptr);
650  Instruction *foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
651                                    Constant *RHSC);
652  Instruction *foldICmpAddOpConst(Value *X, const APInt &C,
653                                  ICmpInst::Predicate Pred);
654  Instruction *foldICmpWithCastOp(ICmpInst &ICI);
655
656  Instruction *foldICmpUsingKnownBits(ICmpInst &Cmp);
657  Instruction *foldICmpWithDominatingICmp(ICmpInst &Cmp);
658  Instruction *foldICmpWithConstant(ICmpInst &Cmp);
659  Instruction *foldICmpInstWithConstant(ICmpInst &Cmp);
660  Instruction *foldICmpInstWithConstantNotInt(ICmpInst &Cmp);
661  Instruction *foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ);
662  Instruction *foldICmpEquality(ICmpInst &Cmp);
663  Instruction *foldIRemByPowerOfTwoToBitTest(ICmpInst &I);
664  Instruction *foldSignBitTest(ICmpInst &I);
665  Instruction *foldICmpWithZero(ICmpInst &Cmp);
666
667  Value *foldUnsignedMultiplicationOverflowCheck(ICmpInst &Cmp);
668
669  Instruction *foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select,
670                                      ConstantInt *C);
671  Instruction *foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc,
672                                     const APInt &C);
673  Instruction *foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And,
674                                   const APInt &C);
675  Instruction *foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor,
676                                   const APInt &C);
677  Instruction *foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
678                                  const APInt &C);
679  Instruction *foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul,
680                                   const APInt &C);
681  Instruction *foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl,
682                                   const APInt &C);
683  Instruction *foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr,
684                                   const APInt &C);
685  Instruction *foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
686                                    const APInt &C);
687  Instruction *foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
688                                    const APInt &C);
689  Instruction *foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div,
690                                   const APInt &C);
691  Instruction *foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub,
692                                   const APInt &C);
693  Instruction *foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add,
694                                   const APInt &C);
695  Instruction *foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And,
696                                     const APInt &C1);
697  Instruction *foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
698                                const APInt &C1, const APInt &C2);
699  Instruction *foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
700                                     const APInt &C2);
701  Instruction *foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
702                                     const APInt &C2);
703
704  Instruction *foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
705                                                 BinaryOperator *BO,
706                                                 const APInt &C);
707  Instruction *foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
708                                             const APInt &C);
709  Instruction *foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
710                                               const APInt &C);
711
712  // Helpers of visitSelectInst().
713  Instruction *foldSelectExtConst(SelectInst &Sel);
714  Instruction *foldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
715  Instruction *foldSelectIntoOp(SelectInst &SI, Value *, Value *);
716  Instruction *foldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
717                            Value *A, Value *B, Instruction &Outer,
718                            SelectPatternFlavor SPF2, Value *C);
719  Instruction *foldSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
720  Instruction *foldSelectValueEquivalence(SelectInst &SI, ICmpInst &ICI);
721
722  Value *insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
723                         bool isSigned, bool Inside);
724  Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
725  bool mergeStoreIntoSuccessor(StoreInst &SI);
726
727  /// Given an initial instruction, check to see if it is the root of a
728  /// bswap/bitreverse idiom. If so, return the equivalent bswap/bitreverse
729  /// intrinsic.
730  Instruction *matchBSwapOrBitReverse(Instruction &I, bool MatchBSwaps,
731                                      bool MatchBitReversals);
732
733  Instruction *SimplifyAnyMemTransfer(AnyMemTransferInst *MI);
734  Instruction *SimplifyAnyMemSet(AnyMemSetInst *MI);
735
736  Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
737
738  /// Returns a value X such that Val = X * Scale, or null if none.
739  ///
740  /// If the multiplication is known not to overflow then NoSignedWrap is set.
741  Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
742};
743
744class Negator final {
745  /// Top-to-bottom, def-to-use negated instruction tree we produced.
746  SmallVector<Instruction *, NegatorMaxNodesSSO> NewInstructions;
747
748  using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
749  BuilderTy Builder;
750
751  const DataLayout &DL;
752  AssumptionCache &AC;
753  const DominatorTree &DT;
754
755  const bool IsTrulyNegation;
756
757  SmallDenseMap<Value *, Value *> NegationsCache;
758
759  Negator(LLVMContext &C, const DataLayout &DL, AssumptionCache &AC,
760          const DominatorTree &DT, bool IsTrulyNegation);
761
762#if LLVM_ENABLE_STATS
763  unsigned NumValuesVisitedInThisNegator = 0;
764  ~Negator();
765#endif
766
767  using Result = std::pair<ArrayRef<Instruction *> /*NewInstructions*/,
768                           Value * /*NegatedRoot*/>;
769
770  std::array<Value *, 2> getSortedOperandsOfBinOp(Instruction *I);
771
772  LLVM_NODISCARD Value *visitImpl(Value *V, unsigned Depth);
773
774  LLVM_NODISCARD Value *negate(Value *V, unsigned Depth);
775
776  /// Recurse depth-first and attempt to sink the negation.
777  /// FIXME: use worklist?
778  LLVM_NODISCARD Optional<Result> run(Value *Root);
779
780  Negator(const Negator &) = delete;
781  Negator(Negator &&) = delete;
782  Negator &operator=(const Negator &) = delete;
783  Negator &operator=(Negator &&) = delete;
784
785public:
786  /// Attempt to negate \p Root. Retuns nullptr if negation can't be performed,
787  /// otherwise returns negated value.
788  LLVM_NODISCARD static Value *Negate(bool LHSIsZero, Value *Root,
789                                      InstCombinerImpl &IC);
790};
791
792} // end namespace llvm
793
794#undef DEBUG_TYPE
795
796#endif // LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
797