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