]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/InstCombine/InstCombineInternal.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r302418, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Transforms / InstCombine / InstCombineInternal.h
1 //===- InstCombineInternal.h - InstCombine pass internals -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
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/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/TargetFolder.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/DIBuilder.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstVisitor.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
34 #include "llvm/Transforms/Utils/Local.h"
35
36 #define DEBUG_TYPE "instcombine"
37
38 namespace llvm {
39 class CallSite;
40 class DataLayout;
41 class DominatorTree;
42 class TargetLibraryInfo;
43 class DbgDeclareInst;
44 class MemIntrinsic;
45 class MemSetInst;
46
47 /// Assign a complexity or rank value to LLVM Values. This is used to reduce
48 /// the amount of pattern matching needed for compares and commutative
49 /// instructions. For example, if we have:
50 ///   icmp ugt X, Constant
51 /// or
52 ///   xor (add X, Constant), cast Z
53 ///
54 /// We do not have to consider the commuted variants of these patterns because
55 /// canonicalization based on complexity guarantees the above ordering.
56 ///
57 /// This routine maps IR values to various complexity ranks:
58 ///   0 -> undef
59 ///   1 -> Constants
60 ///   2 -> Other non-instructions
61 ///   3 -> Arguments
62 ///   4 -> Cast and (f)neg/not instructions
63 ///   5 -> Other instructions
64 static inline unsigned getComplexity(Value *V) {
65   if (isa<Instruction>(V)) {
66     if (isa<CastInst>(V) || BinaryOperator::isNeg(V) ||
67         BinaryOperator::isFNeg(V) || BinaryOperator::isNot(V))
68       return 4;
69     return 5;
70   }
71   if (isa<Argument>(V))
72     return 3;
73   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
74 }
75
76 /// \brief Add one to a Constant
77 static inline Constant *AddOne(Constant *C) {
78   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
79 }
80 /// \brief Subtract one from a Constant
81 static inline Constant *SubOne(Constant *C) {
82   return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
83 }
84
85 /// \brief Return true if the specified value is free to invert (apply ~ to).
86 /// This happens in cases where the ~ can be eliminated.  If WillInvertAllUses
87 /// is true, work under the assumption that the caller intends to remove all
88 /// uses of V and only keep uses of ~V.
89 ///
90 static inline bool IsFreeToInvert(Value *V, bool WillInvertAllUses) {
91   // ~(~(X)) -> X.
92   if (BinaryOperator::isNot(V))
93     return true;
94
95   // Constants can be considered to be not'ed values.
96   if (isa<ConstantInt>(V))
97     return true;
98
99   // A vector of constant integers can be inverted easily.
100   Constant *CV;
101   if (V->getType()->isVectorTy() && match(V, PatternMatch::m_Constant(CV))) {
102     unsigned NumElts = V->getType()->getVectorNumElements();
103     for (unsigned i = 0; i != NumElts; ++i) {
104       Constant *Elt = CV->getAggregateElement(i);
105       if (!Elt)
106         return false;
107
108       if (isa<UndefValue>(Elt))
109         continue;
110
111       if (!isa<ConstantInt>(Elt))
112         return false;
113     }
114     return true;
115   }
116
117   // Compares can be inverted if all of their uses are being modified to use the
118   // ~V.
119   if (isa<CmpInst>(V))
120     return WillInvertAllUses;
121
122   // If `V` is of the form `A + Constant` then `-1 - V` can be folded into `(-1
123   // - Constant) - A` if we are willing to invert all of the uses.
124   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
125     if (BO->getOpcode() == Instruction::Add ||
126         BO->getOpcode() == Instruction::Sub)
127       if (isa<Constant>(BO->getOperand(0)) || isa<Constant>(BO->getOperand(1)))
128         return WillInvertAllUses;
129
130   return false;
131 }
132
133
134 /// \brief Specific patterns of overflow check idioms that we match.
135 enum OverflowCheckFlavor {
136   OCF_UNSIGNED_ADD,
137   OCF_SIGNED_ADD,
138   OCF_UNSIGNED_SUB,
139   OCF_SIGNED_SUB,
140   OCF_UNSIGNED_MUL,
141   OCF_SIGNED_MUL,
142
143   OCF_INVALID
144 };
145
146 /// \brief Returns the OverflowCheckFlavor corresponding to a overflow_with_op
147 /// intrinsic.
148 static inline OverflowCheckFlavor
149 IntrinsicIDToOverflowCheckFlavor(unsigned ID) {
150   switch (ID) {
151   default:
152     return OCF_INVALID;
153   case Intrinsic::uadd_with_overflow:
154     return OCF_UNSIGNED_ADD;
155   case Intrinsic::sadd_with_overflow:
156     return OCF_SIGNED_ADD;
157   case Intrinsic::usub_with_overflow:
158     return OCF_UNSIGNED_SUB;
159   case Intrinsic::ssub_with_overflow:
160     return OCF_SIGNED_SUB;
161   case Intrinsic::umul_with_overflow:
162     return OCF_UNSIGNED_MUL;
163   case Intrinsic::smul_with_overflow:
164     return OCF_SIGNED_MUL;
165   }
166 }
167
168 /// \brief The core instruction combiner logic.
169 ///
170 /// This class provides both the logic to recursively visit instructions and
171 /// combine them.
172 class LLVM_LIBRARY_VISIBILITY InstCombiner
173     : public InstVisitor<InstCombiner, Instruction *> {
174   // FIXME: These members shouldn't be public.
175 public:
176   /// \brief A worklist of the instructions that need to be simplified.
177   InstCombineWorklist &Worklist;
178
179   /// \brief An IRBuilder that automatically inserts new instructions into the
180   /// worklist.
181   typedef IRBuilder<TargetFolder, IRBuilderCallbackInserter> BuilderTy;
182   BuilderTy *Builder;
183
184 private:
185   // Mode in which we are running the combiner.
186   const bool MinimizeSize;
187   /// Enable combines that trigger rarely but are costly in compiletime.
188   const bool ExpensiveCombines;
189
190   AliasAnalysis *AA;
191
192   // Required analyses.
193   AssumptionCache &AC;
194   TargetLibraryInfo &TLI;
195   DominatorTree &DT;
196   const DataLayout &DL;
197   const SimplifyQuery SQ;
198   // Optional analyses. When non-null, these can both be used to do better
199   // combining and will be updated to reflect any changes.
200   LoopInfo *LI;
201
202   bool MadeIRChange;
203
204 public:
205   InstCombiner(InstCombineWorklist &Worklist, BuilderTy *Builder,
206                bool MinimizeSize, bool ExpensiveCombines, AliasAnalysis *AA,
207                AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
208                const DataLayout &DL, LoopInfo *LI)
209       : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
210         ExpensiveCombines(ExpensiveCombines), AA(AA), AC(AC), TLI(TLI), DT(DT),
211         DL(DL), SQ(DL, &TLI, &DT, &AC), LI(LI), MadeIRChange(false) {}
212
213   /// \brief Run the combiner over the entire worklist until it is empty.
214   ///
215   /// \returns true if the IR is changed.
216   bool run();
217
218   AssumptionCache &getAssumptionCache() const { return AC; }
219
220   const DataLayout &getDataLayout() const { return DL; }
221
222   DominatorTree &getDominatorTree() const { return DT; }
223
224   LoopInfo *getLoopInfo() const { return LI; }
225
226   TargetLibraryInfo &getTargetLibraryInfo() const { return TLI; }
227
228   // Visitation implementation - Implement instruction combining for different
229   // instruction types.  The semantics are as follows:
230   // Return Value:
231   //    null        - No change was made
232   //     I          - Change was made, I is still valid, I may be dead though
233   //   otherwise    - Change was made, replace I with returned instruction
234   //
235   Instruction *visitAdd(BinaryOperator &I);
236   Instruction *visitFAdd(BinaryOperator &I);
237   Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
238   Instruction *visitSub(BinaryOperator &I);
239   Instruction *visitFSub(BinaryOperator &I);
240   Instruction *visitMul(BinaryOperator &I);
241   Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
242                        Instruction *InsertBefore);
243   Instruction *visitFMul(BinaryOperator &I);
244   Instruction *visitURem(BinaryOperator &I);
245   Instruction *visitSRem(BinaryOperator &I);
246   Instruction *visitFRem(BinaryOperator &I);
247   bool SimplifyDivRemOfSelect(BinaryOperator &I);
248   Instruction *commonRemTransforms(BinaryOperator &I);
249   Instruction *commonIRemTransforms(BinaryOperator &I);
250   Instruction *commonDivTransforms(BinaryOperator &I);
251   Instruction *commonIDivTransforms(BinaryOperator &I);
252   Instruction *visitUDiv(BinaryOperator &I);
253   Instruction *visitSDiv(BinaryOperator &I);
254   Instruction *visitFDiv(BinaryOperator &I);
255   Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
256   Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
257   Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
258   Instruction *visitAnd(BinaryOperator &I);
259   Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
260   Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
261   Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
262                                    Value *B, Value *C);
263   Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
264                                     Value *B, Value *C);
265   Instruction *visitOr(BinaryOperator &I);
266   Instruction *visitXor(BinaryOperator &I);
267   Instruction *visitShl(BinaryOperator &I);
268   Instruction *visitAShr(BinaryOperator &I);
269   Instruction *visitLShr(BinaryOperator &I);
270   Instruction *commonShiftTransforms(BinaryOperator &I);
271   Instruction *visitFCmpInst(FCmpInst &I);
272   Instruction *visitICmpInst(ICmpInst &I);
273   Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
274                                    BinaryOperator &I);
275   Instruction *commonCastTransforms(CastInst &CI);
276   Instruction *commonPointerCastTransforms(CastInst &CI);
277   Instruction *visitTrunc(TruncInst &CI);
278   Instruction *visitZExt(ZExtInst &CI);
279   Instruction *visitSExt(SExtInst &CI);
280   Instruction *visitFPTrunc(FPTruncInst &CI);
281   Instruction *visitFPExt(CastInst &CI);
282   Instruction *visitFPToUI(FPToUIInst &FI);
283   Instruction *visitFPToSI(FPToSIInst &FI);
284   Instruction *visitUIToFP(CastInst &CI);
285   Instruction *visitSIToFP(CastInst &CI);
286   Instruction *visitPtrToInt(PtrToIntInst &CI);
287   Instruction *visitIntToPtr(IntToPtrInst &CI);
288   Instruction *visitBitCast(BitCastInst &CI);
289   Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
290   Instruction *FoldItoFPtoI(Instruction &FI);
291   Instruction *visitSelectInst(SelectInst &SI);
292   Instruction *visitCallInst(CallInst &CI);
293   Instruction *visitInvokeInst(InvokeInst &II);
294
295   Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
296   Instruction *visitPHINode(PHINode &PN);
297   Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
298   Instruction *visitAllocaInst(AllocaInst &AI);
299   Instruction *visitAllocSite(Instruction &FI);
300   Instruction *visitFree(CallInst &FI);
301   Instruction *visitLoadInst(LoadInst &LI);
302   Instruction *visitStoreInst(StoreInst &SI);
303   Instruction *visitBranchInst(BranchInst &BI);
304   Instruction *visitFenceInst(FenceInst &FI);
305   Instruction *visitSwitchInst(SwitchInst &SI);
306   Instruction *visitReturnInst(ReturnInst &RI);
307   Instruction *visitInsertValueInst(InsertValueInst &IV);
308   Instruction *visitInsertElementInst(InsertElementInst &IE);
309   Instruction *visitExtractElementInst(ExtractElementInst &EI);
310   Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
311   Instruction *visitExtractValueInst(ExtractValueInst &EV);
312   Instruction *visitLandingPadInst(LandingPadInst &LI);
313   Instruction *visitVAStartInst(VAStartInst &I);
314   Instruction *visitVACopyInst(VACopyInst &I);
315
316   /// Specify what to return for unhandled instructions.
317   Instruction *visitInstruction(Instruction &I) { return nullptr; }
318
319   /// True when DB dominates all uses of DI except UI.
320   /// UI must be in the same block as DI.
321   /// The routine checks that the DI parent and DB are different.
322   bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
323                         const BasicBlock *DB) const;
324
325   /// Try to replace select with select operand SIOpd in SI-ICmp sequence.
326   bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
327                                  const unsigned SIOpd);
328
329   /// Try to replace instruction \p I with value \p V which are pointers
330   /// in different address space.
331   /// \return true if successful.
332   bool replacePointer(Instruction &I, Value *V);
333
334 private:
335   bool shouldChangeType(unsigned FromBitWidth, unsigned ToBitWidth) const;
336   bool shouldChangeType(Type *From, Type *To) const;
337   Value *dyn_castNegVal(Value *V) const;
338   Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
339   Type *FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
340                             SmallVectorImpl<Value *> &NewIndices);
341
342   /// Classify whether a cast is worth optimizing.
343   ///
344   /// This is a helper to decide whether the simplification of
345   /// logic(cast(A), cast(B)) to cast(logic(A, B)) should be performed.
346   ///
347   /// \param CI The cast we are interested in.
348   ///
349   /// \return true if this cast actually results in any code being generated and
350   /// if it cannot already be eliminated by some other transformation.
351   bool shouldOptimizeCast(CastInst *CI);
352
353   /// \brief Try to optimize a sequence of instructions checking if an operation
354   /// on LHS and RHS overflows.
355   ///
356   /// If this overflow check is done via one of the overflow check intrinsics,
357   /// then CtxI has to be the call instruction calling that intrinsic.  If this
358   /// overflow check is done by arithmetic followed by a compare, then CtxI has
359   /// to be the arithmetic instruction.
360   ///
361   /// If a simplification is possible, stores the simplified result of the
362   /// operation in OperationResult and result of the overflow check in
363   /// OverflowResult, and return true.  If no simplification is possible,
364   /// returns false.
365   bool OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS, Value *RHS,
366                              Instruction &CtxI, Value *&OperationResult,
367                              Constant *&OverflowResult);
368
369   Instruction *visitCallSite(CallSite CS);
370   Instruction *tryOptimizeCall(CallInst *CI);
371   bool transformConstExprCastCall(CallSite CS);
372   Instruction *transformCallThroughTrampoline(CallSite CS,
373                                               IntrinsicInst *Tramp);
374
375   /// Transform (zext icmp) to bitwise / integer operations in order to
376   /// eliminate it.
377   ///
378   /// \param ICI The icmp of the (zext icmp) pair we are interested in.
379   /// \parem CI The zext of the (zext icmp) pair we are interested in.
380   /// \param DoTransform Pass false to just test whether the given (zext icmp)
381   /// would be transformed. Pass true to actually perform the transformation.
382   ///
383   /// \return null if the transformation cannot be performed. If the
384   /// transformation can be performed the new instruction that replaces the
385   /// (zext icmp) pair will be returned (if \p DoTransform is false the
386   /// unmodified \p ICI will be returned in this case).
387   Instruction *transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
388                                  bool DoTransform = true);
389
390   Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
391   bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction &CxtI);
392   bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction &CxtI);
393   bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction &CxtI);
394   bool WillNotOverflowSignedMul(Value *LHS, Value *RHS, Instruction &CxtI);
395   Value *EmitGEPOffset(User *GEP);
396   Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
397   Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
398   Instruction *foldCastedBitwiseLogic(BinaryOperator &I);
399   Instruction *shrinkBitwiseLogic(TruncInst &Trunc);
400   Instruction *optimizeBitCastFromPhi(CastInst &CI, PHINode *PN);
401
402   /// Determine if a pair of casts can be replaced by a single cast.
403   ///
404   /// \param CI1 The first of a pair of casts.
405   /// \param CI2 The second of a pair of casts.
406   ///
407   /// \return 0 if the cast pair cannot be eliminated, otherwise returns an
408   /// Instruction::CastOps value for a cast that can replace the pair, casting
409   /// CI1->getSrcTy() to CI2->getDstTy().
410   ///
411   /// \see CastInst::isEliminableCastPair
412   Instruction::CastOps isEliminableCastPair(const CastInst *CI1,
413                                             const CastInst *CI2);
414
415 public:
416   /// \brief Inserts an instruction \p New before instruction \p Old
417   ///
418   /// Also adds the new instruction to the worklist and returns \p New so that
419   /// it is suitable for use as the return from the visitation patterns.
420   Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
421     assert(New && !New->getParent() &&
422            "New instruction already inserted into a basic block!");
423     BasicBlock *BB = Old.getParent();
424     BB->getInstList().insert(Old.getIterator(), New); // Insert inst
425     Worklist.Add(New);
426     return New;
427   }
428
429   /// \brief Same as InsertNewInstBefore, but also sets the debug loc.
430   Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
431     New->setDebugLoc(Old.getDebugLoc());
432     return InsertNewInstBefore(New, Old);
433   }
434
435   /// \brief A combiner-aware RAUW-like routine.
436   ///
437   /// This method is to be used when an instruction is found to be dead,
438   /// replaceable with another preexisting expression. Here we add all uses of
439   /// I to the worklist, replace all uses of I with the new value, then return
440   /// I, so that the inst combiner will know that I was modified.
441   Instruction *replaceInstUsesWith(Instruction &I, Value *V) {
442     // If there are no uses to replace, then we return nullptr to indicate that
443     // no changes were made to the program.
444     if (I.use_empty()) return nullptr;
445
446     Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
447
448     // If we are replacing the instruction with itself, this must be in a
449     // segment of unreachable code, so just clobber the instruction.
450     if (&I == V)
451       V = UndefValue::get(I.getType());
452
453     DEBUG(dbgs() << "IC: Replacing " << I << "\n"
454                  << "    with " << *V << '\n');
455
456     I.replaceAllUsesWith(V);
457     return &I;
458   }
459
460   /// Creates a result tuple for an overflow intrinsic \p II with a given
461   /// \p Result and a constant \p Overflow value.
462   Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
463                                    Constant *Overflow) {
464     Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
465     StructType *ST = cast<StructType>(II->getType());
466     Constant *Struct = ConstantStruct::get(ST, V);
467     return InsertValueInst::Create(Struct, Result, 0);
468   }
469
470   /// \brief Combiner aware instruction erasure.
471   ///
472   /// When dealing with an instruction that has side effects or produces a void
473   /// value, we can't rely on DCE to delete the instruction. Instead, visit
474   /// methods should return the value returned by this function.
475   Instruction *eraseInstFromFunction(Instruction &I) {
476     DEBUG(dbgs() << "IC: ERASE " << I << '\n');
477     assert(I.use_empty() && "Cannot erase instruction that is used!");
478     salvageDebugInfo(I);
479
480     // Make sure that we reprocess all operands now that we reduced their
481     // use counts.
482     if (I.getNumOperands() < 8) {
483       for (Use &Operand : I.operands())
484         if (auto *Inst = dyn_cast<Instruction>(Operand))
485           Worklist.Add(Inst);
486     }
487     Worklist.Remove(&I);
488     I.eraseFromParent();
489     MadeIRChange = true;
490     return nullptr; // Don't do anything with FI
491   }
492
493   void computeKnownBits(Value *V, KnownBits &Known,
494                         unsigned Depth, Instruction *CxtI) const {
495     return llvm::computeKnownBits(V, Known, DL, Depth, &AC, CxtI, &DT);
496   }
497
498   bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth = 0,
499                          Instruction *CxtI = nullptr) const {
500     return llvm::MaskedValueIsZero(V, Mask, DL, Depth, &AC, CxtI, &DT);
501   }
502   unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
503                               Instruction *CxtI = nullptr) const {
504     return llvm::ComputeNumSignBits(Op, DL, Depth, &AC, CxtI, &DT);
505   }
506   void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
507                       unsigned Depth = 0, Instruction *CxtI = nullptr) const {
508     return llvm::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth, &AC, CxtI,
509                                 &DT);
510   }
511   OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
512                                                const Instruction *CxtI) {
513     return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
514   }
515   OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
516                                                const Instruction *CxtI) {
517     return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
518   }
519
520   /// Maximum size of array considered when transforming.
521   uint64_t MaxArraySizeForCombine;
522
523 private:
524   /// \brief Performs a few simplifications for operators which are associative
525   /// or commutative.
526   bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
527
528   /// \brief Tries to simplify binary operations which some other binary
529   /// operation distributes over.
530   ///
531   /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
532   /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
533   /// & (B | C) -> (A&B) | (A&C)" if this is a win).  Returns the simplified
534   /// value, or null if it didn't simplify.
535   Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
536
537   /// This tries to simplify binary operations by factorizing out common terms
538   /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
539   Value *tryFactorization(InstCombiner::BuilderTy *, BinaryOperator &,
540                           Instruction::BinaryOps, Value *, Value *, Value *,
541                           Value *);
542
543   /// \brief Attempts to replace V with a simpler value based on the demanded
544   /// bits.
545   Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, KnownBits &Known,
546                                  unsigned Depth, Instruction *CxtI);
547   bool SimplifyDemandedBits(Instruction *I, unsigned Op,
548                             const APInt &DemandedMask, KnownBits &Known,
549                             unsigned Depth = 0);
550   /// Helper routine of SimplifyDemandedUseBits. It computes KnownZero/KnownOne
551   /// bits. It also tries to handle simplifications that can be done based on
552   /// DemandedMask, but without modifying the Instruction.
553   Value *SimplifyMultipleUseDemandedBits(Instruction *I,
554                                          const APInt &DemandedMask,
555                                          KnownBits &Known,
556                                          unsigned Depth, Instruction *CxtI);
557   /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
558   /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
559   Value *simplifyShrShlDemandedBits(
560       Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
561       const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known);
562
563   /// \brief Tries to simplify operands to an integer instruction based on its
564   /// demanded bits.
565   bool SimplifyDemandedInstructionBits(Instruction &Inst);
566
567   Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
568                                     APInt &UndefElts, unsigned Depth = 0);
569
570   Value *SimplifyVectorOp(BinaryOperator &Inst);
571   Value *SimplifyBSwap(BinaryOperator &Inst);
572
573
574   /// Given a binary operator, cast instruction, or select which has a PHI node
575   /// as operand #0, see if we can fold the instruction into the PHI (which is
576   /// only possible if all operands to the PHI are constants).
577   Instruction *foldOpIntoPhi(Instruction &I, PHINode *PN);
578
579   /// Given an instruction with a select as one operand and a constant as the
580   /// other operand, try to fold the binary operator into the select arguments.
581   /// This also works for Cast instructions, which obviously do not have a
582   /// second operand.
583   Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
584
585   /// This is a convenience wrapper function for the above two functions.
586   Instruction *foldOpWithConstantIntoOperand(BinaryOperator &I);
587
588   /// \brief Try to rotate an operation below a PHI node, using PHI nodes for
589   /// its operands.
590   Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
591   Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
592   Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
593   Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
594   Instruction *FoldPHIArgZextsIntoPHI(PHINode &PN);
595
596   /// Helper function for FoldPHIArgXIntoPHI() to get debug location for the
597   /// folded operation.
598   DebugLoc PHIArgMergedDebugLoc(PHINode &PN);
599
600   Instruction *foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
601                            ICmpInst::Predicate Cond, Instruction &I);
602   Instruction *foldAllocaCmp(ICmpInst &ICI, const AllocaInst *Alloca,
603                              const Value *Other);
604   Instruction *foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
605                                             GlobalVariable *GV, CmpInst &ICI,
606                                             ConstantInt *AndCst = nullptr);
607   Instruction *foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
608                                     Constant *RHSC);
609   Instruction *foldICmpAddOpConst(Instruction &ICI, Value *X, ConstantInt *CI,
610                                   ICmpInst::Predicate Pred);
611   Instruction *foldICmpWithCastAndCast(ICmpInst &ICI);
612
613   Instruction *foldICmpUsingKnownBits(ICmpInst &Cmp);
614   Instruction *foldICmpWithConstant(ICmpInst &Cmp);
615   Instruction *foldICmpInstWithConstant(ICmpInst &Cmp);
616   Instruction *foldICmpInstWithConstantNotInt(ICmpInst &Cmp);
617   Instruction *foldICmpBinOp(ICmpInst &Cmp);
618   Instruction *foldICmpEquality(ICmpInst &Cmp);
619
620   Instruction *foldICmpTruncConstant(ICmpInst &Cmp, Instruction *Trunc,
621                                      const APInt *C);
622   Instruction *foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And,
623                                    const APInt *C);
624   Instruction *foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor,
625                                    const APInt *C);
626   Instruction *foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
627                                   const APInt *C);
628   Instruction *foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul,
629                                    const APInt *C);
630   Instruction *foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl,
631                                    const APInt *C);
632   Instruction *foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr,
633                                    const APInt *C);
634   Instruction *foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
635                                     const APInt *C);
636   Instruction *foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div,
637                                    const APInt *C);
638   Instruction *foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub,
639                                    const APInt *C);
640   Instruction *foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add,
641                                    const APInt *C);
642   Instruction *foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And,
643                                      const APInt *C1);
644   Instruction *foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
645                                 const APInt *C1, const APInt *C2);
646   Instruction *foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
647                                      const APInt &C2);
648   Instruction *foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
649                                      const APInt &C2);
650
651   Instruction *foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
652                                                  BinaryOperator *BO,
653                                                  const APInt *C);
654   Instruction *foldICmpIntrinsicWithConstant(ICmpInst &ICI, const APInt *C);
655
656   // Helpers of visitSelectInst().
657   Instruction *foldSelectExtConst(SelectInst &Sel);
658   Instruction *foldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
659   Instruction *foldSelectIntoOp(SelectInst &SI, Value *, Value *);
660   Instruction *foldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
661                             Value *A, Value *B, Instruction &Outer,
662                             SelectPatternFlavor SPF2, Value *C);
663   Instruction *foldSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
664
665   Instruction *OptAndOp(BinaryOperator *Op, ConstantInt *OpRHS,
666                         ConstantInt *AndRHS, BinaryOperator &TheAnd);
667
668   Value *insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
669                          bool isSigned, bool Inside);
670   Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
671   Instruction *MatchBSwap(BinaryOperator &I);
672   bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
673
674   Instruction *SimplifyElementAtomicMemCpy(ElementAtomicMemCpyInst *AMI);
675   Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
676   Instruction *SimplifyMemSet(MemSetInst *MI);
677
678   Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
679
680   /// \brief Returns a value X such that Val = X * Scale, or null if none.
681   ///
682   /// If the multiplication is known not to overflow then NoSignedWrap is set.
683   Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
684 };
685
686 } // end namespace llvm.
687
688 #undef DEBUG_TYPE
689
690 #endif