Home | History | Annotate | Download | only in Analysis
      1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
      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 //
     10 // This file implements routines for folding instructions into simpler forms
     11 // that do not require creating new instructions.  This does constant folding
     12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
     13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
     14 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
     15 // simplified: This is usually true and assuming it simplifies the logic (if
     16 // they have not been simplified then results are correct but maybe suboptimal).
     17 //
     18 //===----------------------------------------------------------------------===//
     19 
     20 #define DEBUG_TYPE "instsimplify"
     21 #include "llvm/Analysis/InstructionSimplify.h"
     22 #include "llvm/ADT/SetVector.h"
     23 #include "llvm/ADT/Statistic.h"
     24 #include "llvm/Analysis/ConstantFolding.h"
     25 #include "llvm/Analysis/Dominators.h"
     26 #include "llvm/Analysis/ValueTracking.h"
     27 #include "llvm/Analysis/MemoryBuiltins.h"
     28 #include "llvm/IR/DataLayout.h"
     29 #include "llvm/IR/GlobalAlias.h"
     30 #include "llvm/IR/Operator.h"
     31 #include "llvm/Support/ConstantRange.h"
     32 #include "llvm/Support/GetElementPtrTypeIterator.h"
     33 #include "llvm/Support/PatternMatch.h"
     34 #include "llvm/Support/ValueHandle.h"
     35 using namespace llvm;
     36 using namespace llvm::PatternMatch;
     37 
     38 enum { RecursionLimit = 3 };
     39 
     40 STATISTIC(NumExpand,  "Number of expansions");
     41 STATISTIC(NumFactor , "Number of factorizations");
     42 STATISTIC(NumReassoc, "Number of reassociations");
     43 
     44 struct Query {
     45   const DataLayout *TD;
     46   const TargetLibraryInfo *TLI;
     47   const DominatorTree *DT;
     48 
     49   Query(const DataLayout *td, const TargetLibraryInfo *tli,
     50         const DominatorTree *dt) : TD(td), TLI(tli), DT(dt) {}
     51 };
     52 
     53 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
     54 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
     55                             unsigned);
     56 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
     57                               unsigned);
     58 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
     59 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
     60 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
     61 
     62 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
     63 /// a vector with every element false, as appropriate for the type.
     64 static Constant *getFalse(Type *Ty) {
     65   assert(Ty->getScalarType()->isIntegerTy(1) &&
     66          "Expected i1 type or a vector of i1!");
     67   return Constant::getNullValue(Ty);
     68 }
     69 
     70 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
     71 /// a vector with every element true, as appropriate for the type.
     72 static Constant *getTrue(Type *Ty) {
     73   assert(Ty->getScalarType()->isIntegerTy(1) &&
     74          "Expected i1 type or a vector of i1!");
     75   return Constant::getAllOnesValue(Ty);
     76 }
     77 
     78 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
     79 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
     80                           Value *RHS) {
     81   CmpInst *Cmp = dyn_cast<CmpInst>(V);
     82   if (!Cmp)
     83     return false;
     84   CmpInst::Predicate CPred = Cmp->getPredicate();
     85   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
     86   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
     87     return true;
     88   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
     89     CRHS == LHS;
     90 }
     91 
     92 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
     93 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
     94   Instruction *I = dyn_cast<Instruction>(V);
     95   if (!I)
     96     // Arguments and constants dominate all instructions.
     97     return true;
     98 
     99   // If we are processing instructions (and/or basic blocks) that have not been
    100   // fully added to a function, the parent nodes may still be null. Simply
    101   // return the conservative answer in these cases.
    102   if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
    103     return false;
    104 
    105   // If we have a DominatorTree then do a precise test.
    106   if (DT) {
    107     if (!DT->isReachableFromEntry(P->getParent()))
    108       return true;
    109     if (!DT->isReachableFromEntry(I->getParent()))
    110       return false;
    111     return DT->dominates(I, P);
    112   }
    113 
    114   // Otherwise, if the instruction is in the entry block, and is not an invoke,
    115   // then it obviously dominates all phi nodes.
    116   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
    117       !isa<InvokeInst>(I))
    118     return true;
    119 
    120   return false;
    121 }
    122 
    123 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
    124 /// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
    125 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
    126 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
    127 /// Returns the simplified value, or null if no simplification was performed.
    128 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
    129                           unsigned OpcToExpand, const Query &Q,
    130                           unsigned MaxRecurse) {
    131   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
    132   // Recursion is always used, so bail out at once if we already hit the limit.
    133   if (!MaxRecurse--)
    134     return 0;
    135 
    136   // Check whether the expression has the form "(A op' B) op C".
    137   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
    138     if (Op0->getOpcode() == OpcodeToExpand) {
    139       // It does!  Try turning it into "(A op C) op' (B op C)".
    140       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
    141       // Do "A op C" and "B op C" both simplify?
    142       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
    143         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
    144           // They do! Return "L op' R" if it simplifies or is already available.
    145           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
    146           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
    147                                      && L == B && R == A)) {
    148             ++NumExpand;
    149             return LHS;
    150           }
    151           // Otherwise return "L op' R" if it simplifies.
    152           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
    153             ++NumExpand;
    154             return V;
    155           }
    156         }
    157     }
    158 
    159   // Check whether the expression has the form "A op (B op' C)".
    160   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
    161     if (Op1->getOpcode() == OpcodeToExpand) {
    162       // It does!  Try turning it into "(A op B) op' (A op C)".
    163       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
    164       // Do "A op B" and "A op C" both simplify?
    165       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
    166         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
    167           // They do! Return "L op' R" if it simplifies or is already available.
    168           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
    169           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
    170                                      && L == C && R == B)) {
    171             ++NumExpand;
    172             return RHS;
    173           }
    174           // Otherwise return "L op' R" if it simplifies.
    175           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
    176             ++NumExpand;
    177             return V;
    178           }
    179         }
    180     }
    181 
    182   return 0;
    183 }
    184 
    185 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
    186 /// using the operation OpCodeToExtract.  For example, when Opcode is Add and
    187 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
    188 /// Returns the simplified value, or null if no simplification was performed.
    189 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
    190                              unsigned OpcToExtract, const Query &Q,
    191                              unsigned MaxRecurse) {
    192   Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
    193   // Recursion is always used, so bail out at once if we already hit the limit.
    194   if (!MaxRecurse--)
    195     return 0;
    196 
    197   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
    198   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
    199 
    200   if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
    201       !Op1 || Op1->getOpcode() != OpcodeToExtract)
    202     return 0;
    203 
    204   // The expression has the form "(A op' B) op (C op' D)".
    205   Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
    206   Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
    207 
    208   // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
    209   // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
    210   // commutative case, "(A op' B) op (C op' A)"?
    211   if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
    212     Value *DD = A == C ? D : C;
    213     // Form "A op' (B op DD)" if it simplifies completely.
    214     // Does "B op DD" simplify?
    215     if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
    216       // It does!  Return "A op' V" if it simplifies or is already available.
    217       // If V equals B then "A op' V" is just the LHS.  If V equals DD then
    218       // "A op' V" is just the RHS.
    219       if (V == B || V == DD) {
    220         ++NumFactor;
    221         return V == B ? LHS : RHS;
    222       }
    223       // Otherwise return "A op' V" if it simplifies.
    224       if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
    225         ++NumFactor;
    226         return W;
    227       }
    228     }
    229   }
    230 
    231   // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
    232   // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
    233   // commutative case, "(A op' B) op (B op' D)"?
    234   if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
    235     Value *CC = B == D ? C : D;
    236     // Form "(A op CC) op' B" if it simplifies completely..
    237     // Does "A op CC" simplify?
    238     if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
    239       // It does!  Return "V op' B" if it simplifies or is already available.
    240       // If V equals A then "V op' B" is just the LHS.  If V equals CC then
    241       // "V op' B" is just the RHS.
    242       if (V == A || V == CC) {
    243         ++NumFactor;
    244         return V == A ? LHS : RHS;
    245       }
    246       // Otherwise return "V op' B" if it simplifies.
    247       if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
    248         ++NumFactor;
    249         return W;
    250       }
    251     }
    252   }
    253 
    254   return 0;
    255 }
    256 
    257 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
    258 /// operations.  Returns the simpler value, or null if none was found.
    259 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
    260                                        const Query &Q, unsigned MaxRecurse) {
    261   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
    262   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
    263 
    264   // Recursion is always used, so bail out at once if we already hit the limit.
    265   if (!MaxRecurse--)
    266     return 0;
    267 
    268   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
    269   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
    270 
    271   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
    272   if (Op0 && Op0->getOpcode() == Opcode) {
    273     Value *A = Op0->getOperand(0);
    274     Value *B = Op0->getOperand(1);
    275     Value *C = RHS;
    276 
    277     // Does "B op C" simplify?
    278     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
    279       // It does!  Return "A op V" if it simplifies or is already available.
    280       // If V equals B then "A op V" is just the LHS.
    281       if (V == B) return LHS;
    282       // Otherwise return "A op V" if it simplifies.
    283       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
    284         ++NumReassoc;
    285         return W;
    286       }
    287     }
    288   }
    289 
    290   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
    291   if (Op1 && Op1->getOpcode() == Opcode) {
    292     Value *A = LHS;
    293     Value *B = Op1->getOperand(0);
    294     Value *C = Op1->getOperand(1);
    295 
    296     // Does "A op B" simplify?
    297     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
    298       // It does!  Return "V op C" if it simplifies or is already available.
    299       // If V equals B then "V op C" is just the RHS.
    300       if (V == B) return RHS;
    301       // Otherwise return "V op C" if it simplifies.
    302       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
    303         ++NumReassoc;
    304         return W;
    305       }
    306     }
    307   }
    308 
    309   // The remaining transforms require commutativity as well as associativity.
    310   if (!Instruction::isCommutative(Opcode))
    311     return 0;
    312 
    313   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
    314   if (Op0 && Op0->getOpcode() == Opcode) {
    315     Value *A = Op0->getOperand(0);
    316     Value *B = Op0->getOperand(1);
    317     Value *C = RHS;
    318 
    319     // Does "C op A" simplify?
    320     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
    321       // It does!  Return "V op B" if it simplifies or is already available.
    322       // If V equals A then "V op B" is just the LHS.
    323       if (V == A) return LHS;
    324       // Otherwise return "V op B" if it simplifies.
    325       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
    326         ++NumReassoc;
    327         return W;
    328       }
    329     }
    330   }
    331 
    332   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
    333   if (Op1 && Op1->getOpcode() == Opcode) {
    334     Value *A = LHS;
    335     Value *B = Op1->getOperand(0);
    336     Value *C = Op1->getOperand(1);
    337 
    338     // Does "C op A" simplify?
    339     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
    340       // It does!  Return "B op V" if it simplifies or is already available.
    341       // If V equals C then "B op V" is just the RHS.
    342       if (V == C) return RHS;
    343       // Otherwise return "B op V" if it simplifies.
    344       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
    345         ++NumReassoc;
    346         return W;
    347       }
    348     }
    349   }
    350 
    351   return 0;
    352 }
    353 
    354 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
    355 /// instruction as an operand, try to simplify the binop by seeing whether
    356 /// evaluating it on both branches of the select results in the same value.
    357 /// Returns the common value if so, otherwise returns null.
    358 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
    359                                     const Query &Q, unsigned MaxRecurse) {
    360   // Recursion is always used, so bail out at once if we already hit the limit.
    361   if (!MaxRecurse--)
    362     return 0;
    363 
    364   SelectInst *SI;
    365   if (isa<SelectInst>(LHS)) {
    366     SI = cast<SelectInst>(LHS);
    367   } else {
    368     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
    369     SI = cast<SelectInst>(RHS);
    370   }
    371 
    372   // Evaluate the BinOp on the true and false branches of the select.
    373   Value *TV;
    374   Value *FV;
    375   if (SI == LHS) {
    376     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
    377     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
    378   } else {
    379     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
    380     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
    381   }
    382 
    383   // If they simplified to the same value, then return the common value.
    384   // If they both failed to simplify then return null.
    385   if (TV == FV)
    386     return TV;
    387 
    388   // If one branch simplified to undef, return the other one.
    389   if (TV && isa<UndefValue>(TV))
    390     return FV;
    391   if (FV && isa<UndefValue>(FV))
    392     return TV;
    393 
    394   // If applying the operation did not change the true and false select values,
    395   // then the result of the binop is the select itself.
    396   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
    397     return SI;
    398 
    399   // If one branch simplified and the other did not, and the simplified
    400   // value is equal to the unsimplified one, return the simplified value.
    401   // For example, select (cond, X, X & Z) & Z -> X & Z.
    402   if ((FV && !TV) || (TV && !FV)) {
    403     // Check that the simplified value has the form "X op Y" where "op" is the
    404     // same as the original operation.
    405     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
    406     if (Simplified && Simplified->getOpcode() == Opcode) {
    407       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
    408       // We already know that "op" is the same as for the simplified value.  See
    409       // if the operands match too.  If so, return the simplified value.
    410       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
    411       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
    412       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
    413       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
    414           Simplified->getOperand(1) == UnsimplifiedRHS)
    415         return Simplified;
    416       if (Simplified->isCommutative() &&
    417           Simplified->getOperand(1) == UnsimplifiedLHS &&
    418           Simplified->getOperand(0) == UnsimplifiedRHS)
    419         return Simplified;
    420     }
    421   }
    422 
    423   return 0;
    424 }
    425 
    426 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
    427 /// try to simplify the comparison by seeing whether both branches of the select
    428 /// result in the same value.  Returns the common value if so, otherwise returns
    429 /// null.
    430 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
    431                                   Value *RHS, const Query &Q,
    432                                   unsigned MaxRecurse) {
    433   // Recursion is always used, so bail out at once if we already hit the limit.
    434   if (!MaxRecurse--)
    435     return 0;
    436 
    437   // Make sure the select is on the LHS.
    438   if (!isa<SelectInst>(LHS)) {
    439     std::swap(LHS, RHS);
    440     Pred = CmpInst::getSwappedPredicate(Pred);
    441   }
    442   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
    443   SelectInst *SI = cast<SelectInst>(LHS);
    444   Value *Cond = SI->getCondition();
    445   Value *TV = SI->getTrueValue();
    446   Value *FV = SI->getFalseValue();
    447 
    448   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
    449   // Does "cmp TV, RHS" simplify?
    450   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
    451   if (TCmp == Cond) {
    452     // It not only simplified, it simplified to the select condition.  Replace
    453     // it with 'true'.
    454     TCmp = getTrue(Cond->getType());
    455   } else if (!TCmp) {
    456     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
    457     // condition then we can replace it with 'true'.  Otherwise give up.
    458     if (!isSameCompare(Cond, Pred, TV, RHS))
    459       return 0;
    460     TCmp = getTrue(Cond->getType());
    461   }
    462 
    463   // Does "cmp FV, RHS" simplify?
    464   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
    465   if (FCmp == Cond) {
    466     // It not only simplified, it simplified to the select condition.  Replace
    467     // it with 'false'.
    468     FCmp = getFalse(Cond->getType());
    469   } else if (!FCmp) {
    470     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
    471     // condition then we can replace it with 'false'.  Otherwise give up.
    472     if (!isSameCompare(Cond, Pred, FV, RHS))
    473       return 0;
    474     FCmp = getFalse(Cond->getType());
    475   }
    476 
    477   // If both sides simplified to the same value, then use it as the result of
    478   // the original comparison.
    479   if (TCmp == FCmp)
    480     return TCmp;
    481 
    482   // The remaining cases only make sense if the select condition has the same
    483   // type as the result of the comparison, so bail out if this is not so.
    484   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
    485     return 0;
    486   // If the false value simplified to false, then the result of the compare
    487   // is equal to "Cond && TCmp".  This also catches the case when the false
    488   // value simplified to false and the true value to true, returning "Cond".
    489   if (match(FCmp, m_Zero()))
    490     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
    491       return V;
    492   // If the true value simplified to true, then the result of the compare
    493   // is equal to "Cond || FCmp".
    494   if (match(TCmp, m_One()))
    495     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
    496       return V;
    497   // Finally, if the false value simplified to true and the true value to
    498   // false, then the result of the compare is equal to "!Cond".
    499   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
    500     if (Value *V =
    501         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
    502                         Q, MaxRecurse))
    503       return V;
    504 
    505   return 0;
    506 }
    507 
    508 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
    509 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
    510 /// it on the incoming phi values yields the same result for every value.  If so
    511 /// returns the common value, otherwise returns null.
    512 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
    513                                  const Query &Q, unsigned MaxRecurse) {
    514   // Recursion is always used, so bail out at once if we already hit the limit.
    515   if (!MaxRecurse--)
    516     return 0;
    517 
    518   PHINode *PI;
    519   if (isa<PHINode>(LHS)) {
    520     PI = cast<PHINode>(LHS);
    521     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
    522     if (!ValueDominatesPHI(RHS, PI, Q.DT))
    523       return 0;
    524   } else {
    525     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
    526     PI = cast<PHINode>(RHS);
    527     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
    528     if (!ValueDominatesPHI(LHS, PI, Q.DT))
    529       return 0;
    530   }
    531 
    532   // Evaluate the BinOp on the incoming phi values.
    533   Value *CommonValue = 0;
    534   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
    535     Value *Incoming = PI->getIncomingValue(i);
    536     // If the incoming value is the phi node itself, it can safely be skipped.
    537     if (Incoming == PI) continue;
    538     Value *V = PI == LHS ?
    539       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
    540       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
    541     // If the operation failed to simplify, or simplified to a different value
    542     // to previously, then give up.
    543     if (!V || (CommonValue && V != CommonValue))
    544       return 0;
    545     CommonValue = V;
    546   }
    547 
    548   return CommonValue;
    549 }
    550 
    551 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
    552 /// try to simplify the comparison by seeing whether comparing with all of the
    553 /// incoming phi values yields the same result every time.  If so returns the
    554 /// common result, otherwise returns null.
    555 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
    556                                const Query &Q, unsigned MaxRecurse) {
    557   // Recursion is always used, so bail out at once if we already hit the limit.
    558   if (!MaxRecurse--)
    559     return 0;
    560 
    561   // Make sure the phi is on the LHS.
    562   if (!isa<PHINode>(LHS)) {
    563     std::swap(LHS, RHS);
    564     Pred = CmpInst::getSwappedPredicate(Pred);
    565   }
    566   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
    567   PHINode *PI = cast<PHINode>(LHS);
    568 
    569   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
    570   if (!ValueDominatesPHI(RHS, PI, Q.DT))
    571     return 0;
    572 
    573   // Evaluate the BinOp on the incoming phi values.
    574   Value *CommonValue = 0;
    575   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
    576     Value *Incoming = PI->getIncomingValue(i);
    577     // If the incoming value is the phi node itself, it can safely be skipped.
    578     if (Incoming == PI) continue;
    579     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
    580     // If the operation failed to simplify, or simplified to a different value
    581     // to previously, then give up.
    582     if (!V || (CommonValue && V != CommonValue))
    583       return 0;
    584     CommonValue = V;
    585   }
    586 
    587   return CommonValue;
    588 }
    589 
    590 /// SimplifyAddInst - Given operands for an Add, see if we can
    591 /// fold the result.  If not, this returns null.
    592 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
    593                               const Query &Q, unsigned MaxRecurse) {
    594   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
    595     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
    596       Constant *Ops[] = { CLHS, CRHS };
    597       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
    598                                       Q.TD, Q.TLI);
    599     }
    600 
    601     // Canonicalize the constant to the RHS.
    602     std::swap(Op0, Op1);
    603   }
    604 
    605   // X + undef -> undef
    606   if (match(Op1, m_Undef()))
    607     return Op1;
    608 
    609   // X + 0 -> X
    610   if (match(Op1, m_Zero()))
    611     return Op0;
    612 
    613   // X + (Y - X) -> Y
    614   // (Y - X) + X -> Y
    615   // Eg: X + -X -> 0
    616   Value *Y = 0;
    617   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
    618       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
    619     return Y;
    620 
    621   // X + ~X -> -1   since   ~X = -X-1
    622   if (match(Op0, m_Not(m_Specific(Op1))) ||
    623       match(Op1, m_Not(m_Specific(Op0))))
    624     return Constant::getAllOnesValue(Op0->getType());
    625 
    626   /// i1 add -> xor.
    627   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
    628     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
    629       return V;
    630 
    631   // Try some generic simplifications for associative operations.
    632   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
    633                                           MaxRecurse))
    634     return V;
    635 
    636   // Mul distributes over Add.  Try some generic simplifications based on this.
    637   if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
    638                                 Q, MaxRecurse))
    639     return V;
    640 
    641   // Threading Add over selects and phi nodes is pointless, so don't bother.
    642   // Threading over the select in "A + select(cond, B, C)" means evaluating
    643   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
    644   // only if B and C are equal.  If B and C are equal then (since we assume
    645   // that operands have already been simplified) "select(cond, B, C)" should
    646   // have been simplified to the common value of B and C already.  Analysing
    647   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
    648   // for threading over phi nodes.
    649 
    650   return 0;
    651 }
    652 
    653 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
    654                              const DataLayout *TD, const TargetLibraryInfo *TLI,
    655                              const DominatorTree *DT) {
    656   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
    657                            RecursionLimit);
    658 }
    659 
    660 /// \brief Compute the base pointer and cumulative constant offsets for V.
    661 ///
    662 /// This strips all constant offsets off of V, leaving it the base pointer, and
    663 /// accumulates the total constant offset applied in the returned constant. It
    664 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
    665 /// no constant offsets applied.
    666 ///
    667 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
    668 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
    669 /// folding.
    670 static Constant *stripAndComputeConstantOffsets(const DataLayout *TD,
    671                                                 Value *&V) {
    672   assert(V->getType()->getScalarType()->isPointerTy());
    673 
    674   // Without DataLayout, just be conservative for now. Theoretically, more could
    675   // be done in this case.
    676   if (!TD)
    677     return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
    678 
    679   Type *IntPtrTy = TD->getIntPtrType(V->getType())->getScalarType();
    680   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
    681 
    682   // Even though we don't look through PHI nodes, we could be called on an
    683   // instruction in an unreachable block, which may be on a cycle.
    684   SmallPtrSet<Value *, 4> Visited;
    685   Visited.insert(V);
    686   do {
    687     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
    688       if (!GEP->isInBounds() || !GEP->accumulateConstantOffset(*TD, Offset))
    689         break;
    690       V = GEP->getPointerOperand();
    691     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
    692       V = cast<Operator>(V)->getOperand(0);
    693     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
    694       if (GA->mayBeOverridden())
    695         break;
    696       V = GA->getAliasee();
    697     } else {
    698       break;
    699     }
    700     assert(V->getType()->getScalarType()->isPointerTy() &&
    701            "Unexpected operand type!");
    702   } while (Visited.insert(V));
    703 
    704   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
    705   if (V->getType()->isVectorTy())
    706     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
    707                                     OffsetIntPtr);
    708   return OffsetIntPtr;
    709 }
    710 
    711 /// \brief Compute the constant difference between two pointer values.
    712 /// If the difference is not a constant, returns zero.
    713 static Constant *computePointerDifference(const DataLayout *TD,
    714                                           Value *LHS, Value *RHS) {
    715   Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
    716   Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
    717 
    718   // If LHS and RHS are not related via constant offsets to the same base
    719   // value, there is nothing we can do here.
    720   if (LHS != RHS)
    721     return 0;
    722 
    723   // Otherwise, the difference of LHS - RHS can be computed as:
    724   //    LHS - RHS
    725   //  = (LHSOffset + Base) - (RHSOffset + Base)
    726   //  = LHSOffset - RHSOffset
    727   return ConstantExpr::getSub(LHSOffset, RHSOffset);
    728 }
    729 
    730 /// SimplifySubInst - Given operands for a Sub, see if we can
    731 /// fold the result.  If not, this returns null.
    732 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
    733                               const Query &Q, unsigned MaxRecurse) {
    734   if (Constant *CLHS = dyn_cast<Constant>(Op0))
    735     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
    736       Constant *Ops[] = { CLHS, CRHS };
    737       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
    738                                       Ops, Q.TD, Q.TLI);
    739     }
    740 
    741   // X - undef -> undef
    742   // undef - X -> undef
    743   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
    744     return UndefValue::get(Op0->getType());
    745 
    746   // X - 0 -> X
    747   if (match(Op1, m_Zero()))
    748     return Op0;
    749 
    750   // X - X -> 0
    751   if (Op0 == Op1)
    752     return Constant::getNullValue(Op0->getType());
    753 
    754   // (X*2) - X -> X
    755   // (X<<1) - X -> X
    756   Value *X = 0;
    757   if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
    758       match(Op0, m_Shl(m_Specific(Op1), m_One())))
    759     return Op1;
    760 
    761   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
    762   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
    763   Value *Y = 0, *Z = Op1;
    764   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
    765     // See if "V === Y - Z" simplifies.
    766     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
    767       // It does!  Now see if "X + V" simplifies.
    768       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
    769         // It does, we successfully reassociated!
    770         ++NumReassoc;
    771         return W;
    772       }
    773     // See if "V === X - Z" simplifies.
    774     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
    775       // It does!  Now see if "Y + V" simplifies.
    776       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
    777         // It does, we successfully reassociated!
    778         ++NumReassoc;
    779         return W;
    780       }
    781   }
    782 
    783   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
    784   // For example, X - (X + 1) -> -1
    785   X = Op0;
    786   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
    787     // See if "V === X - Y" simplifies.
    788     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
    789       // It does!  Now see if "V - Z" simplifies.
    790       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
    791         // It does, we successfully reassociated!
    792         ++NumReassoc;
    793         return W;
    794       }
    795     // See if "V === X - Z" simplifies.
    796     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
    797       // It does!  Now see if "V - Y" simplifies.
    798       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
    799         // It does, we successfully reassociated!
    800         ++NumReassoc;
    801         return W;
    802       }
    803   }
    804 
    805   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
    806   // For example, X - (X - Y) -> Y.
    807   Z = Op0;
    808   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
    809     // See if "V === Z - X" simplifies.
    810     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
    811       // It does!  Now see if "V + Y" simplifies.
    812       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
    813         // It does, we successfully reassociated!
    814         ++NumReassoc;
    815         return W;
    816       }
    817 
    818   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
    819   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
    820       match(Op1, m_Trunc(m_Value(Y))))
    821     if (X->getType() == Y->getType())
    822       // See if "V === X - Y" simplifies.
    823       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
    824         // It does!  Now see if "trunc V" simplifies.
    825         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
    826           // It does, return the simplified "trunc V".
    827           return W;
    828 
    829   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
    830   if (match(Op0, m_PtrToInt(m_Value(X))) &&
    831       match(Op1, m_PtrToInt(m_Value(Y))))
    832     if (Constant *Result = computePointerDifference(Q.TD, X, Y))
    833       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
    834 
    835   // Mul distributes over Sub.  Try some generic simplifications based on this.
    836   if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
    837                                 Q, MaxRecurse))
    838     return V;
    839 
    840   // i1 sub -> xor.
    841   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
    842     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
    843       return V;
    844 
    845   // Threading Sub over selects and phi nodes is pointless, so don't bother.
    846   // Threading over the select in "A - select(cond, B, C)" means evaluating
    847   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
    848   // only if B and C are equal.  If B and C are equal then (since we assume
    849   // that operands have already been simplified) "select(cond, B, C)" should
    850   // have been simplified to the common value of B and C already.  Analysing
    851   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
    852   // for threading over phi nodes.
    853 
    854   return 0;
    855 }
    856 
    857 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
    858                              const DataLayout *TD, const TargetLibraryInfo *TLI,
    859                              const DominatorTree *DT) {
    860   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
    861                            RecursionLimit);
    862 }
    863 
    864 /// Given operands for an FAdd, see if we can fold the result.  If not, this
    865 /// returns null.
    866 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    867                               const Query &Q, unsigned MaxRecurse) {
    868   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
    869     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
    870       Constant *Ops[] = { CLHS, CRHS };
    871       return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
    872                                       Ops, Q.TD, Q.TLI);
    873     }
    874 
    875     // Canonicalize the constant to the RHS.
    876     std::swap(Op0, Op1);
    877   }
    878 
    879   // fadd X, -0 ==> X
    880   if (match(Op1, m_NegZero()))
    881     return Op0;
    882 
    883   // fadd X, 0 ==> X, when we know X is not -0
    884   if (match(Op1, m_Zero()) &&
    885       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
    886     return Op0;
    887 
    888   // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
    889   //   where nnan and ninf have to occur at least once somewhere in this
    890   //   expression
    891   Value *SubOp = 0;
    892   if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
    893     SubOp = Op1;
    894   else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
    895     SubOp = Op0;
    896   if (SubOp) {
    897     Instruction *FSub = cast<Instruction>(SubOp);
    898     if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
    899         (FMF.noInfs() || FSub->hasNoInfs()))
    900       return Constant::getNullValue(Op0->getType());
    901   }
    902 
    903   return 0;
    904 }
    905 
    906 /// Given operands for an FSub, see if we can fold the result.  If not, this
    907 /// returns null.
    908 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
    909                               const Query &Q, unsigned MaxRecurse) {
    910   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
    911     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
    912       Constant *Ops[] = { CLHS, CRHS };
    913       return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
    914                                       Ops, Q.TD, Q.TLI);
    915     }
    916   }
    917 
    918   // fsub X, 0 ==> X
    919   if (match(Op1, m_Zero()))
    920     return Op0;
    921 
    922   // fsub X, -0 ==> X, when we know X is not -0
    923   if (match(Op1, m_NegZero()) &&
    924       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
    925     return Op0;
    926 
    927   // fsub 0, (fsub -0.0, X) ==> X
    928   Value *X;
    929   if (match(Op0, m_AnyZero())) {
    930     if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
    931       return X;
    932     if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
    933       return X;
    934   }
    935 
    936   // fsub nnan ninf x, x ==> 0.0
    937   if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
    938     return Constant::getNullValue(Op0->getType());
    939 
    940   return 0;
    941 }
    942 
    943 /// Given the operands for an FMul, see if we can fold the result
    944 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
    945                                FastMathFlags FMF,
    946                                const Query &Q,
    947                                unsigned MaxRecurse) {
    948  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
    949     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
    950       Constant *Ops[] = { CLHS, CRHS };
    951       return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
    952                                       Ops, Q.TD, Q.TLI);
    953     }
    954 
    955     // Canonicalize the constant to the RHS.
    956     std::swap(Op0, Op1);
    957  }
    958 
    959  // fmul X, 1.0 ==> X
    960  if (match(Op1, m_FPOne()))
    961    return Op0;
    962 
    963  // fmul nnan nsz X, 0 ==> 0
    964  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
    965    return Op1;
    966 
    967  return 0;
    968 }
    969 
    970 /// SimplifyMulInst - Given operands for a Mul, see if we can
    971 /// fold the result.  If not, this returns null.
    972 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
    973                               unsigned MaxRecurse) {
    974   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
    975     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
    976       Constant *Ops[] = { CLHS, CRHS };
    977       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
    978                                       Ops, Q.TD, Q.TLI);
    979     }
    980 
    981     // Canonicalize the constant to the RHS.
    982     std::swap(Op0, Op1);
    983   }
    984 
    985   // X * undef -> 0
    986   if (match(Op1, m_Undef()))
    987     return Constant::getNullValue(Op0->getType());
    988 
    989   // X * 0 -> 0
    990   if (match(Op1, m_Zero()))
    991     return Op1;
    992 
    993   // X * 1 -> X
    994   if (match(Op1, m_One()))
    995     return Op0;
    996 
    997   // (X / Y) * Y -> X if the division is exact.
    998   Value *X = 0;
    999   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
   1000       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
   1001     return X;
   1002 
   1003   // i1 mul -> and.
   1004   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
   1005     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
   1006       return V;
   1007 
   1008   // Try some generic simplifications for associative operations.
   1009   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
   1010                                           MaxRecurse))
   1011     return V;
   1012 
   1013   // Mul distributes over Add.  Try some generic simplifications based on this.
   1014   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
   1015                              Q, MaxRecurse))
   1016     return V;
   1017 
   1018   // If the operation is with the result of a select instruction, check whether
   1019   // operating on either branch of the select always yields the same value.
   1020   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
   1021     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
   1022                                          MaxRecurse))
   1023       return V;
   1024 
   1025   // If the operation is with the result of a phi instruction, check whether
   1026   // operating on all incoming values of the phi always yields the same value.
   1027   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
   1028     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
   1029                                       MaxRecurse))
   1030       return V;
   1031 
   1032   return 0;
   1033 }
   1034 
   1035 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
   1036                              const DataLayout *TD, const TargetLibraryInfo *TLI,
   1037                              const DominatorTree *DT) {
   1038   return ::SimplifyFAddInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
   1039 }
   1040 
   1041 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
   1042                              const DataLayout *TD, const TargetLibraryInfo *TLI,
   1043                              const DominatorTree *DT) {
   1044   return ::SimplifyFSubInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
   1045 }
   1046 
   1047 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
   1048                               FastMathFlags FMF,
   1049                               const DataLayout *TD,
   1050                               const TargetLibraryInfo *TLI,
   1051                               const DominatorTree *DT) {
   1052   return ::SimplifyFMulInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
   1053 }
   1054 
   1055 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1056                              const TargetLibraryInfo *TLI,
   1057                              const DominatorTree *DT) {
   1058   return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1059 }
   1060 
   1061 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
   1062 /// fold the result.  If not, this returns null.
   1063 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
   1064                           const Query &Q, unsigned MaxRecurse) {
   1065   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
   1066     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
   1067       Constant *Ops[] = { C0, C1 };
   1068       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
   1069     }
   1070   }
   1071 
   1072   bool isSigned = Opcode == Instruction::SDiv;
   1073 
   1074   // X / undef -> undef
   1075   if (match(Op1, m_Undef()))
   1076     return Op1;
   1077 
   1078   // undef / X -> 0
   1079   if (match(Op0, m_Undef()))
   1080     return Constant::getNullValue(Op0->getType());
   1081 
   1082   // 0 / X -> 0, we don't need to preserve faults!
   1083   if (match(Op0, m_Zero()))
   1084     return Op0;
   1085 
   1086   // X / 1 -> X
   1087   if (match(Op1, m_One()))
   1088     return Op0;
   1089 
   1090   if (Op0->getType()->isIntegerTy(1))
   1091     // It can't be division by zero, hence it must be division by one.
   1092     return Op0;
   1093 
   1094   // X / X -> 1
   1095   if (Op0 == Op1)
   1096     return ConstantInt::get(Op0->getType(), 1);
   1097 
   1098   // (X * Y) / Y -> X if the multiplication does not overflow.
   1099   Value *X = 0, *Y = 0;
   1100   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
   1101     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
   1102     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
   1103     // If the Mul knows it does not overflow, then we are good to go.
   1104     if ((isSigned && Mul->hasNoSignedWrap()) ||
   1105         (!isSigned && Mul->hasNoUnsignedWrap()))
   1106       return X;
   1107     // If X has the form X = A / Y then X * Y cannot overflow.
   1108     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
   1109       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
   1110         return X;
   1111   }
   1112 
   1113   // (X rem Y) / Y -> 0
   1114   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
   1115       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
   1116     return Constant::getNullValue(Op0->getType());
   1117 
   1118   // If the operation is with the result of a select instruction, check whether
   1119   // operating on either branch of the select always yields the same value.
   1120   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
   1121     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
   1122       return V;
   1123 
   1124   // If the operation is with the result of a phi instruction, check whether
   1125   // operating on all incoming values of the phi always yields the same value.
   1126   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
   1127     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
   1128       return V;
   1129 
   1130   return 0;
   1131 }
   1132 
   1133 /// SimplifySDivInst - Given operands for an SDiv, see if we can
   1134 /// fold the result.  If not, this returns null.
   1135 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
   1136                                unsigned MaxRecurse) {
   1137   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
   1138     return V;
   1139 
   1140   return 0;
   1141 }
   1142 
   1143 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1144                               const TargetLibraryInfo *TLI,
   1145                               const DominatorTree *DT) {
   1146   return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1147 }
   1148 
   1149 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
   1150 /// fold the result.  If not, this returns null.
   1151 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
   1152                                unsigned MaxRecurse) {
   1153   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
   1154     return V;
   1155 
   1156   return 0;
   1157 }
   1158 
   1159 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1160                               const TargetLibraryInfo *TLI,
   1161                               const DominatorTree *DT) {
   1162   return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1163 }
   1164 
   1165 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
   1166                                unsigned) {
   1167   // undef / X -> undef    (the undef could be a snan).
   1168   if (match(Op0, m_Undef()))
   1169     return Op0;
   1170 
   1171   // X / undef -> undef
   1172   if (match(Op1, m_Undef()))
   1173     return Op1;
   1174 
   1175   return 0;
   1176 }
   1177 
   1178 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1179                               const TargetLibraryInfo *TLI,
   1180                               const DominatorTree *DT) {
   1181   return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1182 }
   1183 
   1184 /// SimplifyRem - Given operands for an SRem or URem, see if we can
   1185 /// fold the result.  If not, this returns null.
   1186 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
   1187                           const Query &Q, unsigned MaxRecurse) {
   1188   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
   1189     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
   1190       Constant *Ops[] = { C0, C1 };
   1191       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
   1192     }
   1193   }
   1194 
   1195   // X % undef -> undef
   1196   if (match(Op1, m_Undef()))
   1197     return Op1;
   1198 
   1199   // undef % X -> 0
   1200   if (match(Op0, m_Undef()))
   1201     return Constant::getNullValue(Op0->getType());
   1202 
   1203   // 0 % X -> 0, we don't need to preserve faults!
   1204   if (match(Op0, m_Zero()))
   1205     return Op0;
   1206 
   1207   // X % 0 -> undef, we don't need to preserve faults!
   1208   if (match(Op1, m_Zero()))
   1209     return UndefValue::get(Op0->getType());
   1210 
   1211   // X % 1 -> 0
   1212   if (match(Op1, m_One()))
   1213     return Constant::getNullValue(Op0->getType());
   1214 
   1215   if (Op0->getType()->isIntegerTy(1))
   1216     // It can't be remainder by zero, hence it must be remainder by one.
   1217     return Constant::getNullValue(Op0->getType());
   1218 
   1219   // X % X -> 0
   1220   if (Op0 == Op1)
   1221     return Constant::getNullValue(Op0->getType());
   1222 
   1223   // If the operation is with the result of a select instruction, check whether
   1224   // operating on either branch of the select always yields the same value.
   1225   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
   1226     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
   1227       return V;
   1228 
   1229   // If the operation is with the result of a phi instruction, check whether
   1230   // operating on all incoming values of the phi always yields the same value.
   1231   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
   1232     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
   1233       return V;
   1234 
   1235   return 0;
   1236 }
   1237 
   1238 /// SimplifySRemInst - Given operands for an SRem, see if we can
   1239 /// fold the result.  If not, this returns null.
   1240 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
   1241                                unsigned MaxRecurse) {
   1242   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
   1243     return V;
   1244 
   1245   return 0;
   1246 }
   1247 
   1248 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1249                               const TargetLibraryInfo *TLI,
   1250                               const DominatorTree *DT) {
   1251   return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1252 }
   1253 
   1254 /// SimplifyURemInst - Given operands for a URem, see if we can
   1255 /// fold the result.  If not, this returns null.
   1256 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
   1257                                unsigned MaxRecurse) {
   1258   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
   1259     return V;
   1260 
   1261   return 0;
   1262 }
   1263 
   1264 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1265                               const TargetLibraryInfo *TLI,
   1266                               const DominatorTree *DT) {
   1267   return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1268 }
   1269 
   1270 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
   1271                                unsigned) {
   1272   // undef % X -> undef    (the undef could be a snan).
   1273   if (match(Op0, m_Undef()))
   1274     return Op0;
   1275 
   1276   // X % undef -> undef
   1277   if (match(Op1, m_Undef()))
   1278     return Op1;
   1279 
   1280   return 0;
   1281 }
   1282 
   1283 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1284                               const TargetLibraryInfo *TLI,
   1285                               const DominatorTree *DT) {
   1286   return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1287 }
   1288 
   1289 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
   1290 /// fold the result.  If not, this returns null.
   1291 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
   1292                             const Query &Q, unsigned MaxRecurse) {
   1293   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
   1294     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
   1295       Constant *Ops[] = { C0, C1 };
   1296       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
   1297     }
   1298   }
   1299 
   1300   // 0 shift by X -> 0
   1301   if (match(Op0, m_Zero()))
   1302     return Op0;
   1303 
   1304   // X shift by 0 -> X
   1305   if (match(Op1, m_Zero()))
   1306     return Op0;
   1307 
   1308   // X shift by undef -> undef because it may shift by the bitwidth.
   1309   if (match(Op1, m_Undef()))
   1310     return Op1;
   1311 
   1312   // Shifting by the bitwidth or more is undefined.
   1313   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
   1314     if (CI->getValue().getLimitedValue() >=
   1315         Op0->getType()->getScalarSizeInBits())
   1316       return UndefValue::get(Op0->getType());
   1317 
   1318   // If the operation is with the result of a select instruction, check whether
   1319   // operating on either branch of the select always yields the same value.
   1320   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
   1321     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
   1322       return V;
   1323 
   1324   // If the operation is with the result of a phi instruction, check whether
   1325   // operating on all incoming values of the phi always yields the same value.
   1326   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
   1327     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
   1328       return V;
   1329 
   1330   return 0;
   1331 }
   1332 
   1333 /// SimplifyShlInst - Given operands for an Shl, see if we can
   1334 /// fold the result.  If not, this returns null.
   1335 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
   1336                               const Query &Q, unsigned MaxRecurse) {
   1337   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
   1338     return V;
   1339 
   1340   // undef << X -> 0
   1341   if (match(Op0, m_Undef()))
   1342     return Constant::getNullValue(Op0->getType());
   1343 
   1344   // (X >> A) << A -> X
   1345   Value *X;
   1346   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
   1347     return X;
   1348   return 0;
   1349 }
   1350 
   1351 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
   1352                              const DataLayout *TD, const TargetLibraryInfo *TLI,
   1353                              const DominatorTree *DT) {
   1354   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
   1355                            RecursionLimit);
   1356 }
   1357 
   1358 /// SimplifyLShrInst - Given operands for an LShr, see if we can
   1359 /// fold the result.  If not, this returns null.
   1360 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
   1361                                const Query &Q, unsigned MaxRecurse) {
   1362   if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
   1363     return V;
   1364 
   1365   // X >> X -> 0
   1366   if (Op0 == Op1)
   1367     return Constant::getNullValue(Op0->getType());
   1368 
   1369   // undef >>l X -> 0
   1370   if (match(Op0, m_Undef()))
   1371     return Constant::getNullValue(Op0->getType());
   1372 
   1373   // (X << A) >> A -> X
   1374   Value *X;
   1375   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
   1376       cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
   1377     return X;
   1378 
   1379   return 0;
   1380 }
   1381 
   1382 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
   1383                               const DataLayout *TD,
   1384                               const TargetLibraryInfo *TLI,
   1385                               const DominatorTree *DT) {
   1386   return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
   1387                             RecursionLimit);
   1388 }
   1389 
   1390 /// SimplifyAShrInst - Given operands for an AShr, see if we can
   1391 /// fold the result.  If not, this returns null.
   1392 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
   1393                                const Query &Q, unsigned MaxRecurse) {
   1394   if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
   1395     return V;
   1396 
   1397   // X >> X -> 0
   1398   if (Op0 == Op1)
   1399     return Constant::getNullValue(Op0->getType());
   1400 
   1401   // all ones >>a X -> all ones
   1402   if (match(Op0, m_AllOnes()))
   1403     return Op0;
   1404 
   1405   // undef >>a X -> all ones
   1406   if (match(Op0, m_Undef()))
   1407     return Constant::getAllOnesValue(Op0->getType());
   1408 
   1409   // (X << A) >> A -> X
   1410   Value *X;
   1411   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
   1412       cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
   1413     return X;
   1414 
   1415   return 0;
   1416 }
   1417 
   1418 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
   1419                               const DataLayout *TD,
   1420                               const TargetLibraryInfo *TLI,
   1421                               const DominatorTree *DT) {
   1422   return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
   1423                             RecursionLimit);
   1424 }
   1425 
   1426 /// SimplifyAndInst - Given operands for an And, see if we can
   1427 /// fold the result.  If not, this returns null.
   1428 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
   1429                               unsigned MaxRecurse) {
   1430   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
   1431     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
   1432       Constant *Ops[] = { CLHS, CRHS };
   1433       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
   1434                                       Ops, Q.TD, Q.TLI);
   1435     }
   1436 
   1437     // Canonicalize the constant to the RHS.
   1438     std::swap(Op0, Op1);
   1439   }
   1440 
   1441   // X & undef -> 0
   1442   if (match(Op1, m_Undef()))
   1443     return Constant::getNullValue(Op0->getType());
   1444 
   1445   // X & X = X
   1446   if (Op0 == Op1)
   1447     return Op0;
   1448 
   1449   // X & 0 = 0
   1450   if (match(Op1, m_Zero()))
   1451     return Op1;
   1452 
   1453   // X & -1 = X
   1454   if (match(Op1, m_AllOnes()))
   1455     return Op0;
   1456 
   1457   // A & ~A  =  ~A & A  =  0
   1458   if (match(Op0, m_Not(m_Specific(Op1))) ||
   1459       match(Op1, m_Not(m_Specific(Op0))))
   1460     return Constant::getNullValue(Op0->getType());
   1461 
   1462   // (A | ?) & A = A
   1463   Value *A = 0, *B = 0;
   1464   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
   1465       (A == Op1 || B == Op1))
   1466     return Op1;
   1467 
   1468   // A & (A | ?) = A
   1469   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
   1470       (A == Op0 || B == Op0))
   1471     return Op0;
   1472 
   1473   // A & (-A) = A if A is a power of two or zero.
   1474   if (match(Op0, m_Neg(m_Specific(Op1))) ||
   1475       match(Op1, m_Neg(m_Specific(Op0)))) {
   1476     if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
   1477       return Op0;
   1478     if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
   1479       return Op1;
   1480   }
   1481 
   1482   // Try some generic simplifications for associative operations.
   1483   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
   1484                                           MaxRecurse))
   1485     return V;
   1486 
   1487   // And distributes over Or.  Try some generic simplifications based on this.
   1488   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
   1489                              Q, MaxRecurse))
   1490     return V;
   1491 
   1492   // And distributes over Xor.  Try some generic simplifications based on this.
   1493   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
   1494                              Q, MaxRecurse))
   1495     return V;
   1496 
   1497   // Or distributes over And.  Try some generic simplifications based on this.
   1498   if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
   1499                                 Q, MaxRecurse))
   1500     return V;
   1501 
   1502   // If the operation is with the result of a select instruction, check whether
   1503   // operating on either branch of the select always yields the same value.
   1504   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
   1505     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
   1506                                          MaxRecurse))
   1507       return V;
   1508 
   1509   // If the operation is with the result of a phi instruction, check whether
   1510   // operating on all incoming values of the phi always yields the same value.
   1511   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
   1512     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
   1513                                       MaxRecurse))
   1514       return V;
   1515 
   1516   return 0;
   1517 }
   1518 
   1519 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1520                              const TargetLibraryInfo *TLI,
   1521                              const DominatorTree *DT) {
   1522   return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1523 }
   1524 
   1525 /// SimplifyOrInst - Given operands for an Or, see if we can
   1526 /// fold the result.  If not, this returns null.
   1527 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
   1528                              unsigned MaxRecurse) {
   1529   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
   1530     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
   1531       Constant *Ops[] = { CLHS, CRHS };
   1532       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
   1533                                       Ops, Q.TD, Q.TLI);
   1534     }
   1535 
   1536     // Canonicalize the constant to the RHS.
   1537     std::swap(Op0, Op1);
   1538   }
   1539 
   1540   // X | undef -> -1
   1541   if (match(Op1, m_Undef()))
   1542     return Constant::getAllOnesValue(Op0->getType());
   1543 
   1544   // X | X = X
   1545   if (Op0 == Op1)
   1546     return Op0;
   1547 
   1548   // X | 0 = X
   1549   if (match(Op1, m_Zero()))
   1550     return Op0;
   1551 
   1552   // X | -1 = -1
   1553   if (match(Op1, m_AllOnes()))
   1554     return Op1;
   1555 
   1556   // A | ~A  =  ~A | A  =  -1
   1557   if (match(Op0, m_Not(m_Specific(Op1))) ||
   1558       match(Op1, m_Not(m_Specific(Op0))))
   1559     return Constant::getAllOnesValue(Op0->getType());
   1560 
   1561   // (A & ?) | A = A
   1562   Value *A = 0, *B = 0;
   1563   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
   1564       (A == Op1 || B == Op1))
   1565     return Op1;
   1566 
   1567   // A | (A & ?) = A
   1568   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
   1569       (A == Op0 || B == Op0))
   1570     return Op0;
   1571 
   1572   // ~(A & ?) | A = -1
   1573   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
   1574       (A == Op1 || B == Op1))
   1575     return Constant::getAllOnesValue(Op1->getType());
   1576 
   1577   // A | ~(A & ?) = -1
   1578   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
   1579       (A == Op0 || B == Op0))
   1580     return Constant::getAllOnesValue(Op0->getType());
   1581 
   1582   // Try some generic simplifications for associative operations.
   1583   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
   1584                                           MaxRecurse))
   1585     return V;
   1586 
   1587   // Or distributes over And.  Try some generic simplifications based on this.
   1588   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
   1589                              MaxRecurse))
   1590     return V;
   1591 
   1592   // And distributes over Or.  Try some generic simplifications based on this.
   1593   if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
   1594                                 Q, MaxRecurse))
   1595     return V;
   1596 
   1597   // If the operation is with the result of a select instruction, check whether
   1598   // operating on either branch of the select always yields the same value.
   1599   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
   1600     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
   1601                                          MaxRecurse))
   1602       return V;
   1603 
   1604   // If the operation is with the result of a phi instruction, check whether
   1605   // operating on all incoming values of the phi always yields the same value.
   1606   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
   1607     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
   1608       return V;
   1609 
   1610   return 0;
   1611 }
   1612 
   1613 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1614                             const TargetLibraryInfo *TLI,
   1615                             const DominatorTree *DT) {
   1616   return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1617 }
   1618 
   1619 /// SimplifyXorInst - Given operands for a Xor, see if we can
   1620 /// fold the result.  If not, this returns null.
   1621 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
   1622                               unsigned MaxRecurse) {
   1623   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
   1624     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
   1625       Constant *Ops[] = { CLHS, CRHS };
   1626       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
   1627                                       Ops, Q.TD, Q.TLI);
   1628     }
   1629 
   1630     // Canonicalize the constant to the RHS.
   1631     std::swap(Op0, Op1);
   1632   }
   1633 
   1634   // A ^ undef -> undef
   1635   if (match(Op1, m_Undef()))
   1636     return Op1;
   1637 
   1638   // A ^ 0 = A
   1639   if (match(Op1, m_Zero()))
   1640     return Op0;
   1641 
   1642   // A ^ A = 0
   1643   if (Op0 == Op1)
   1644     return Constant::getNullValue(Op0->getType());
   1645 
   1646   // A ^ ~A  =  ~A ^ A  =  -1
   1647   if (match(Op0, m_Not(m_Specific(Op1))) ||
   1648       match(Op1, m_Not(m_Specific(Op0))))
   1649     return Constant::getAllOnesValue(Op0->getType());
   1650 
   1651   // Try some generic simplifications for associative operations.
   1652   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
   1653                                           MaxRecurse))
   1654     return V;
   1655 
   1656   // And distributes over Xor.  Try some generic simplifications based on this.
   1657   if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
   1658                                 Q, MaxRecurse))
   1659     return V;
   1660 
   1661   // Threading Xor over selects and phi nodes is pointless, so don't bother.
   1662   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
   1663   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
   1664   // only if B and C are equal.  If B and C are equal then (since we assume
   1665   // that operands have already been simplified) "select(cond, B, C)" should
   1666   // have been simplified to the common value of B and C already.  Analysing
   1667   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
   1668   // for threading over phi nodes.
   1669 
   1670   return 0;
   1671 }
   1672 
   1673 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *TD,
   1674                              const TargetLibraryInfo *TLI,
   1675                              const DominatorTree *DT) {
   1676   return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
   1677 }
   1678 
   1679 static Type *GetCompareTy(Value *Op) {
   1680   return CmpInst::makeCmpResultType(Op->getType());
   1681 }
   1682 
   1683 /// ExtractEquivalentCondition - Rummage around inside V looking for something
   1684 /// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
   1685 /// otherwise return null.  Helper function for analyzing max/min idioms.
   1686 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
   1687                                          Value *LHS, Value *RHS) {
   1688   SelectInst *SI = dyn_cast<SelectInst>(V);
   1689   if (!SI)
   1690     return 0;
   1691   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
   1692   if (!Cmp)
   1693     return 0;
   1694   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
   1695   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
   1696     return Cmp;
   1697   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
   1698       LHS == CmpRHS && RHS == CmpLHS)
   1699     return Cmp;
   1700   return 0;
   1701 }
   1702 
   1703 // A significant optimization not implemented here is assuming that alloca
   1704 // addresses are not equal to incoming argument values. They don't *alias*,
   1705 // as we say, but that doesn't mean they aren't equal, so we take a
   1706 // conservative approach.
   1707 //
   1708 // This is inspired in part by C++11 5.10p1:
   1709 //   "Two pointers of the same type compare equal if and only if they are both
   1710 //    null, both point to the same function, or both represent the same
   1711 //    address."
   1712 //
   1713 // This is pretty permissive.
   1714 //
   1715 // It's also partly due to C11 6.5.9p6:
   1716 //   "Two pointers compare equal if and only if both are null pointers, both are
   1717 //    pointers to the same object (including a pointer to an object and a
   1718 //    subobject at its beginning) or function, both are pointers to one past the
   1719 //    last element of the same array object, or one is a pointer to one past the
   1720 //    end of one array object and the other is a pointer to the start of a
   1721 //    different array object that happens to immediately follow the first array
   1722 //    object in the address space.)
   1723 //
   1724 // C11's version is more restrictive, however there's no reason why an argument
   1725 // couldn't be a one-past-the-end value for a stack object in the caller and be
   1726 // equal to the beginning of a stack object in the callee.
   1727 //
   1728 // If the C and C++ standards are ever made sufficiently restrictive in this
   1729 // area, it may be possible to update LLVM's semantics accordingly and reinstate
   1730 // this optimization.
   1731 static Constant *computePointerICmp(const DataLayout *TD,
   1732                                     const TargetLibraryInfo *TLI,
   1733                                     CmpInst::Predicate Pred,
   1734                                     Value *LHS, Value *RHS) {
   1735   // First, skip past any trivial no-ops.
   1736   LHS = LHS->stripPointerCasts();
   1737   RHS = RHS->stripPointerCasts();
   1738 
   1739   // A non-null pointer is not equal to a null pointer.
   1740   if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
   1741       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
   1742     return ConstantInt::get(GetCompareTy(LHS),
   1743                             !CmpInst::isTrueWhenEqual(Pred));
   1744 
   1745   // We can only fold certain predicates on pointer comparisons.
   1746   switch (Pred) {
   1747   default:
   1748     return 0;
   1749 
   1750     // Equality comaprisons are easy to fold.
   1751   case CmpInst::ICMP_EQ:
   1752   case CmpInst::ICMP_NE:
   1753     break;
   1754 
   1755     // We can only handle unsigned relational comparisons because 'inbounds' on
   1756     // a GEP only protects against unsigned wrapping.
   1757   case CmpInst::ICMP_UGT:
   1758   case CmpInst::ICMP_UGE:
   1759   case CmpInst::ICMP_ULT:
   1760   case CmpInst::ICMP_ULE:
   1761     // However, we have to switch them to their signed variants to handle
   1762     // negative indices from the base pointer.
   1763     Pred = ICmpInst::getSignedPredicate(Pred);
   1764     break;
   1765   }
   1766 
   1767   // Strip off any constant offsets so that we can reason about them.
   1768   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
   1769   // here and compare base addresses like AliasAnalysis does, however there are
   1770   // numerous hazards. AliasAnalysis and its utilities rely on special rules
   1771   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
   1772   // doesn't need to guarantee pointer inequality when it says NoAlias.
   1773   Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
   1774   Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
   1775 
   1776   // If LHS and RHS are related via constant offsets to the same base
   1777   // value, we can replace it with an icmp which just compares the offsets.
   1778   if (LHS == RHS)
   1779     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
   1780 
   1781   // Various optimizations for (in)equality comparisons.
   1782   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
   1783     // Different non-empty allocations that exist at the same time have
   1784     // different addresses (if the program can tell). Global variables always
   1785     // exist, so they always exist during the lifetime of each other and all
   1786     // allocas. Two different allocas usually have different addresses...
   1787     //
   1788     // However, if there's an @llvm.stackrestore dynamically in between two
   1789     // allocas, they may have the same address. It's tempting to reduce the
   1790     // scope of the problem by only looking at *static* allocas here. That would
   1791     // cover the majority of allocas while significantly reducing the likelihood
   1792     // of having an @llvm.stackrestore pop up in the middle. However, it's not
   1793     // actually impossible for an @llvm.stackrestore to pop up in the middle of
   1794     // an entry block. Also, if we have a block that's not attached to a
   1795     // function, we can't tell if it's "static" under the current definition.
   1796     // Theoretically, this problem could be fixed by creating a new kind of
   1797     // instruction kind specifically for static allocas. Such a new instruction
   1798     // could be required to be at the top of the entry block, thus preventing it
   1799     // from being subject to a @llvm.stackrestore. Instcombine could even
   1800     // convert regular allocas into these special allocas. It'd be nifty.
   1801     // However, until then, this problem remains open.
   1802     //
   1803     // So, we'll assume that two non-empty allocas have different addresses
   1804     // for now.
   1805     //
   1806     // With all that, if the offsets are within the bounds of their allocations
   1807     // (and not one-past-the-end! so we can't use inbounds!), and their
   1808     // allocations aren't the same, the pointers are not equal.
   1809     //
   1810     // Note that it's not necessary to check for LHS being a global variable
   1811     // address, due to canonicalization and constant folding.
   1812     if (isa<AllocaInst>(LHS) &&
   1813         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
   1814       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
   1815       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
   1816       uint64_t LHSSize, RHSSize;
   1817       if (LHSOffsetCI && RHSOffsetCI &&
   1818           getObjectSize(LHS, LHSSize, TD, TLI) &&
   1819           getObjectSize(RHS, RHSSize, TD, TLI)) {
   1820         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
   1821         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
   1822         if (!LHSOffsetValue.isNegative() &&
   1823             !RHSOffsetValue.isNegative() &&
   1824             LHSOffsetValue.ult(LHSSize) &&
   1825             RHSOffsetValue.ult(RHSSize)) {
   1826           return ConstantInt::get(GetCompareTy(LHS),
   1827                                   !CmpInst::isTrueWhenEqual(Pred));
   1828         }
   1829       }
   1830 
   1831       // Repeat the above check but this time without depending on DataLayout
   1832       // or being able to compute a precise size.
   1833       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
   1834           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
   1835           LHSOffset->isNullValue() &&
   1836           RHSOffset->isNullValue())
   1837         return ConstantInt::get(GetCompareTy(LHS),
   1838                                 !CmpInst::isTrueWhenEqual(Pred));
   1839     }
   1840   }
   1841 
   1842   // Otherwise, fail.
   1843   return 0;
   1844 }
   1845 
   1846 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
   1847 /// fold the result.  If not, this returns null.
   1848 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
   1849                                const Query &Q, unsigned MaxRecurse) {
   1850   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
   1851   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
   1852 
   1853   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
   1854     if (Constant *CRHS = dyn_cast<Constant>(RHS))
   1855       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
   1856 
   1857     // If we have a constant, make sure it is on the RHS.
   1858     std::swap(LHS, RHS);
   1859     Pred = CmpInst::getSwappedPredicate(Pred);
   1860   }
   1861 
   1862   Type *ITy = GetCompareTy(LHS); // The return type.
   1863   Type *OpTy = LHS->getType();   // The operand type.
   1864 
   1865   // icmp X, X -> true/false
   1866   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
   1867   // because X could be 0.
   1868   if (LHS == RHS || isa<UndefValue>(RHS))
   1869     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
   1870 
   1871   // Special case logic when the operands have i1 type.
   1872   if (OpTy->getScalarType()->isIntegerTy(1)) {
   1873     switch (Pred) {
   1874     default: break;
   1875     case ICmpInst::ICMP_EQ:
   1876       // X == 1 -> X
   1877       if (match(RHS, m_One()))
   1878         return LHS;
   1879       break;
   1880     case ICmpInst::ICMP_NE:
   1881       // X != 0 -> X
   1882       if (match(RHS, m_Zero()))
   1883         return LHS;
   1884       break;
   1885     case ICmpInst::ICMP_UGT:
   1886       // X >u 0 -> X
   1887       if (match(RHS, m_Zero()))
   1888         return LHS;
   1889       break;
   1890     case ICmpInst::ICMP_UGE:
   1891       // X >=u 1 -> X
   1892       if (match(RHS, m_One()))
   1893         return LHS;
   1894       break;
   1895     case ICmpInst::ICMP_SLT:
   1896       // X <s 0 -> X
   1897       if (match(RHS, m_Zero()))
   1898         return LHS;
   1899       break;
   1900     case ICmpInst::ICMP_SLE:
   1901       // X <=s -1 -> X
   1902       if (match(RHS, m_One()))
   1903         return LHS;
   1904       break;
   1905     }
   1906   }
   1907 
   1908   // If we are comparing with zero then try hard since this is a common case.
   1909   if (match(RHS, m_Zero())) {
   1910     bool LHSKnownNonNegative, LHSKnownNegative;
   1911     switch (Pred) {
   1912     default: llvm_unreachable("Unknown ICmp predicate!");
   1913     case ICmpInst::ICMP_ULT:
   1914       return getFalse(ITy);
   1915     case ICmpInst::ICMP_UGE:
   1916       return getTrue(ITy);
   1917     case ICmpInst::ICMP_EQ:
   1918     case ICmpInst::ICMP_ULE:
   1919       if (isKnownNonZero(LHS, Q.TD))
   1920         return getFalse(ITy);
   1921       break;
   1922     case ICmpInst::ICMP_NE:
   1923     case ICmpInst::ICMP_UGT:
   1924       if (isKnownNonZero(LHS, Q.TD))
   1925         return getTrue(ITy);
   1926       break;
   1927     case ICmpInst::ICMP_SLT:
   1928       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
   1929       if (LHSKnownNegative)
   1930         return getTrue(ITy);
   1931       if (LHSKnownNonNegative)
   1932         return getFalse(ITy);
   1933       break;
   1934     case ICmpInst::ICMP_SLE:
   1935       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
   1936       if (LHSKnownNegative)
   1937         return getTrue(ITy);
   1938       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
   1939         return getFalse(ITy);
   1940       break;
   1941     case ICmpInst::ICMP_SGE:
   1942       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
   1943       if (LHSKnownNegative)
   1944         return getFalse(ITy);
   1945       if (LHSKnownNonNegative)
   1946         return getTrue(ITy);
   1947       break;
   1948     case ICmpInst::ICMP_SGT:
   1949       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
   1950       if (LHSKnownNegative)
   1951         return getFalse(ITy);
   1952       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
   1953         return getTrue(ITy);
   1954       break;
   1955     }
   1956   }
   1957 
   1958   // See if we are doing a comparison with a constant integer.
   1959   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
   1960     // Rule out tautological comparisons (eg., ult 0 or uge 0).
   1961     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
   1962     if (RHS_CR.isEmptySet())
   1963       return ConstantInt::getFalse(CI->getContext());
   1964     if (RHS_CR.isFullSet())
   1965       return ConstantInt::getTrue(CI->getContext());
   1966 
   1967     // Many binary operators with constant RHS have easy to compute constant
   1968     // range.  Use them to check whether the comparison is a tautology.
   1969     uint32_t Width = CI->getBitWidth();
   1970     APInt Lower = APInt(Width, 0);
   1971     APInt Upper = APInt(Width, 0);
   1972     ConstantInt *CI2;
   1973     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
   1974       // 'urem x, CI2' produces [0, CI2).
   1975       Upper = CI2->getValue();
   1976     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
   1977       // 'srem x, CI2' produces (-|CI2|, |CI2|).
   1978       Upper = CI2->getValue().abs();
   1979       Lower = (-Upper) + 1;
   1980     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
   1981       // 'udiv CI2, x' produces [0, CI2].
   1982       Upper = CI2->getValue() + 1;
   1983     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
   1984       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
   1985       APInt NegOne = APInt::getAllOnesValue(Width);
   1986       if (!CI2->isZero())
   1987         Upper = NegOne.udiv(CI2->getValue()) + 1;
   1988     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
   1989       // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
   1990       APInt IntMin = APInt::getSignedMinValue(Width);
   1991       APInt IntMax = APInt::getSignedMaxValue(Width);
   1992       APInt Val = CI2->getValue().abs();
   1993       if (!Val.isMinValue()) {
   1994         Lower = IntMin.sdiv(Val);
   1995         Upper = IntMax.sdiv(Val) + 1;
   1996       }
   1997     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
   1998       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
   1999       APInt NegOne = APInt::getAllOnesValue(Width);
   2000       if (CI2->getValue().ult(Width))
   2001         Upper = NegOne.lshr(CI2->getValue()) + 1;
   2002     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
   2003       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
   2004       APInt IntMin = APInt::getSignedMinValue(Width);
   2005       APInt IntMax = APInt::getSignedMaxValue(Width);
   2006       if (CI2->getValue().ult(Width)) {
   2007         Lower = IntMin.ashr(CI2->getValue());
   2008         Upper = IntMax.ashr(CI2->getValue()) + 1;
   2009       }
   2010     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
   2011       // 'or x, CI2' produces [CI2, UINT_MAX].
   2012       Lower = CI2->getValue();
   2013     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
   2014       // 'and x, CI2' produces [0, CI2].
   2015       Upper = CI2->getValue() + 1;
   2016     }
   2017     if (Lower != Upper) {
   2018       ConstantRange LHS_CR = ConstantRange(Lower, Upper);
   2019       if (RHS_CR.contains(LHS_CR))
   2020         return ConstantInt::getTrue(RHS->getContext());
   2021       if (RHS_CR.inverse().contains(LHS_CR))
   2022         return ConstantInt::getFalse(RHS->getContext());
   2023     }
   2024   }
   2025 
   2026   // Compare of cast, for example (zext X) != 0 -> X != 0
   2027   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
   2028     Instruction *LI = cast<CastInst>(LHS);
   2029     Value *SrcOp = LI->getOperand(0);
   2030     Type *SrcTy = SrcOp->getType();
   2031     Type *DstTy = LI->getType();
   2032 
   2033     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
   2034     // if the integer type is the same size as the pointer type.
   2035     if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
   2036         Q.TD->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
   2037       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
   2038         // Transfer the cast to the constant.
   2039         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
   2040                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
   2041                                         Q, MaxRecurse-1))
   2042           return V;
   2043       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
   2044         if (RI->getOperand(0)->getType() == SrcTy)
   2045           // Compare without the cast.
   2046           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
   2047                                           Q, MaxRecurse-1))
   2048             return V;
   2049       }
   2050     }
   2051 
   2052     if (isa<ZExtInst>(LHS)) {
   2053       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
   2054       // same type.
   2055       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
   2056         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
   2057           // Compare X and Y.  Note that signed predicates become unsigned.
   2058           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
   2059                                           SrcOp, RI->getOperand(0), Q,
   2060                                           MaxRecurse-1))
   2061             return V;
   2062       }
   2063       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
   2064       // too.  If not, then try to deduce the result of the comparison.
   2065       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
   2066         // Compute the constant that would happen if we truncated to SrcTy then
   2067         // reextended to DstTy.
   2068         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
   2069         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
   2070 
   2071         // If the re-extended constant didn't change then this is effectively
   2072         // also a case of comparing two zero-extended values.
   2073         if (RExt == CI && MaxRecurse)
   2074           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
   2075                                         SrcOp, Trunc, Q, MaxRecurse-1))
   2076             return V;
   2077 
   2078         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
   2079         // there.  Use this to work out the result of the comparison.
   2080         if (RExt != CI) {
   2081           switch (Pred) {
   2082           default: llvm_unreachable("Unknown ICmp predicate!");
   2083           // LHS <u RHS.
   2084           case ICmpInst::ICMP_EQ:
   2085           case ICmpInst::ICMP_UGT:
   2086           case ICmpInst::ICMP_UGE:
   2087             return ConstantInt::getFalse(CI->getContext());
   2088 
   2089           case ICmpInst::ICMP_NE:
   2090           case ICmpInst::ICMP_ULT:
   2091           case ICmpInst::ICMP_ULE:
   2092             return ConstantInt::getTrue(CI->getContext());
   2093 
   2094           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
   2095           // is non-negative then LHS <s RHS.
   2096           case ICmpInst::ICMP_SGT:
   2097           case ICmpInst::ICMP_SGE:
   2098             return CI->getValue().isNegative() ?
   2099               ConstantInt::getTrue(CI->getContext()) :
   2100               ConstantInt::getFalse(CI->getContext());
   2101 
   2102           case ICmpInst::ICMP_SLT:
   2103           case ICmpInst::ICMP_SLE:
   2104             return CI->getValue().isNegative() ?
   2105               ConstantInt::getFalse(CI->getContext()) :
   2106               ConstantInt::getTrue(CI->getContext());
   2107           }
   2108         }
   2109       }
   2110     }
   2111 
   2112     if (isa<SExtInst>(LHS)) {
   2113       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
   2114       // same type.
   2115       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
   2116         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
   2117           // Compare X and Y.  Note that the predicate does not change.
   2118           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
   2119                                           Q, MaxRecurse-1))
   2120             return V;
   2121       }
   2122       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
   2123       // too.  If not, then try to deduce the result of the comparison.
   2124       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
   2125         // Compute the constant that would happen if we truncated to SrcTy then
   2126         // reextended to DstTy.
   2127         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
   2128         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
   2129 
   2130         // If the re-extended constant didn't change then this is effectively
   2131         // also a case of comparing two sign-extended values.
   2132         if (RExt == CI && MaxRecurse)
   2133           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
   2134             return V;
   2135 
   2136         // Otherwise the upper bits of LHS are all equal, while RHS has varying
   2137         // bits there.  Use this to work out the result of the comparison.
   2138         if (RExt != CI) {
   2139           switch (Pred) {
   2140           default: llvm_unreachable("Unknown ICmp predicate!");
   2141           case ICmpInst::ICMP_EQ:
   2142             return ConstantInt::getFalse(CI->getContext());
   2143           case ICmpInst::ICMP_NE:
   2144             return ConstantInt::getTrue(CI->getContext());
   2145 
   2146           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
   2147           // LHS >s RHS.
   2148           case ICmpInst::ICMP_SGT:
   2149           case ICmpInst::ICMP_SGE:
   2150             return CI->getValue().isNegative() ?
   2151               ConstantInt::getTrue(CI->getContext()) :
   2152               ConstantInt::getFalse(CI->getContext());
   2153           case ICmpInst::ICMP_SLT:
   2154           case ICmpInst::ICMP_SLE:
   2155             return CI->getValue().isNegative() ?
   2156               ConstantInt::getFalse(CI->getContext()) :
   2157               ConstantInt::getTrue(CI->getContext());
   2158 
   2159           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
   2160           // LHS >u RHS.
   2161           case ICmpInst::ICMP_UGT:
   2162           case ICmpInst::ICMP_UGE:
   2163             // Comparison is true iff the LHS <s 0.
   2164             if (MaxRecurse)
   2165               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
   2166                                               Constant::getNullValue(SrcTy),
   2167                                               Q, MaxRecurse-1))
   2168                 return V;
   2169             break;
   2170           case ICmpInst::ICMP_ULT:
   2171           case ICmpInst::ICMP_ULE:
   2172             // Comparison is true iff the LHS >=s 0.
   2173             if (MaxRecurse)
   2174               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
   2175                                               Constant::getNullValue(SrcTy),
   2176                                               Q, MaxRecurse-1))
   2177                 return V;
   2178             break;
   2179           }
   2180         }
   2181       }
   2182     }
   2183   }
   2184 
   2185   // Special logic for binary operators.
   2186   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
   2187   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
   2188   if (MaxRecurse && (LBO || RBO)) {
   2189     // Analyze the case when either LHS or RHS is an add instruction.
   2190     Value *A = 0, *B = 0, *C = 0, *D = 0;
   2191     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
   2192     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
   2193     if (LBO && LBO->getOpcode() == Instruction::Add) {
   2194       A = LBO->getOperand(0); B = LBO->getOperand(1);
   2195       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
   2196         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
   2197         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
   2198     }
   2199     if (RBO && RBO->getOpcode() == Instruction::Add) {
   2200       C = RBO->getOperand(0); D = RBO->getOperand(1);
   2201       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
   2202         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
   2203         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
   2204     }
   2205 
   2206     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
   2207     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
   2208       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
   2209                                       Constant::getNullValue(RHS->getType()),
   2210                                       Q, MaxRecurse-1))
   2211         return V;
   2212 
   2213     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
   2214     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
   2215       if (Value *V = SimplifyICmpInst(Pred,
   2216                                       Constant::getNullValue(LHS->getType()),
   2217                                       C == LHS ? D : C, Q, MaxRecurse-1))
   2218         return V;
   2219 
   2220     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
   2221     if (A && C && (A == C || A == D || B == C || B == D) &&
   2222         NoLHSWrapProblem && NoRHSWrapProblem) {
   2223       // Determine Y and Z in the form icmp (X+Y), (X+Z).
   2224       Value *Y, *Z;
   2225       if (A == C) {
   2226         // C + B == C + D  ->  B == D
   2227         Y = B;
   2228         Z = D;
   2229       } else if (A == D) {
   2230         // D + B == C + D  ->  B == C
   2231         Y = B;
   2232         Z = C;
   2233       } else if (B == C) {
   2234         // A + C == C + D  ->  A == D
   2235         Y = A;
   2236         Z = D;
   2237       } else {
   2238         assert(B == D);
   2239         // A + D == C + D  ->  A == C
   2240         Y = A;
   2241         Z = C;
   2242       }
   2243       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
   2244         return V;
   2245     }
   2246   }
   2247 
   2248   // icmp pred (urem X, Y), Y
   2249   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
   2250     bool KnownNonNegative, KnownNegative;
   2251     switch (Pred) {
   2252     default:
   2253       break;
   2254     case ICmpInst::ICMP_SGT:
   2255     case ICmpInst::ICMP_SGE:
   2256       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
   2257       if (!KnownNonNegative)
   2258         break;
   2259       // fall-through
   2260     case ICmpInst::ICMP_EQ:
   2261     case ICmpInst::ICMP_UGT:
   2262     case ICmpInst::ICMP_UGE:
   2263       return getFalse(ITy);
   2264     case ICmpInst::ICMP_SLT:
   2265     case ICmpInst::ICMP_SLE:
   2266       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
   2267       if (!KnownNonNegative)
   2268         break;
   2269       // fall-through
   2270     case ICmpInst::ICMP_NE:
   2271     case ICmpInst::ICMP_ULT:
   2272     case ICmpInst::ICMP_ULE:
   2273       return getTrue(ITy);
   2274     }
   2275   }
   2276 
   2277   // icmp pred X, (urem Y, X)
   2278   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
   2279     bool KnownNonNegative, KnownNegative;
   2280     switch (Pred) {
   2281     default:
   2282       break;
   2283     case ICmpInst::ICMP_SGT:
   2284     case ICmpInst::ICMP_SGE:
   2285       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
   2286       if (!KnownNonNegative)
   2287         break;
   2288       // fall-through
   2289     case ICmpInst::ICMP_NE:
   2290     case ICmpInst::ICMP_UGT:
   2291     case ICmpInst::ICMP_UGE:
   2292       return getTrue(ITy);
   2293     case ICmpInst::ICMP_SLT:
   2294     case ICmpInst::ICMP_SLE:
   2295       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
   2296       if (!KnownNonNegative)
   2297         break;
   2298       // fall-through
   2299     case ICmpInst::ICMP_EQ:
   2300     case ICmpInst::ICMP_ULT:
   2301     case ICmpInst::ICMP_ULE:
   2302       return getFalse(ITy);
   2303     }
   2304   }
   2305 
   2306   // x udiv y <=u x.
   2307   if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
   2308     // icmp pred (X /u Y), X
   2309     if (Pred == ICmpInst::ICMP_UGT)
   2310       return getFalse(ITy);
   2311     if (Pred == ICmpInst::ICMP_ULE)
   2312       return getTrue(ITy);
   2313   }
   2314 
   2315   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
   2316       LBO->getOperand(1) == RBO->getOperand(1)) {
   2317     switch (LBO->getOpcode()) {
   2318     default: break;
   2319     case Instruction::UDiv:
   2320     case Instruction::LShr:
   2321       if (ICmpInst::isSigned(Pred))
   2322         break;
   2323       // fall-through
   2324     case Instruction::SDiv:
   2325     case Instruction::AShr:
   2326       if (!LBO->isExact() || !RBO->isExact())
   2327         break;
   2328       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
   2329                                       RBO->getOperand(0), Q, MaxRecurse-1))
   2330         return V;
   2331       break;
   2332     case Instruction::Shl: {
   2333       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
   2334       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
   2335       if (!NUW && !NSW)
   2336         break;
   2337       if (!NSW && ICmpInst::isSigned(Pred))
   2338         break;
   2339       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
   2340                                       RBO->getOperand(0), Q, MaxRecurse-1))
   2341         return V;
   2342       break;
   2343     }
   2344     }
   2345   }
   2346 
   2347   // Simplify comparisons involving max/min.
   2348   Value *A, *B;
   2349   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
   2350   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
   2351 
   2352   // Signed variants on "max(a,b)>=a -> true".
   2353   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
   2354     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
   2355     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
   2356     // We analyze this as smax(A, B) pred A.
   2357     P = Pred;
   2358   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
   2359              (A == LHS || B == LHS)) {
   2360     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
   2361     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
   2362     // We analyze this as smax(A, B) swapped-pred A.
   2363     P = CmpInst::getSwappedPredicate(Pred);
   2364   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
   2365              (A == RHS || B == RHS)) {
   2366     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
   2367     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
   2368     // We analyze this as smax(-A, -B) swapped-pred -A.
   2369     // Note that we do not need to actually form -A or -B thanks to EqP.
   2370     P = CmpInst::getSwappedPredicate(Pred);
   2371   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
   2372              (A == LHS || B == LHS)) {
   2373     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
   2374     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
   2375     // We analyze this as smax(-A, -B) pred -A.
   2376     // Note that we do not need to actually form -A or -B thanks to EqP.
   2377     P = Pred;
   2378   }
   2379   if (P != CmpInst::BAD_ICMP_PREDICATE) {
   2380     // Cases correspond to "max(A, B) p A".
   2381     switch (P) {
   2382     default:
   2383       break;
   2384     case CmpInst::ICMP_EQ:
   2385     case CmpInst::ICMP_SLE:
   2386       // Equivalent to "A EqP B".  This may be the same as the condition tested
   2387       // in the max/min; if so, we can just return that.
   2388       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
   2389         return V;
   2390       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
   2391         return V;
   2392       // Otherwise, see if "A EqP B" simplifies.
   2393       if (MaxRecurse)
   2394         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
   2395           return V;
   2396       break;
   2397     case CmpInst::ICMP_NE:
   2398     case CmpInst::ICMP_SGT: {
   2399       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
   2400       // Equivalent to "A InvEqP B".  This may be the same as the condition
   2401       // tested in the max/min; if so, we can just return that.
   2402       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
   2403         return V;
   2404       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
   2405         return V;
   2406       // Otherwise, see if "A InvEqP B" simplifies.
   2407       if (MaxRecurse)
   2408         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
   2409           return V;
   2410       break;
   2411     }
   2412     case CmpInst::ICMP_SGE:
   2413       // Always true.
   2414       return getTrue(ITy);
   2415     case CmpInst::ICMP_SLT:
   2416       // Always false.
   2417       return getFalse(ITy);
   2418     }
   2419   }
   2420 
   2421   // Unsigned variants on "max(a,b)>=a -> true".
   2422   P = CmpInst::BAD_ICMP_PREDICATE;
   2423   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
   2424     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
   2425     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
   2426     // We analyze this as umax(A, B) pred A.
   2427     P = Pred;
   2428   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
   2429              (A == LHS || B == LHS)) {
   2430     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
   2431     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
   2432     // We analyze this as umax(A, B) swapped-pred A.
   2433     P = CmpInst::getSwappedPredicate(Pred);
   2434   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
   2435              (A == RHS || B == RHS)) {
   2436     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
   2437     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
   2438     // We analyze this as umax(-A, -B) swapped-pred -A.
   2439     // Note that we do not need to actually form -A or -B thanks to EqP.
   2440     P = CmpInst::getSwappedPredicate(Pred);
   2441   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
   2442              (A == LHS || B == LHS)) {
   2443     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
   2444     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
   2445     // We analyze this as umax(-A, -B) pred -A.
   2446     // Note that we do not need to actually form -A or -B thanks to EqP.
   2447     P = Pred;
   2448   }
   2449   if (P != CmpInst::BAD_ICMP_PREDICATE) {
   2450     // Cases correspond to "max(A, B) p A".
   2451     switch (P) {
   2452     default:
   2453       break;
   2454     case CmpInst::ICMP_EQ:
   2455     case CmpInst::ICMP_ULE:
   2456       // Equivalent to "A EqP B".  This may be the same as the condition tested
   2457       // in the max/min; if so, we can just return that.
   2458       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
   2459         return V;
   2460       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
   2461         return V;
   2462       // Otherwise, see if "A EqP B" simplifies.
   2463       if (MaxRecurse)
   2464         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
   2465           return V;
   2466       break;
   2467     case CmpInst::ICMP_NE:
   2468     case CmpInst::ICMP_UGT: {
   2469       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
   2470       // Equivalent to "A InvEqP B".  This may be the same as the condition
   2471       // tested in the max/min; if so, we can just return that.
   2472       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
   2473         return V;
   2474       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
   2475         return V;
   2476       // Otherwise, see if "A InvEqP B" simplifies.
   2477       if (MaxRecurse)
   2478         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
   2479           return V;
   2480       break;
   2481     }
   2482     case CmpInst::ICMP_UGE:
   2483       // Always true.
   2484       return getTrue(ITy);
   2485     case CmpInst::ICMP_ULT:
   2486       // Always false.
   2487       return getFalse(ITy);
   2488     }
   2489   }
   2490 
   2491   // Variants on "max(x,y) >= min(x,z)".
   2492   Value *C, *D;
   2493   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
   2494       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
   2495       (A == C || A == D || B == C || B == D)) {
   2496     // max(x, ?) pred min(x, ?).
   2497     if (Pred == CmpInst::ICMP_SGE)
   2498       // Always true.
   2499       return getTrue(ITy);
   2500     if (Pred == CmpInst::ICMP_SLT)
   2501       // Always false.
   2502       return getFalse(ITy);
   2503   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
   2504              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
   2505              (A == C || A == D || B == C || B == D)) {
   2506     // min(x, ?) pred max(x, ?).
   2507     if (Pred == CmpInst::ICMP_SLE)
   2508       // Always true.
   2509       return getTrue(ITy);
   2510     if (Pred == CmpInst::ICMP_SGT)
   2511       // Always false.
   2512       return getFalse(ITy);
   2513   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
   2514              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
   2515              (A == C || A == D || B == C || B == D)) {
   2516     // max(x, ?) pred min(x, ?).
   2517     if (Pred == CmpInst::ICMP_UGE)
   2518       // Always true.
   2519       return getTrue(ITy);
   2520     if (Pred == CmpInst::ICMP_ULT)
   2521       // Always false.
   2522       return getFalse(ITy);
   2523   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
   2524              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
   2525              (A == C || A == D || B == C || B == D)) {
   2526     // min(x, ?) pred max(x, ?).
   2527     if (Pred == CmpInst::ICMP_ULE)
   2528       // Always true.
   2529       return getTrue(ITy);
   2530     if (Pred == CmpInst::ICMP_UGT)
   2531       // Always false.
   2532       return getFalse(ITy);
   2533   }
   2534 
   2535   // Simplify comparisons of related pointers using a powerful, recursive
   2536   // GEP-walk when we have target data available..
   2537   if (LHS->getType()->isPointerTy())
   2538     if (Constant *C = computePointerICmp(Q.TD, Q.TLI, Pred, LHS, RHS))
   2539       return C;
   2540 
   2541   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
   2542     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
   2543       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
   2544           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
   2545           (ICmpInst::isEquality(Pred) ||
   2546            (GLHS->isInBounds() && GRHS->isInBounds() &&
   2547             Pred == ICmpInst::getSignedPredicate(Pred)))) {
   2548         // The bases are equal and the indices are constant.  Build a constant
   2549         // expression GEP with the same indices and a null base pointer to see
   2550         // what constant folding can make out of it.
   2551         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
   2552         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
   2553         Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
   2554 
   2555         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
   2556         Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
   2557         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
   2558       }
   2559     }
   2560   }
   2561 
   2562   // If the comparison is with the result of a select instruction, check whether
   2563   // comparing with either branch of the select always yields the same value.
   2564   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
   2565     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
   2566       return V;
   2567 
   2568   // If the comparison is with the result of a phi instruction, check whether
   2569   // doing the compare with each incoming phi value yields a common result.
   2570   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
   2571     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
   2572       return V;
   2573 
   2574   return 0;
   2575 }
   2576 
   2577 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
   2578                               const DataLayout *TD,
   2579                               const TargetLibraryInfo *TLI,
   2580                               const DominatorTree *DT) {
   2581   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
   2582                             RecursionLimit);
   2583 }
   2584 
   2585 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
   2586 /// fold the result.  If not, this returns null.
   2587 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
   2588                                const Query &Q, unsigned MaxRecurse) {
   2589   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
   2590   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
   2591 
   2592   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
   2593     if (Constant *CRHS = dyn_cast<Constant>(RHS))
   2594       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
   2595 
   2596     // If we have a constant, make sure it is on the RHS.
   2597     std::swap(LHS, RHS);
   2598     Pred = CmpInst::getSwappedPredicate(Pred);
   2599   }
   2600 
   2601   // Fold trivial predicates.
   2602   if (Pred == FCmpInst::FCMP_FALSE)
   2603     return ConstantInt::get(GetCompareTy(LHS), 0);
   2604   if (Pred == FCmpInst::FCMP_TRUE)
   2605     return ConstantInt::get(GetCompareTy(LHS), 1);
   2606 
   2607   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
   2608     return UndefValue::get(GetCompareTy(LHS));
   2609 
   2610   // fcmp x,x -> true/false.  Not all compares are foldable.
   2611   if (LHS == RHS) {
   2612     if (CmpInst::isTrueWhenEqual(Pred))
   2613       return ConstantInt::get(GetCompareTy(LHS), 1);
   2614     if (CmpInst::isFalseWhenEqual(Pred))
   2615       return ConstantInt::get(GetCompareTy(LHS), 0);
   2616   }
   2617 
   2618   // Handle fcmp with constant RHS
   2619   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
   2620     // If the constant is a nan, see if we can fold the comparison based on it.
   2621     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
   2622       if (CFP->getValueAPF().isNaN()) {
   2623         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
   2624           return ConstantInt::getFalse(CFP->getContext());
   2625         assert(FCmpInst::isUnordered(Pred) &&
   2626                "Comparison must be either ordered or unordered!");
   2627         // True if unordered.
   2628         return ConstantInt::getTrue(CFP->getContext());
   2629       }
   2630       // Check whether the constant is an infinity.
   2631       if (CFP->getValueAPF().isInfinity()) {
   2632         if (CFP->getValueAPF().isNegative()) {
   2633           switch (Pred) {
   2634           case FCmpInst::FCMP_OLT:
   2635             // No value is ordered and less than negative infinity.
   2636             return ConstantInt::getFalse(CFP->getContext());
   2637           case FCmpInst::FCMP_UGE:
   2638             // All values are unordered with or at least negative infinity.
   2639             return ConstantInt::getTrue(CFP->getContext());
   2640           default:
   2641             break;
   2642           }
   2643         } else {
   2644           switch (Pred) {
   2645           case FCmpInst::FCMP_OGT:
   2646             // No value is ordered and greater than infinity.
   2647             return ConstantInt::getFalse(CFP->getContext());
   2648           case FCmpInst::FCMP_ULE:
   2649             // All values are unordered with and at most infinity.
   2650             return ConstantInt::getTrue(CFP->getContext());
   2651           default:
   2652             break;
   2653           }
   2654         }
   2655       }
   2656     }
   2657   }
   2658 
   2659   // If the comparison is with the result of a select instruction, check whether
   2660   // comparing with either branch of the select always yields the same value.
   2661   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
   2662     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
   2663       return V;
   2664 
   2665   // If the comparison is with the result of a phi instruction, check whether
   2666   // doing the compare with each incoming phi value yields a common result.
   2667   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
   2668     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
   2669       return V;
   2670 
   2671   return 0;
   2672 }
   2673 
   2674 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
   2675                               const DataLayout *TD,
   2676                               const TargetLibraryInfo *TLI,
   2677                               const DominatorTree *DT) {
   2678   return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
   2679                             RecursionLimit);
   2680 }
   2681 
   2682 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
   2683 /// the result.  If not, this returns null.
   2684 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
   2685                                  Value *FalseVal, const Query &Q,
   2686                                  unsigned MaxRecurse) {
   2687   // select true, X, Y  -> X
   2688   // select false, X, Y -> Y
   2689   if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
   2690     return CB->getZExtValue() ? TrueVal : FalseVal;
   2691 
   2692   // select C, X, X -> X
   2693   if (TrueVal == FalseVal)
   2694     return TrueVal;
   2695 
   2696   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
   2697     if (isa<Constant>(TrueVal))
   2698       return TrueVal;
   2699     return FalseVal;
   2700   }
   2701   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
   2702     return FalseVal;
   2703   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
   2704     return TrueVal;
   2705 
   2706   return 0;
   2707 }
   2708 
   2709 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
   2710                                 const DataLayout *TD,
   2711                                 const TargetLibraryInfo *TLI,
   2712                                 const DominatorTree *DT) {
   2713   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
   2714                               RecursionLimit);
   2715 }
   2716 
   2717 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
   2718 /// fold the result.  If not, this returns null.
   2719 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
   2720   // The type of the GEP pointer operand.
   2721   PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
   2722   // The GEP pointer operand is not a pointer, it's a vector of pointers.
   2723   if (!PtrTy)
   2724     return 0;
   2725 
   2726   // getelementptr P -> P.
   2727   if (Ops.size() == 1)
   2728     return Ops[0];
   2729 
   2730   if (isa<UndefValue>(Ops[0])) {
   2731     // Compute the (pointer) type returned by the GEP instruction.
   2732     Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
   2733     Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
   2734     return UndefValue::get(GEPTy);
   2735   }
   2736 
   2737   if (Ops.size() == 2) {
   2738     // getelementptr P, 0 -> P.
   2739     if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
   2740       if (C->isZero())
   2741         return Ops[0];
   2742     // getelementptr P, N -> P if P points to a type of zero size.
   2743     if (Q.TD) {
   2744       Type *Ty = PtrTy->getElementType();
   2745       if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
   2746         return Ops[0];
   2747     }
   2748   }
   2749 
   2750   // Check to see if this is constant foldable.
   2751   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
   2752     if (!isa<Constant>(Ops[i]))
   2753       return 0;
   2754 
   2755   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
   2756 }
   2757 
   2758 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *TD,
   2759                              const TargetLibraryInfo *TLI,
   2760                              const DominatorTree *DT) {
   2761   return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
   2762 }
   2763 
   2764 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
   2765 /// can fold the result.  If not, this returns null.
   2766 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
   2767                                       ArrayRef<unsigned> Idxs, const Query &Q,
   2768                                       unsigned) {
   2769   if (Constant *CAgg = dyn_cast<Constant>(Agg))
   2770     if (Constant *CVal = dyn_cast<Constant>(Val))
   2771       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
   2772 
   2773   // insertvalue x, undef, n -> x
   2774   if (match(Val, m_Undef()))
   2775     return Agg;
   2776 
   2777   // insertvalue x, (extractvalue y, n), n
   2778   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
   2779     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
   2780         EV->getIndices() == Idxs) {
   2781       // insertvalue undef, (extractvalue y, n), n -> y
   2782       if (match(Agg, m_Undef()))
   2783         return EV->getAggregateOperand();
   2784 
   2785       // insertvalue y, (extractvalue y, n), n -> y
   2786       if (Agg == EV->getAggregateOperand())
   2787         return Agg;
   2788     }
   2789 
   2790   return 0;
   2791 }
   2792 
   2793 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
   2794                                      ArrayRef<unsigned> Idxs,
   2795                                      const DataLayout *TD,
   2796                                      const TargetLibraryInfo *TLI,
   2797                                      const DominatorTree *DT) {
   2798   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
   2799                                    RecursionLimit);
   2800 }
   2801 
   2802 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
   2803 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
   2804   // If all of the PHI's incoming values are the same then replace the PHI node
   2805   // with the common value.
   2806   Value *CommonValue = 0;
   2807   bool HasUndefInput = false;
   2808   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
   2809     Value *Incoming = PN->getIncomingValue(i);
   2810     // If the incoming value is the phi node itself, it can safely be skipped.
   2811     if (Incoming == PN) continue;
   2812     if (isa<UndefValue>(Incoming)) {
   2813       // Remember that we saw an undef value, but otherwise ignore them.
   2814       HasUndefInput = true;
   2815       continue;
   2816     }
   2817     if (CommonValue && Incoming != CommonValue)
   2818       return 0;  // Not the same, bail out.
   2819     CommonValue = Incoming;
   2820   }
   2821 
   2822   // If CommonValue is null then all of the incoming values were either undef or
   2823   // equal to the phi node itself.
   2824   if (!CommonValue)
   2825     return UndefValue::get(PN->getType());
   2826 
   2827   // If we have a PHI node like phi(X, undef, X), where X is defined by some
   2828   // instruction, we cannot return X as the result of the PHI node unless it
   2829   // dominates the PHI block.
   2830   if (HasUndefInput)
   2831     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
   2832 
   2833   return CommonValue;
   2834 }
   2835 
   2836 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
   2837   if (Constant *C = dyn_cast<Constant>(Op))
   2838     return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
   2839 
   2840   return 0;
   2841 }
   2842 
   2843 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *TD,
   2844                                const TargetLibraryInfo *TLI,
   2845                                const DominatorTree *DT) {
   2846   return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
   2847 }
   2848 
   2849 //=== Helper functions for higher up the class hierarchy.
   2850 
   2851 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
   2852 /// fold the result.  If not, this returns null.
   2853 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
   2854                             const Query &Q, unsigned MaxRecurse) {
   2855   switch (Opcode) {
   2856   case Instruction::Add:
   2857     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
   2858                            Q, MaxRecurse);
   2859   case Instruction::FAdd:
   2860     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
   2861 
   2862   case Instruction::Sub:
   2863     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
   2864                            Q, MaxRecurse);
   2865   case Instruction::FSub:
   2866     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
   2867 
   2868   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
   2869   case Instruction::FMul:
   2870     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
   2871   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
   2872   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
   2873   case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
   2874   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
   2875   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
   2876   case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
   2877   case Instruction::Shl:
   2878     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
   2879                            Q, MaxRecurse);
   2880   case Instruction::LShr:
   2881     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
   2882   case Instruction::AShr:
   2883     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
   2884   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
   2885   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
   2886   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
   2887   default:
   2888     if (Constant *CLHS = dyn_cast<Constant>(LHS))
   2889       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
   2890         Constant *COps[] = {CLHS, CRHS};
   2891         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
   2892                                         Q.TLI);
   2893       }
   2894 
   2895     // If the operation is associative, try some generic simplifications.
   2896     if (Instruction::isAssociative(Opcode))
   2897       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
   2898         return V;
   2899 
   2900     // If the operation is with the result of a select instruction check whether
   2901     // operating on either branch of the select always yields the same value.
   2902     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
   2903       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
   2904         return V;
   2905 
   2906     // If the operation is with the result of a phi instruction, check whether
   2907     // operating on all incoming values of the phi always yields the same value.
   2908     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
   2909       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
   2910         return V;
   2911 
   2912     return 0;
   2913   }
   2914 }
   2915 
   2916 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
   2917                            const DataLayout *TD, const TargetLibraryInfo *TLI,
   2918                            const DominatorTree *DT) {
   2919   return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
   2920 }
   2921 
   2922 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
   2923 /// fold the result.
   2924 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
   2925                               const Query &Q, unsigned MaxRecurse) {
   2926   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
   2927     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
   2928   return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
   2929 }
   2930 
   2931 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
   2932                              const DataLayout *TD, const TargetLibraryInfo *TLI,
   2933                              const DominatorTree *DT) {
   2934   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
   2935                            RecursionLimit);
   2936 }
   2937 
   2938 static bool IsIdempotent(Intrinsic::ID ID) {
   2939   switch (ID) {
   2940   default: return false;
   2941 
   2942   // Unary idempotent: f(f(x)) = f(x)
   2943   case Intrinsic::fabs:
   2944   case Intrinsic::floor:
   2945   case Intrinsic::ceil:
   2946   case Intrinsic::trunc:
   2947   case Intrinsic::rint:
   2948   case Intrinsic::nearbyint:
   2949     return true;
   2950   }
   2951 }
   2952 
   2953 template <typename IterTy>
   2954 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
   2955                                 const Query &Q, unsigned MaxRecurse) {
   2956   // Perform idempotent optimizations
   2957   if (!IsIdempotent(IID))
   2958     return 0;
   2959 
   2960   // Unary Ops
   2961   if (std::distance(ArgBegin, ArgEnd) == 1)
   2962     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
   2963       if (II->getIntrinsicID() == IID)
   2964         return II;
   2965 
   2966   return 0;
   2967 }
   2968 
   2969 template <typename IterTy>
   2970 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
   2971                            const Query &Q, unsigned MaxRecurse) {
   2972   Type *Ty = V->getType();
   2973   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
   2974     Ty = PTy->getElementType();
   2975   FunctionType *FTy = cast<FunctionType>(Ty);
   2976 
   2977   // call undef -> undef
   2978   if (isa<UndefValue>(V))
   2979     return UndefValue::get(FTy->getReturnType());
   2980 
   2981   Function *F = dyn_cast<Function>(V);
   2982   if (!F)
   2983     return 0;
   2984 
   2985   if (unsigned IID = F->getIntrinsicID())
   2986     if (Value *Ret =
   2987         SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
   2988       return Ret;
   2989 
   2990   if (!canConstantFoldCallTo(F))
   2991     return 0;
   2992 
   2993   SmallVector<Constant *, 4> ConstantArgs;
   2994   ConstantArgs.reserve(ArgEnd - ArgBegin);
   2995   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
   2996     Constant *C = dyn_cast<Constant>(*I);
   2997     if (!C)
   2998       return 0;
   2999     ConstantArgs.push_back(C);
   3000   }
   3001 
   3002   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
   3003 }
   3004 
   3005 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
   3006                           User::op_iterator ArgEnd, const DataLayout *TD,
   3007                           const TargetLibraryInfo *TLI,
   3008                           const DominatorTree *DT) {
   3009   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(TD, TLI, DT),
   3010                         RecursionLimit);
   3011 }
   3012 
   3013 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
   3014                           const DataLayout *TD, const TargetLibraryInfo *TLI,
   3015                           const DominatorTree *DT) {
   3016   return ::SimplifyCall(V, Args.begin(), Args.end(), Query(TD, TLI, DT),
   3017                         RecursionLimit);
   3018 }
   3019 
   3020 /// SimplifyInstruction - See if we can compute a simplified version of this
   3021 /// instruction.  If not, this returns null.
   3022 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *TD,
   3023                                  const TargetLibraryInfo *TLI,
   3024                                  const DominatorTree *DT) {
   3025   Value *Result;
   3026 
   3027   switch (I->getOpcode()) {
   3028   default:
   3029     Result = ConstantFoldInstruction(I, TD, TLI);
   3030     break;
   3031   case Instruction::FAdd:
   3032     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
   3033                               I->getFastMathFlags(), TD, TLI, DT);
   3034     break;
   3035   case Instruction::Add:
   3036     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
   3037                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
   3038                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
   3039                              TD, TLI, DT);
   3040     break;
   3041   case Instruction::FSub:
   3042     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
   3043                               I->getFastMathFlags(), TD, TLI, DT);
   3044     break;
   3045   case Instruction::Sub:
   3046     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
   3047                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
   3048                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
   3049                              TD, TLI, DT);
   3050     break;
   3051   case Instruction::FMul:
   3052     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
   3053                               I->getFastMathFlags(), TD, TLI, DT);
   3054     break;
   3055   case Instruction::Mul:
   3056     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3057     break;
   3058   case Instruction::SDiv:
   3059     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3060     break;
   3061   case Instruction::UDiv:
   3062     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3063     break;
   3064   case Instruction::FDiv:
   3065     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3066     break;
   3067   case Instruction::SRem:
   3068     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3069     break;
   3070   case Instruction::URem:
   3071     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3072     break;
   3073   case Instruction::FRem:
   3074     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3075     break;
   3076   case Instruction::Shl:
   3077     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
   3078                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
   3079                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
   3080                              TD, TLI, DT);
   3081     break;
   3082   case Instruction::LShr:
   3083     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
   3084                               cast<BinaryOperator>(I)->isExact(),
   3085                               TD, TLI, DT);
   3086     break;
   3087   case Instruction::AShr:
   3088     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
   3089                               cast<BinaryOperator>(I)->isExact(),
   3090                               TD, TLI, DT);
   3091     break;
   3092   case Instruction::And:
   3093     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3094     break;
   3095   case Instruction::Or:
   3096     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3097     break;
   3098   case Instruction::Xor:
   3099     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3100     break;
   3101   case Instruction::ICmp:
   3102     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
   3103                               I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3104     break;
   3105   case Instruction::FCmp:
   3106     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
   3107                               I->getOperand(0), I->getOperand(1), TD, TLI, DT);
   3108     break;
   3109   case Instruction::Select:
   3110     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
   3111                                 I->getOperand(2), TD, TLI, DT);
   3112     break;
   3113   case Instruction::GetElementPtr: {
   3114     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
   3115     Result = SimplifyGEPInst(Ops, TD, TLI, DT);
   3116     break;
   3117   }
   3118   case Instruction::InsertValue: {
   3119     InsertValueInst *IV = cast<InsertValueInst>(I);
   3120     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
   3121                                      IV->getInsertedValueOperand(),
   3122                                      IV->getIndices(), TD, TLI, DT);
   3123     break;
   3124   }
   3125   case Instruction::PHI:
   3126     Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
   3127     break;
   3128   case Instruction::Call: {
   3129     CallSite CS(cast<CallInst>(I));
   3130     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
   3131                           TD, TLI, DT);
   3132     break;
   3133   }
   3134   case Instruction::Trunc:
   3135     Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
   3136     break;
   3137   }
   3138 
   3139   /// If called on unreachable code, the above logic may report that the
   3140   /// instruction simplified to itself.  Make life easier for users by
   3141   /// detecting that case here, returning a safe value instead.
   3142   return Result == I ? UndefValue::get(I->getType()) : Result;
   3143 }
   3144 
   3145 /// \brief Implementation of recursive simplification through an instructions
   3146 /// uses.
   3147 ///
   3148 /// This is the common implementation of the recursive simplification routines.
   3149 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
   3150 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
   3151 /// instructions to process and attempt to simplify it using
   3152 /// InstructionSimplify.
   3153 ///
   3154 /// This routine returns 'true' only when *it* simplifies something. The passed
   3155 /// in simplified value does not count toward this.
   3156 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
   3157                                               const DataLayout *TD,
   3158                                               const TargetLibraryInfo *TLI,
   3159                                               const DominatorTree *DT) {
   3160   bool Simplified = false;
   3161   SmallSetVector<Instruction *, 8> Worklist;
   3162 
   3163   // If we have an explicit value to collapse to, do that round of the
   3164   // simplification loop by hand initially.
   3165   if (SimpleV) {
   3166     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
   3167          ++UI)
   3168       if (*UI != I)
   3169         Worklist.insert(cast<Instruction>(*UI));
   3170 
   3171     // Replace the instruction with its simplified value.
   3172     I->replaceAllUsesWith(SimpleV);
   3173 
   3174     // Gracefully handle edge cases where the instruction is not wired into any
   3175     // parent block.
   3176     if (I->getParent())
   3177       I->eraseFromParent();
   3178   } else {
   3179     Worklist.insert(I);
   3180   }
   3181 
   3182   // Note that we must test the size on each iteration, the worklist can grow.
   3183   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
   3184     I = Worklist[Idx];
   3185 
   3186     // See if this instruction simplifies.
   3187     SimpleV = SimplifyInstruction(I, TD, TLI, DT);
   3188     if (!SimpleV)
   3189       continue;
   3190 
   3191     Simplified = true;
   3192 
   3193     // Stash away all the uses of the old instruction so we can check them for
   3194     // recursive simplifications after a RAUW. This is cheaper than checking all
   3195     // uses of To on the recursive step in most cases.
   3196     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
   3197          ++UI)
   3198       Worklist.insert(cast<Instruction>(*UI));
   3199 
   3200     // Replace the instruction with its simplified value.
   3201     I->replaceAllUsesWith(SimpleV);
   3202 
   3203     // Gracefully handle edge cases where the instruction is not wired into any
   3204     // parent block.
   3205     if (I->getParent())
   3206       I->eraseFromParent();
   3207   }
   3208   return Simplified;
   3209 }
   3210 
   3211 bool llvm::recursivelySimplifyInstruction(Instruction *I,
   3212                                           const DataLayout *TD,
   3213                                           const TargetLibraryInfo *TLI,
   3214                                           const DominatorTree *DT) {
   3215   return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
   3216 }
   3217 
   3218 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
   3219                                          const DataLayout *TD,
   3220                                          const TargetLibraryInfo *TLI,
   3221                                          const DominatorTree *DT) {
   3222   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
   3223   assert(SimpleV && "Must provide a simplified value.");
   3224   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
   3225 }
   3226