LLVM  mainline
InstructionCombining.cpp
Go to the documentation of this file.
00001 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // InstructionCombining - Combine instructions to form fewer, simple
00011 // instructions.  This pass does not modify the CFG.  This pass is where
00012 // algebraic simplification happens.
00013 //
00014 // This pass combines things like:
00015 //    %Y = add i32 %X, 1
00016 //    %Z = add i32 %Y, 1
00017 // into:
00018 //    %Z = add i32 %X, 2
00019 //
00020 // This is a simple worklist driven algorithm.
00021 //
00022 // This pass guarantees that the following canonicalizations are performed on
00023 // the program:
00024 //    1. If a binary operator has a constant operand, it is moved to the RHS
00025 //    2. Bitwise operators with constant operands are always grouped so that
00026 //       shifts are performed first, then or's, then and's, then xor's.
00027 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
00028 //    4. All cmp instructions on boolean values are replaced with logical ops
00029 //    5. add X, X is represented as (X*2) => (X << 1)
00030 //    6. Multiplies with a power-of-two constant argument are transformed into
00031 //       shifts.
00032 //   ... etc.
00033 //
00034 //===----------------------------------------------------------------------===//
00035 
00036 #include "llvm/Transforms/InstCombine/InstCombine.h"
00037 #include "InstCombineInternal.h"
00038 #include "llvm-c/Initialization.h"
00039 #include "llvm/ADT/SmallPtrSet.h"
00040 #include "llvm/ADT/Statistic.h"
00041 #include "llvm/ADT/StringSwitch.h"
00042 #include "llvm/Analysis/AssumptionCache.h"
00043 #include "llvm/Analysis/CFG.h"
00044 #include "llvm/Analysis/ConstantFolding.h"
00045 #include "llvm/Analysis/InstructionSimplify.h"
00046 #include "llvm/Analysis/LibCallSemantics.h"
00047 #include "llvm/Analysis/LoopInfo.h"
00048 #include "llvm/Analysis/MemoryBuiltins.h"
00049 #include "llvm/Analysis/TargetLibraryInfo.h"
00050 #include "llvm/Analysis/ValueTracking.h"
00051 #include "llvm/IR/CFG.h"
00052 #include "llvm/IR/DataLayout.h"
00053 #include "llvm/IR/Dominators.h"
00054 #include "llvm/IR/GetElementPtrTypeIterator.h"
00055 #include "llvm/IR/IntrinsicInst.h"
00056 #include "llvm/IR/PatternMatch.h"
00057 #include "llvm/IR/ValueHandle.h"
00058 #include "llvm/Support/CommandLine.h"
00059 #include "llvm/Support/Debug.h"
00060 #include "llvm/Support/raw_ostream.h"
00061 #include "llvm/Transforms/Scalar.h"
00062 #include "llvm/Transforms/Utils/Local.h"
00063 #include <algorithm>
00064 #include <climits>
00065 using namespace llvm;
00066 using namespace llvm::PatternMatch;
00067 
00068 #define DEBUG_TYPE "instcombine"
00069 
00070 STATISTIC(NumCombined , "Number of insts combined");
00071 STATISTIC(NumConstProp, "Number of constant folds");
00072 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
00073 STATISTIC(NumSunkInst , "Number of instructions sunk");
00074 STATISTIC(NumExpand,    "Number of expansions");
00075 STATISTIC(NumFactor   , "Number of factorizations");
00076 STATISTIC(NumReassoc  , "Number of reassociations");
00077 
00078 Value *InstCombiner::EmitGEPOffset(User *GEP) {
00079   return llvm::EmitGEPOffset(Builder, DL, GEP);
00080 }
00081 
00082 /// ShouldChangeType - Return true if it is desirable to convert a computation
00083 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
00084 /// type for example, or from a smaller to a larger illegal type.
00085 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
00086   assert(From->isIntegerTy() && To->isIntegerTy());
00087 
00088   unsigned FromWidth = From->getPrimitiveSizeInBits();
00089   unsigned ToWidth = To->getPrimitiveSizeInBits();
00090   bool FromLegal = DL.isLegalInteger(FromWidth);
00091   bool ToLegal = DL.isLegalInteger(ToWidth);
00092 
00093   // If this is a legal integer from type, and the result would be an illegal
00094   // type, don't do the transformation.
00095   if (FromLegal && !ToLegal)
00096     return false;
00097 
00098   // Otherwise, if both are illegal, do not increase the size of the result. We
00099   // do allow things like i160 -> i64, but not i64 -> i160.
00100   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
00101     return false;
00102 
00103   return true;
00104 }
00105 
00106 // Return true, if No Signed Wrap should be maintained for I.
00107 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
00108 // where both B and C should be ConstantInts, results in a constant that does
00109 // not overflow. This function only handles the Add and Sub opcodes. For
00110 // all other opcodes, the function conservatively returns false.
00111 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
00112   OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
00113   if (!OBO || !OBO->hasNoSignedWrap()) {
00114     return false;
00115   }
00116 
00117   // We reason about Add and Sub Only.
00118   Instruction::BinaryOps Opcode = I.getOpcode();
00119   if (Opcode != Instruction::Add &&
00120       Opcode != Instruction::Sub) {
00121     return false;
00122   }
00123 
00124   ConstantInt *CB = dyn_cast<ConstantInt>(B);
00125   ConstantInt *CC = dyn_cast<ConstantInt>(C);
00126 
00127   if (!CB || !CC) {
00128     return false;
00129   }
00130 
00131   const APInt &BVal = CB->getValue();
00132   const APInt &CVal = CC->getValue();
00133   bool Overflow = false;
00134 
00135   if (Opcode == Instruction::Add) {
00136     BVal.sadd_ov(CVal, Overflow);
00137   } else {
00138     BVal.ssub_ov(CVal, Overflow);
00139   }
00140 
00141   return !Overflow;
00142 }
00143 
00144 /// Conservatively clears subclassOptionalData after a reassociation or
00145 /// commutation. We preserve fast-math flags when applicable as they can be
00146 /// preserved.
00147 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
00148   FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
00149   if (!FPMO) {
00150     I.clearSubclassOptionalData();
00151     return;
00152   }
00153 
00154   FastMathFlags FMF = I.getFastMathFlags();
00155   I.clearSubclassOptionalData();
00156   I.setFastMathFlags(FMF);
00157 }
00158 
00159 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
00160 /// operators which are associative or commutative:
00161 //
00162 //  Commutative operators:
00163 //
00164 //  1. Order operands such that they are listed from right (least complex) to
00165 //     left (most complex).  This puts constants before unary operators before
00166 //     binary operators.
00167 //
00168 //  Associative operators:
00169 //
00170 //  2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
00171 //  3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
00172 //
00173 //  Associative and commutative operators:
00174 //
00175 //  4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
00176 //  5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
00177 //  6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
00178 //     if C1 and C2 are constants.
00179 //
00180 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
00181   Instruction::BinaryOps Opcode = I.getOpcode();
00182   bool Changed = false;
00183 
00184   do {
00185     // Order operands such that they are listed from right (least complex) to
00186     // left (most complex).  This puts constants before unary operators before
00187     // binary operators.
00188     if (I.isCommutative() && getComplexity(I.getOperand(0)) <
00189         getComplexity(I.getOperand(1)))
00190       Changed = !I.swapOperands();
00191 
00192     BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
00193     BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
00194 
00195     if (I.isAssociative()) {
00196       // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
00197       if (Op0 && Op0->getOpcode() == Opcode) {
00198         Value *A = Op0->getOperand(0);
00199         Value *B = Op0->getOperand(1);
00200         Value *C = I.getOperand(1);
00201 
00202         // Does "B op C" simplify?
00203         if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
00204           // It simplifies to V.  Form "A op V".
00205           I.setOperand(0, A);
00206           I.setOperand(1, V);
00207           // Conservatively clear the optional flags, since they may not be
00208           // preserved by the reassociation.
00209           if (MaintainNoSignedWrap(I, B, C) &&
00210               (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
00211             // Note: this is only valid because SimplifyBinOp doesn't look at
00212             // the operands to Op0.
00213             I.clearSubclassOptionalData();
00214             I.setHasNoSignedWrap(true);
00215           } else {
00216             ClearSubclassDataAfterReassociation(I);
00217           }
00218 
00219           Changed = true;
00220           ++NumReassoc;
00221           continue;
00222         }
00223       }
00224 
00225       // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
00226       if (Op1 && Op1->getOpcode() == Opcode) {
00227         Value *A = I.getOperand(0);
00228         Value *B = Op1->getOperand(0);
00229         Value *C = Op1->getOperand(1);
00230 
00231         // Does "A op B" simplify?
00232         if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
00233           // It simplifies to V.  Form "V op C".
00234           I.setOperand(0, V);
00235           I.setOperand(1, C);
00236           // Conservatively clear the optional flags, since they may not be
00237           // preserved by the reassociation.
00238           ClearSubclassDataAfterReassociation(I);
00239           Changed = true;
00240           ++NumReassoc;
00241           continue;
00242         }
00243       }
00244     }
00245 
00246     if (I.isAssociative() && I.isCommutative()) {
00247       // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
00248       if (Op0 && Op0->getOpcode() == Opcode) {
00249         Value *A = Op0->getOperand(0);
00250         Value *B = Op0->getOperand(1);
00251         Value *C = I.getOperand(1);
00252 
00253         // Does "C op A" simplify?
00254         if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
00255           // It simplifies to V.  Form "V op B".
00256           I.setOperand(0, V);
00257           I.setOperand(1, B);
00258           // Conservatively clear the optional flags, since they may not be
00259           // preserved by the reassociation.
00260           ClearSubclassDataAfterReassociation(I);
00261           Changed = true;
00262           ++NumReassoc;
00263           continue;
00264         }
00265       }
00266 
00267       // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
00268       if (Op1 && Op1->getOpcode() == Opcode) {
00269         Value *A = I.getOperand(0);
00270         Value *B = Op1->getOperand(0);
00271         Value *C = Op1->getOperand(1);
00272 
00273         // Does "C op A" simplify?
00274         if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
00275           // It simplifies to V.  Form "B op V".
00276           I.setOperand(0, B);
00277           I.setOperand(1, V);
00278           // Conservatively clear the optional flags, since they may not be
00279           // preserved by the reassociation.
00280           ClearSubclassDataAfterReassociation(I);
00281           Changed = true;
00282           ++NumReassoc;
00283           continue;
00284         }
00285       }
00286 
00287       // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
00288       // if C1 and C2 are constants.
00289       if (Op0 && Op1 &&
00290           Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
00291           isa<Constant>(Op0->getOperand(1)) &&
00292           isa<Constant>(Op1->getOperand(1)) &&
00293           Op0->hasOneUse() && Op1->hasOneUse()) {
00294         Value *A = Op0->getOperand(0);
00295         Constant *C1 = cast<Constant>(Op0->getOperand(1));
00296         Value *B = Op1->getOperand(0);
00297         Constant *C2 = cast<Constant>(Op1->getOperand(1));
00298 
00299         Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
00300         BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
00301         if (isa<FPMathOperator>(New)) {
00302           FastMathFlags Flags = I.getFastMathFlags();
00303           Flags &= Op0->getFastMathFlags();
00304           Flags &= Op1->getFastMathFlags();
00305           New->setFastMathFlags(Flags);
00306         }
00307         InsertNewInstWith(New, I);
00308         New->takeName(Op1);
00309         I.setOperand(0, New);
00310         I.setOperand(1, Folded);
00311         // Conservatively clear the optional flags, since they may not be
00312         // preserved by the reassociation.
00313         ClearSubclassDataAfterReassociation(I);
00314 
00315         Changed = true;
00316         continue;
00317       }
00318     }
00319 
00320     // No further simplifications.
00321     return Changed;
00322   } while (1);
00323 }
00324 
00325 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
00326 /// "(X LOp Y) ROp (X LOp Z)".
00327 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
00328                                      Instruction::BinaryOps ROp) {
00329   switch (LOp) {
00330   default:
00331     return false;
00332 
00333   case Instruction::And:
00334     // And distributes over Or and Xor.
00335     switch (ROp) {
00336     default:
00337       return false;
00338     case Instruction::Or:
00339     case Instruction::Xor:
00340       return true;
00341     }
00342 
00343   case Instruction::Mul:
00344     // Multiplication distributes over addition and subtraction.
00345     switch (ROp) {
00346     default:
00347       return false;
00348     case Instruction::Add:
00349     case Instruction::Sub:
00350       return true;
00351     }
00352 
00353   case Instruction::Or:
00354     // Or distributes over And.
00355     switch (ROp) {
00356     default:
00357       return false;
00358     case Instruction::And:
00359       return true;
00360     }
00361   }
00362 }
00363 
00364 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
00365 /// "(X ROp Z) LOp (Y ROp Z)".
00366 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
00367                                      Instruction::BinaryOps ROp) {
00368   if (Instruction::isCommutative(ROp))
00369     return LeftDistributesOverRight(ROp, LOp);
00370 
00371   switch (LOp) {
00372   default:
00373     return false;
00374   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
00375   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
00376   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
00377   case Instruction::And:
00378   case Instruction::Or:
00379   case Instruction::Xor:
00380     switch (ROp) {
00381     default:
00382       return false;
00383     case Instruction::Shl:
00384     case Instruction::LShr:
00385     case Instruction::AShr:
00386       return true;
00387     }
00388   }
00389   // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
00390   // but this requires knowing that the addition does not overflow and other
00391   // such subtleties.
00392   return false;
00393 }
00394 
00395 /// This function returns identity value for given opcode, which can be used to
00396 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
00397 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
00398   if (isa<Constant>(V))
00399     return nullptr;
00400 
00401   if (OpCode == Instruction::Mul)
00402     return ConstantInt::get(V->getType(), 1);
00403 
00404   // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
00405 
00406   return nullptr;
00407 }
00408 
00409 /// This function factors binary ops which can be combined using distributive
00410 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
00411 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
00412 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
00413 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
00414 /// RHS to 4.
00415 static Instruction::BinaryOps
00416 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
00417                           BinaryOperator *Op, Value *&LHS, Value *&RHS) {
00418   if (!Op)
00419     return Instruction::BinaryOpsEnd;
00420 
00421   LHS = Op->getOperand(0);
00422   RHS = Op->getOperand(1);
00423 
00424   switch (TopLevelOpcode) {
00425   default:
00426     return Op->getOpcode();
00427 
00428   case Instruction::Add:
00429   case Instruction::Sub:
00430     if (Op->getOpcode() == Instruction::Shl) {
00431       if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
00432         // The multiplier is really 1 << CST.
00433         RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
00434         return Instruction::Mul;
00435       }
00436     }
00437     return Op->getOpcode();
00438   }
00439 
00440   // TODO: We can add other conversions e.g. shr => div etc.
00441 }
00442 
00443 /// This tries to simplify binary operations by factorizing out common terms
00444 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
00445 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
00446                                const DataLayout &DL, BinaryOperator &I,
00447                                Instruction::BinaryOps InnerOpcode, Value *A,
00448                                Value *B, Value *C, Value *D) {
00449 
00450   // If any of A, B, C, D are null, we can not factor I, return early.
00451   // Checking A and C should be enough.
00452   if (!A || !C || !B || !D)
00453     return nullptr;
00454 
00455   Value *V = nullptr;
00456   Value *SimplifiedInst = nullptr;
00457   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00458   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
00459 
00460   // Does "X op' Y" always equal "Y op' X"?
00461   bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
00462 
00463   // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
00464   if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
00465     // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
00466     // commutative case, "(A op' B) op (C op' A)"?
00467     if (A == C || (InnerCommutative && A == D)) {
00468       if (A != C)
00469         std::swap(C, D);
00470       // Consider forming "A op' (B op D)".
00471       // If "B op D" simplifies then it can be formed with no cost.
00472       V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
00473       // If "B op D" doesn't simplify then only go on if both of the existing
00474       // operations "A op' B" and "C op' D" will be zapped as no longer used.
00475       if (!V && LHS->hasOneUse() && RHS->hasOneUse())
00476         V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
00477       if (V) {
00478         SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
00479       }
00480     }
00481 
00482   // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
00483   if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
00484     // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
00485     // commutative case, "(A op' B) op (B op' D)"?
00486     if (B == D || (InnerCommutative && B == C)) {
00487       if (B != D)
00488         std::swap(C, D);
00489       // Consider forming "(A op C) op' B".
00490       // If "A op C" simplifies then it can be formed with no cost.
00491       V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
00492 
00493       // If "A op C" doesn't simplify then only go on if both of the existing
00494       // operations "A op' B" and "C op' D" will be zapped as no longer used.
00495       if (!V && LHS->hasOneUse() && RHS->hasOneUse())
00496         V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
00497       if (V) {
00498         SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
00499       }
00500     }
00501 
00502   if (SimplifiedInst) {
00503     ++NumFactor;
00504     SimplifiedInst->takeName(&I);
00505 
00506     // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
00507     // TODO: Check for NUW.
00508     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
00509       if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
00510         bool HasNSW = false;
00511         if (isa<OverflowingBinaryOperator>(&I))
00512           HasNSW = I.hasNoSignedWrap();
00513 
00514         if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
00515           if (isa<OverflowingBinaryOperator>(Op0))
00516             HasNSW &= Op0->hasNoSignedWrap();
00517 
00518         if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
00519           if (isa<OverflowingBinaryOperator>(Op1))
00520             HasNSW &= Op1->hasNoSignedWrap();
00521 
00522         // We can propogate 'nsw' if we know that
00523         //  %Y = mul nsw i16 %X, C
00524         //  %Z = add nsw i16 %Y, %X
00525         // =>
00526         //  %Z = mul nsw i16 %X, C+1
00527         //
00528         // iff C+1 isn't INT_MIN
00529         const APInt *CInt;
00530         if (TopLevelOpcode == Instruction::Add &&
00531             InnerOpcode == Instruction::Mul)
00532           if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
00533             BO->setHasNoSignedWrap(HasNSW);
00534       }
00535     }
00536   }
00537   return SimplifiedInst;
00538 }
00539 
00540 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
00541 /// which some other binary operation distributes over either by factorizing
00542 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
00543 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
00544 /// a win).  Returns the simplified value, or null if it didn't simplify.
00545 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
00546   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00547   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
00548   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
00549 
00550   // Factorization.
00551   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
00552   auto TopLevelOpcode = I.getOpcode();
00553   auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
00554   auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
00555 
00556   // The instruction has the form "(A op' B) op (C op' D)".  Try to factorize
00557   // a common term.
00558   if (LHSOpcode == RHSOpcode) {
00559     if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
00560       return V;
00561   }
00562 
00563   // The instruction has the form "(A op' B) op (C)".  Try to factorize common
00564   // term.
00565   if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
00566                                   getIdentityValue(LHSOpcode, RHS)))
00567     return V;
00568 
00569   // The instruction has the form "(B) op (C op' D)".  Try to factorize common
00570   // term.
00571   if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
00572                                   getIdentityValue(RHSOpcode, LHS), C, D))
00573     return V;
00574 
00575   // Expansion.
00576   if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
00577     // The instruction has the form "(A op' B) op C".  See if expanding it out
00578     // to "(A op C) op' (B op C)" results in simplifications.
00579     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
00580     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
00581 
00582     // Do "A op C" and "B op C" both simplify?
00583     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
00584       if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
00585         // They do! Return "L op' R".
00586         ++NumExpand;
00587         // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
00588         if ((L == A && R == B) ||
00589             (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
00590           return Op0;
00591         // Otherwise return "L op' R" if it simplifies.
00592         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
00593           return V;
00594         // Otherwise, create a new instruction.
00595         C = Builder->CreateBinOp(InnerOpcode, L, R);
00596         C->takeName(&I);
00597         return C;
00598       }
00599   }
00600 
00601   if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
00602     // The instruction has the form "A op (B op' C)".  See if expanding it out
00603     // to "(A op B) op' (A op C)" results in simplifications.
00604     Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
00605     Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
00606 
00607     // Do "A op B" and "A op C" both simplify?
00608     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
00609       if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
00610         // They do! Return "L op' R".
00611         ++NumExpand;
00612         // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
00613         if ((L == B && R == C) ||
00614             (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
00615           return Op1;
00616         // Otherwise return "L op' R" if it simplifies.
00617         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
00618           return V;
00619         // Otherwise, create a new instruction.
00620         A = Builder->CreateBinOp(InnerOpcode, L, R);
00621         A->takeName(&I);
00622         return A;
00623       }
00624   }
00625 
00626   return nullptr;
00627 }
00628 
00629 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
00630 // if the LHS is a constant zero (which is the 'negate' form).
00631 //
00632 Value *InstCombiner::dyn_castNegVal(Value *V) const {
00633   if (BinaryOperator::isNeg(V))
00634     return BinaryOperator::getNegArgument(V);
00635 
00636   // Constants can be considered to be negated values if they can be folded.
00637   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
00638     return ConstantExpr::getNeg(C);
00639 
00640   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
00641     if (C->getType()->getElementType()->isIntegerTy())
00642       return ConstantExpr::getNeg(C);
00643 
00644   return nullptr;
00645 }
00646 
00647 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
00648 // instruction if the LHS is a constant negative zero (which is the 'negate'
00649 // form).
00650 //
00651 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
00652   if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
00653     return BinaryOperator::getFNegArgument(V);
00654 
00655   // Constants can be considered to be negated values if they can be folded.
00656   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
00657     return ConstantExpr::getFNeg(C);
00658 
00659   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
00660     if (C->getType()->getElementType()->isFloatingPointTy())
00661       return ConstantExpr::getFNeg(C);
00662 
00663   return nullptr;
00664 }
00665 
00666 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
00667                                              InstCombiner *IC) {
00668   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
00669     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
00670   }
00671 
00672   // Figure out if the constant is the left or the right argument.
00673   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
00674   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
00675 
00676   if (Constant *SOC = dyn_cast<Constant>(SO)) {
00677     if (ConstIsRHS)
00678       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
00679     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
00680   }
00681 
00682   Value *Op0 = SO, *Op1 = ConstOperand;
00683   if (!ConstIsRHS)
00684     std::swap(Op0, Op1);
00685 
00686   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
00687     Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
00688                                     SO->getName()+".op");
00689     Instruction *FPInst = dyn_cast<Instruction>(RI);
00690     if (FPInst && isa<FPMathOperator>(FPInst))
00691       FPInst->copyFastMathFlags(BO);
00692     return RI;
00693   }
00694   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
00695     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
00696                                    SO->getName()+".cmp");
00697   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
00698     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
00699                                    SO->getName()+".cmp");
00700   llvm_unreachable("Unknown binary instruction type!");
00701 }
00702 
00703 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
00704 // constant as the other operand, try to fold the binary operator into the
00705 // select arguments.  This also works for Cast instructions, which obviously do
00706 // not have a second operand.
00707 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
00708   // Don't modify shared select instructions
00709   if (!SI->hasOneUse()) return nullptr;
00710   Value *TV = SI->getOperand(1);
00711   Value *FV = SI->getOperand(2);
00712 
00713   if (isa<Constant>(TV) || isa<Constant>(FV)) {
00714     // Bool selects with constant operands can be folded to logical ops.
00715     if (SI->getType()->isIntegerTy(1)) return nullptr;
00716 
00717     // If it's a bitcast involving vectors, make sure it has the same number of
00718     // elements on both sides.
00719     if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
00720       VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
00721       VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
00722 
00723       // Verify that either both or neither are vectors.
00724       if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
00725       // If vectors, verify that they have the same number of elements.
00726       if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
00727         return nullptr;
00728     }
00729 
00730     // Test if a CmpInst instruction is used exclusively by a select as
00731     // part of a minimum or maximum operation. If so, refrain from doing
00732     // any other folding. This helps out other analyses which understand
00733     // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
00734     // and CodeGen. And in this case, at least one of the comparison
00735     // operands has at least one user besides the compare (the select),
00736     // which would often largely negate the benefit of folding anyway.
00737     if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
00738       if (CI->hasOneUse()) {
00739         Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
00740         if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
00741             (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
00742           return nullptr;
00743       }
00744     }
00745 
00746     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
00747     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
00748 
00749     return SelectInst::Create(SI->getCondition(),
00750                               SelectTrueVal, SelectFalseVal);
00751   }
00752   return nullptr;
00753 }
00754 
00755 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
00756 /// has a PHI node as operand #0, see if we can fold the instruction into the
00757 /// PHI (which is only possible if all operands to the PHI are constants).
00758 ///
00759 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
00760   PHINode *PN = cast<PHINode>(I.getOperand(0));
00761   unsigned NumPHIValues = PN->getNumIncomingValues();
00762   if (NumPHIValues == 0)
00763     return nullptr;
00764 
00765   // We normally only transform phis with a single use.  However, if a PHI has
00766   // multiple uses and they are all the same operation, we can fold *all* of the
00767   // uses into the PHI.
00768   if (!PN->hasOneUse()) {
00769     // Walk the use list for the instruction, comparing them to I.
00770     for (User *U : PN->users()) {
00771       Instruction *UI = cast<Instruction>(U);
00772       if (UI != &I && !I.isIdenticalTo(UI))
00773         return nullptr;
00774     }
00775     // Otherwise, we can replace *all* users with the new PHI we form.
00776   }
00777 
00778   // Check to see if all of the operands of the PHI are simple constants
00779   // (constantint/constantfp/undef).  If there is one non-constant value,
00780   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
00781   // bail out.  We don't do arbitrary constant expressions here because moving
00782   // their computation can be expensive without a cost model.
00783   BasicBlock *NonConstBB = nullptr;
00784   for (unsigned i = 0; i != NumPHIValues; ++i) {
00785     Value *InVal = PN->getIncomingValue(i);
00786     if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
00787       continue;
00788 
00789     if (isa<PHINode>(InVal)) return nullptr;  // Itself a phi.
00790     if (NonConstBB) return nullptr;  // More than one non-const value.
00791 
00792     NonConstBB = PN->getIncomingBlock(i);
00793 
00794     // If the InVal is an invoke at the end of the pred block, then we can't
00795     // insert a computation after it without breaking the edge.
00796     if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
00797       if (II->getParent() == NonConstBB)
00798         return nullptr;
00799 
00800     // If the incoming non-constant value is in I's block, we will remove one
00801     // instruction, but insert another equivalent one, leading to infinite
00802     // instcombine.
00803     if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
00804       return nullptr;
00805   }
00806 
00807   // If there is exactly one non-constant value, we can insert a copy of the
00808   // operation in that block.  However, if this is a critical edge, we would be
00809   // inserting the computation on some other paths (e.g. inside a loop).  Only
00810   // do this if the pred block is unconditionally branching into the phi block.
00811   if (NonConstBB != nullptr) {
00812     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
00813     if (!BI || !BI->isUnconditional()) return nullptr;
00814   }
00815 
00816   // Okay, we can do the transformation: create the new PHI node.
00817   PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
00818   InsertNewInstBefore(NewPN, *PN);
00819   NewPN->takeName(PN);
00820 
00821   // If we are going to have to insert a new computation, do so right before the
00822   // predecessors terminator.
00823   if (NonConstBB)
00824     Builder->SetInsertPoint(NonConstBB->getTerminator());
00825 
00826   // Next, add all of the operands to the PHI.
00827   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
00828     // We only currently try to fold the condition of a select when it is a phi,
00829     // not the true/false values.
00830     Value *TrueV = SI->getTrueValue();
00831     Value *FalseV = SI->getFalseValue();
00832     BasicBlock *PhiTransBB = PN->getParent();
00833     for (unsigned i = 0; i != NumPHIValues; ++i) {
00834       BasicBlock *ThisBB = PN->getIncomingBlock(i);
00835       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
00836       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
00837       Value *InV = nullptr;
00838       // Beware of ConstantExpr:  it may eventually evaluate to getNullValue,
00839       // even if currently isNullValue gives false.
00840       Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
00841       if (InC && !isa<ConstantExpr>(InC))
00842         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
00843       else
00844         InV = Builder->CreateSelect(PN->getIncomingValue(i),
00845                                     TrueVInPred, FalseVInPred, "phitmp");
00846       NewPN->addIncoming(InV, ThisBB);
00847     }
00848   } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
00849     Constant *C = cast<Constant>(I.getOperand(1));
00850     for (unsigned i = 0; i != NumPHIValues; ++i) {
00851       Value *InV = nullptr;
00852       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
00853         InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
00854       else if (isa<ICmpInst>(CI))
00855         InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
00856                                   C, "phitmp");
00857       else
00858         InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
00859                                   C, "phitmp");
00860       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
00861     }
00862   } else if (I.getNumOperands() == 2) {
00863     Constant *C = cast<Constant>(I.getOperand(1));
00864     for (unsigned i = 0; i != NumPHIValues; ++i) {
00865       Value *InV = nullptr;
00866       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
00867         InV = ConstantExpr::get(I.getOpcode(), InC, C);
00868       else
00869         InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
00870                                    PN->getIncomingValue(i), C, "phitmp");
00871       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
00872     }
00873   } else {
00874     CastInst *CI = cast<CastInst>(&I);
00875     Type *RetTy = CI->getType();
00876     for (unsigned i = 0; i != NumPHIValues; ++i) {
00877       Value *InV;
00878       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
00879         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
00880       else
00881         InV = Builder->CreateCast(CI->getOpcode(),
00882                                 PN->getIncomingValue(i), I.getType(), "phitmp");
00883       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
00884     }
00885   }
00886 
00887   for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
00888     Instruction *User = cast<Instruction>(*UI++);
00889     if (User == &I) continue;
00890     ReplaceInstUsesWith(*User, NewPN);
00891     EraseInstFromFunction(*User);
00892   }
00893   return ReplaceInstUsesWith(I, NewPN);
00894 }
00895 
00896 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
00897 /// whether or not there is a sequence of GEP indices into the pointed type that
00898 /// will land us at the specified offset.  If so, fill them into NewIndices and
00899 /// return the resultant element type, otherwise return null.
00900 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
00901                                         SmallVectorImpl<Value *> &NewIndices) {
00902   Type *Ty = PtrTy->getElementType();
00903   if (!Ty->isSized())
00904     return nullptr;
00905 
00906   // Start with the index over the outer type.  Note that the type size
00907   // might be zero (even if the offset isn't zero) if the indexed type
00908   // is something like [0 x {int, int}]
00909   Type *IntPtrTy = DL.getIntPtrType(PtrTy);
00910   int64_t FirstIdx = 0;
00911   if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
00912     FirstIdx = Offset/TySize;
00913     Offset -= FirstIdx*TySize;
00914 
00915     // Handle hosts where % returns negative instead of values [0..TySize).
00916     if (Offset < 0) {
00917       --FirstIdx;
00918       Offset += TySize;
00919       assert(Offset >= 0);
00920     }
00921     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
00922   }
00923 
00924   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
00925 
00926   // Index into the types.  If we fail, set OrigBase to null.
00927   while (Offset) {
00928     // Indexing into tail padding between struct/array elements.
00929     if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
00930       return nullptr;
00931 
00932     if (StructType *STy = dyn_cast<StructType>(Ty)) {
00933       const StructLayout *SL = DL.getStructLayout(STy);
00934       assert(Offset < (int64_t)SL->getSizeInBytes() &&
00935              "Offset must stay within the indexed type");
00936 
00937       unsigned Elt = SL->getElementContainingOffset(Offset);
00938       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
00939                                             Elt));
00940 
00941       Offset -= SL->getElementOffset(Elt);
00942       Ty = STy->getElementType(Elt);
00943     } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
00944       uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
00945       assert(EltSize && "Cannot index into a zero-sized array");
00946       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
00947       Offset %= EltSize;
00948       Ty = AT->getElementType();
00949     } else {
00950       // Otherwise, we can't index into the middle of this atomic type, bail.
00951       return nullptr;
00952     }
00953   }
00954 
00955   return Ty;
00956 }
00957 
00958 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
00959   // If this GEP has only 0 indices, it is the same pointer as
00960   // Src. If Src is not a trivial GEP too, don't combine
00961   // the indices.
00962   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
00963       !Src.hasOneUse())
00964     return false;
00965   return true;
00966 }
00967 
00968 /// Descale - Return a value X such that Val = X * Scale, or null if none.  If
00969 /// the multiplication is known not to overflow then NoSignedWrap is set.
00970 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
00971   assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
00972   assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
00973          Scale.getBitWidth() && "Scale not compatible with value!");
00974 
00975   // If Val is zero or Scale is one then Val = Val * Scale.
00976   if (match(Val, m_Zero()) || Scale == 1) {
00977     NoSignedWrap = true;
00978     return Val;
00979   }
00980 
00981   // If Scale is zero then it does not divide Val.
00982   if (Scale.isMinValue())
00983     return nullptr;
00984 
00985   // Look through chains of multiplications, searching for a constant that is
00986   // divisible by Scale.  For example, descaling X*(Y*(Z*4)) by a factor of 4
00987   // will find the constant factor 4 and produce X*(Y*Z).  Descaling X*(Y*8) by
00988   // a factor of 4 will produce X*(Y*2).  The principle of operation is to bore
00989   // down from Val:
00990   //
00991   //     Val = M1 * X          ||   Analysis starts here and works down
00992   //      M1 = M2 * Y          ||   Doesn't descend into terms with more
00993   //      M2 =  Z * 4          \/   than one use
00994   //
00995   // Then to modify a term at the bottom:
00996   //
00997   //     Val = M1 * X
00998   //      M1 =  Z * Y          ||   Replaced M2 with Z
00999   //
01000   // Then to work back up correcting nsw flags.
01001 
01002   // Op - the term we are currently analyzing.  Starts at Val then drills down.
01003   // Replaced with its descaled value before exiting from the drill down loop.
01004   Value *Op = Val;
01005 
01006   // Parent - initially null, but after drilling down notes where Op came from.
01007   // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
01008   // 0'th operand of Val.
01009   std::pair<Instruction*, unsigned> Parent;
01010 
01011   // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
01012   // levels that doesn't overflow.
01013   bool RequireNoSignedWrap = false;
01014 
01015   // logScale - log base 2 of the scale.  Negative if not a power of 2.
01016   int32_t logScale = Scale.exactLogBase2();
01017 
01018   for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
01019 
01020     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
01021       // If Op is a constant divisible by Scale then descale to the quotient.
01022       APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
01023       APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
01024       if (!Remainder.isMinValue())
01025         // Not divisible by Scale.
01026         return nullptr;
01027       // Replace with the quotient in the parent.
01028       Op = ConstantInt::get(CI->getType(), Quotient);
01029       NoSignedWrap = true;
01030       break;
01031     }
01032 
01033     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
01034 
01035       if (BO->getOpcode() == Instruction::Mul) {
01036         // Multiplication.
01037         NoSignedWrap = BO->hasNoSignedWrap();
01038         if (RequireNoSignedWrap && !NoSignedWrap)
01039           return nullptr;
01040 
01041         // There are three cases for multiplication: multiplication by exactly
01042         // the scale, multiplication by a constant different to the scale, and
01043         // multiplication by something else.
01044         Value *LHS = BO->getOperand(0);
01045         Value *RHS = BO->getOperand(1);
01046 
01047         if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
01048           // Multiplication by a constant.
01049           if (CI->getValue() == Scale) {
01050             // Multiplication by exactly the scale, replace the multiplication
01051             // by its left-hand side in the parent.
01052             Op = LHS;
01053             break;
01054           }
01055 
01056           // Otherwise drill down into the constant.
01057           if (!Op->hasOneUse())
01058             return nullptr;
01059 
01060           Parent = std::make_pair(BO, 1);
01061           continue;
01062         }
01063 
01064         // Multiplication by something else. Drill down into the left-hand side
01065         // since that's where the reassociate pass puts the good stuff.
01066         if (!Op->hasOneUse())
01067           return nullptr;
01068 
01069         Parent = std::make_pair(BO, 0);
01070         continue;
01071       }
01072 
01073       if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
01074           isa<ConstantInt>(BO->getOperand(1))) {
01075         // Multiplication by a power of 2.
01076         NoSignedWrap = BO->hasNoSignedWrap();
01077         if (RequireNoSignedWrap && !NoSignedWrap)
01078           return nullptr;
01079 
01080         Value *LHS = BO->getOperand(0);
01081         int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
01082           getLimitedValue(Scale.getBitWidth());
01083         // Op = LHS << Amt.
01084 
01085         if (Amt == logScale) {
01086           // Multiplication by exactly the scale, replace the multiplication
01087           // by its left-hand side in the parent.
01088           Op = LHS;
01089           break;
01090         }
01091         if (Amt < logScale || !Op->hasOneUse())
01092           return nullptr;
01093 
01094         // Multiplication by more than the scale.  Reduce the multiplying amount
01095         // by the scale in the parent.
01096         Parent = std::make_pair(BO, 1);
01097         Op = ConstantInt::get(BO->getType(), Amt - logScale);
01098         break;
01099       }
01100     }
01101 
01102     if (!Op->hasOneUse())
01103       return nullptr;
01104 
01105     if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
01106       if (Cast->getOpcode() == Instruction::SExt) {
01107         // Op is sign-extended from a smaller type, descale in the smaller type.
01108         unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
01109         APInt SmallScale = Scale.trunc(SmallSize);
01110         // Suppose Op = sext X, and we descale X as Y * SmallScale.  We want to
01111         // descale Op as (sext Y) * Scale.  In order to have
01112         //   sext (Y * SmallScale) = (sext Y) * Scale
01113         // some conditions need to hold however: SmallScale must sign-extend to
01114         // Scale and the multiplication Y * SmallScale should not overflow.
01115         if (SmallScale.sext(Scale.getBitWidth()) != Scale)
01116           // SmallScale does not sign-extend to Scale.
01117           return nullptr;
01118         assert(SmallScale.exactLogBase2() == logScale);
01119         // Require that Y * SmallScale must not overflow.
01120         RequireNoSignedWrap = true;
01121 
01122         // Drill down through the cast.
01123         Parent = std::make_pair(Cast, 0);
01124         Scale = SmallScale;
01125         continue;
01126       }
01127 
01128       if (Cast->getOpcode() == Instruction::Trunc) {
01129         // Op is truncated from a larger type, descale in the larger type.
01130         // Suppose Op = trunc X, and we descale X as Y * sext Scale.  Then
01131         //   trunc (Y * sext Scale) = (trunc Y) * Scale
01132         // always holds.  However (trunc Y) * Scale may overflow even if
01133         // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
01134         // from this point up in the expression (see later).
01135         if (RequireNoSignedWrap)
01136           return nullptr;
01137 
01138         // Drill down through the cast.
01139         unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
01140         Parent = std::make_pair(Cast, 0);
01141         Scale = Scale.sext(LargeSize);
01142         if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
01143           logScale = -1;
01144         assert(Scale.exactLogBase2() == logScale);
01145         continue;
01146       }
01147     }
01148 
01149     // Unsupported expression, bail out.
01150     return nullptr;
01151   }
01152 
01153   // If Op is zero then Val = Op * Scale.
01154   if (match(Op, m_Zero())) {
01155     NoSignedWrap = true;
01156     return Op;
01157   }
01158 
01159   // We know that we can successfully descale, so from here on we can safely
01160   // modify the IR.  Op holds the descaled version of the deepest term in the
01161   // expression.  NoSignedWrap is 'true' if multiplying Op by Scale is known
01162   // not to overflow.
01163 
01164   if (!Parent.first)
01165     // The expression only had one term.
01166     return Op;
01167 
01168   // Rewrite the parent using the descaled version of its operand.
01169   assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
01170   assert(Op != Parent.first->getOperand(Parent.second) &&
01171          "Descaling was a no-op?");
01172   Parent.first->setOperand(Parent.second, Op);
01173   Worklist.Add(Parent.first);
01174 
01175   // Now work back up the expression correcting nsw flags.  The logic is based
01176   // on the following observation: if X * Y is known not to overflow as a signed
01177   // multiplication, and Y is replaced by a value Z with smaller absolute value,
01178   // then X * Z will not overflow as a signed multiplication either.  As we work
01179   // our way up, having NoSignedWrap 'true' means that the descaled value at the
01180   // current level has strictly smaller absolute value than the original.
01181   Instruction *Ancestor = Parent.first;
01182   do {
01183     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
01184       // If the multiplication wasn't nsw then we can't say anything about the
01185       // value of the descaled multiplication, and we have to clear nsw flags
01186       // from this point on up.
01187       bool OpNoSignedWrap = BO->hasNoSignedWrap();
01188       NoSignedWrap &= OpNoSignedWrap;
01189       if (NoSignedWrap != OpNoSignedWrap) {
01190         BO->setHasNoSignedWrap(NoSignedWrap);
01191         Worklist.Add(Ancestor);
01192       }
01193     } else if (Ancestor->getOpcode() == Instruction::Trunc) {
01194       // The fact that the descaled input to the trunc has smaller absolute
01195       // value than the original input doesn't tell us anything useful about
01196       // the absolute values of the truncations.
01197       NoSignedWrap = false;
01198     }
01199     assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
01200            "Failed to keep proper track of nsw flags while drilling down?");
01201 
01202     if (Ancestor == Val)
01203       // Got to the top, all done!
01204       return Val;
01205 
01206     // Move up one level in the expression.
01207     assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
01208     Ancestor = Ancestor->user_back();
01209   } while (1);
01210 }
01211 
01212 /// \brief Creates node of binary operation with the same attributes as the
01213 /// specified one but with other operands.
01214 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
01215                                  InstCombiner::BuilderTy *B) {
01216   Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
01217   if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
01218     if (isa<OverflowingBinaryOperator>(NewBO)) {
01219       NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
01220       NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
01221     }
01222     if (isa<PossiblyExactOperator>(NewBO))
01223       NewBO->setIsExact(Inst.isExact());
01224   }
01225   return BORes;
01226 }
01227 
01228 /// \brief Makes transformation of binary operation specific for vector types.
01229 /// \param Inst Binary operator to transform.
01230 /// \return Pointer to node that must replace the original binary operator, or
01231 ///         null pointer if no transformation was made.
01232 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
01233   if (!Inst.getType()->isVectorTy()) return nullptr;
01234 
01235   // It may not be safe to reorder shuffles and things like div, urem, etc.
01236   // because we may trap when executing those ops on unknown vector elements.
01237   // See PR20059.
01238   if (!isSafeToSpeculativelyExecute(&Inst))
01239     return nullptr;
01240 
01241   unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
01242   Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
01243   assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
01244   assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
01245 
01246   // If both arguments of binary operation are shuffles, which use the same
01247   // mask and shuffle within a single vector, it is worthwhile to move the
01248   // shuffle after binary operation:
01249   //   Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
01250   if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
01251     ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
01252     ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
01253     if (isa<UndefValue>(LShuf->getOperand(1)) &&
01254         isa<UndefValue>(RShuf->getOperand(1)) &&
01255         LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
01256         LShuf->getMask() == RShuf->getMask()) {
01257       Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
01258           RShuf->getOperand(0), Builder);
01259       Value *Res = Builder->CreateShuffleVector(NewBO,
01260           UndefValue::get(NewBO->getType()), LShuf->getMask());
01261       return Res;
01262     }
01263   }
01264 
01265   // If one argument is a shuffle within one vector, the other is a constant,
01266   // try moving the shuffle after the binary operation.
01267   ShuffleVectorInst *Shuffle = nullptr;
01268   Constant *C1 = nullptr;
01269   if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
01270   if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
01271   if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
01272   if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
01273   if (Shuffle && C1 &&
01274       (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
01275       isa<UndefValue>(Shuffle->getOperand(1)) &&
01276       Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
01277     SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
01278     // Find constant C2 that has property:
01279     //   shuffle(C2, ShMask) = C1
01280     // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
01281     // reorder is not possible.
01282     SmallVector<Constant*, 16> C2M(VWidth,
01283                                UndefValue::get(C1->getType()->getScalarType()));
01284     bool MayChange = true;
01285     for (unsigned I = 0; I < VWidth; ++I) {
01286       if (ShMask[I] >= 0) {
01287         assert(ShMask[I] < (int)VWidth);
01288         if (!isa<UndefValue>(C2M[ShMask[I]])) {
01289           MayChange = false;
01290           break;
01291         }
01292         C2M[ShMask[I]] = C1->getAggregateElement(I);
01293       }
01294     }
01295     if (MayChange) {
01296       Constant *C2 = ConstantVector::get(C2M);
01297       Value *NewLHS, *NewRHS;
01298       if (isa<Constant>(LHS)) {
01299         NewLHS = C2;
01300         NewRHS = Shuffle->getOperand(0);
01301       } else {
01302         NewLHS = Shuffle->getOperand(0);
01303         NewRHS = C2;
01304       }
01305       Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
01306       Value *Res = Builder->CreateShuffleVector(NewBO,
01307           UndefValue::get(Inst.getType()), Shuffle->getMask());
01308       return Res;
01309     }
01310   }
01311 
01312   return nullptr;
01313 }
01314 
01315 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
01316   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
01317 
01318   if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
01319     return ReplaceInstUsesWith(GEP, V);
01320 
01321   Value *PtrOp = GEP.getOperand(0);
01322 
01323   // Eliminate unneeded casts for indices, and replace indices which displace
01324   // by multiples of a zero size type with zero.
01325   bool MadeChange = false;
01326   Type *IntPtrTy = DL.getIntPtrType(GEP.getPointerOperandType());
01327 
01328   gep_type_iterator GTI = gep_type_begin(GEP);
01329   for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
01330        ++I, ++GTI) {
01331     // Skip indices into struct types.
01332     SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
01333     if (!SeqTy)
01334       continue;
01335 
01336     // If the element type has zero size then any index over it is equivalent
01337     // to an index of zero, so replace it with zero if it is not zero already.
01338     if (SeqTy->getElementType()->isSized() &&
01339         DL.getTypeAllocSize(SeqTy->getElementType()) == 0)
01340       if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
01341         *I = Constant::getNullValue(IntPtrTy);
01342         MadeChange = true;
01343       }
01344 
01345     Type *IndexTy = (*I)->getType();
01346     if (IndexTy != IntPtrTy) {
01347       // If we are using a wider index than needed for this platform, shrink
01348       // it to what we need.  If narrower, sign-extend it to what we need.
01349       // This explicit cast can make subsequent optimizations more obvious.
01350       *I = Builder->CreateIntCast(*I, IntPtrTy, true);
01351       MadeChange = true;
01352     }
01353   }
01354   if (MadeChange)
01355     return &GEP;
01356 
01357   // Check to see if the inputs to the PHI node are getelementptr instructions.
01358   if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
01359     GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
01360     if (!Op1)
01361       return nullptr;
01362 
01363     // Don't fold a GEP into itself through a PHI node. This can only happen
01364     // through the back-edge of a loop. Folding a GEP into itself means that
01365     // the value of the previous iteration needs to be stored in the meantime,
01366     // thus requiring an additional register variable to be live, but not
01367     // actually achieving anything (the GEP still needs to be executed once per
01368     // loop iteration).
01369     if (Op1 == &GEP)
01370       return nullptr;
01371 
01372     signed DI = -1;
01373 
01374     for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
01375       GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
01376       if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
01377         return nullptr;
01378 
01379       // As for Op1 above, don't try to fold a GEP into itself.
01380       if (Op2 == &GEP)
01381         return nullptr;
01382 
01383       // Keep track of the type as we walk the GEP.
01384       Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
01385 
01386       for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
01387         if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
01388           return nullptr;
01389 
01390         if (Op1->getOperand(J) != Op2->getOperand(J)) {
01391           if (DI == -1) {
01392             // We have not seen any differences yet in the GEPs feeding the
01393             // PHI yet, so we record this one if it is allowed to be a
01394             // variable.
01395 
01396             // The first two arguments can vary for any GEP, the rest have to be
01397             // static for struct slots
01398             if (J > 1 && CurTy->isStructTy())
01399               return nullptr;
01400 
01401             DI = J;
01402           } else {
01403             // The GEP is different by more than one input. While this could be
01404             // extended to support GEPs that vary by more than one variable it
01405             // doesn't make sense since it greatly increases the complexity and
01406             // would result in an R+R+R addressing mode which no backend
01407             // directly supports and would need to be broken into several
01408             // simpler instructions anyway.
01409             return nullptr;
01410           }
01411         }
01412 
01413         // Sink down a layer of the type for the next iteration.
01414         if (J > 0) {
01415           if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
01416             CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
01417           } else {
01418             CurTy = nullptr;
01419           }
01420         }
01421       }
01422     }
01423 
01424     GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
01425 
01426     if (DI == -1) {
01427       // All the GEPs feeding the PHI are identical. Clone one down into our
01428       // BB so that it can be merged with the current GEP.
01429       GEP.getParent()->getInstList().insert(
01430           GEP.getParent()->getFirstInsertionPt(), NewGEP);
01431     } else {
01432       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
01433       // into the current block so it can be merged, and create a new PHI to
01434       // set that index.
01435       Instruction *InsertPt = Builder->GetInsertPoint();
01436       Builder->SetInsertPoint(PN);
01437       PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
01438                                           PN->getNumOperands());
01439       Builder->SetInsertPoint(InsertPt);
01440 
01441       for (auto &I : PN->operands())
01442         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
01443                            PN->getIncomingBlock(I));
01444 
01445       NewGEP->setOperand(DI, NewPN);
01446       GEP.getParent()->getInstList().insert(
01447           GEP.getParent()->getFirstInsertionPt(), NewGEP);
01448       NewGEP->setOperand(DI, NewPN);
01449     }
01450 
01451     GEP.setOperand(0, NewGEP);
01452     PtrOp = NewGEP;
01453   }
01454 
01455   // Combine Indices - If the source pointer to this getelementptr instruction
01456   // is a getelementptr instruction, combine the indices of the two
01457   // getelementptr instructions into a single instruction.
01458   //
01459   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
01460     if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
01461       return nullptr;
01462 
01463     // Note that if our source is a gep chain itself then we wait for that
01464     // chain to be resolved before we perform this transformation.  This
01465     // avoids us creating a TON of code in some cases.
01466     if (GEPOperator *SrcGEP =
01467           dyn_cast<GEPOperator>(Src->getOperand(0)))
01468       if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
01469         return nullptr;   // Wait until our source is folded to completion.
01470 
01471     SmallVector<Value*, 8> Indices;
01472 
01473     // Find out whether the last index in the source GEP is a sequential idx.
01474     bool EndsWithSequential = false;
01475     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
01476          I != E; ++I)
01477       EndsWithSequential = !(*I)->isStructTy();
01478 
01479     // Can we combine the two pointer arithmetics offsets?
01480     if (EndsWithSequential) {
01481       // Replace: gep (gep %P, long B), long A, ...
01482       // With:    T = long A+B; gep %P, T, ...
01483       //
01484       Value *Sum;
01485       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
01486       Value *GO1 = GEP.getOperand(1);
01487       if (SO1 == Constant::getNullValue(SO1->getType())) {
01488         Sum = GO1;
01489       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
01490         Sum = SO1;
01491       } else {
01492         // If they aren't the same type, then the input hasn't been processed
01493         // by the loop above yet (which canonicalizes sequential index types to
01494         // intptr_t).  Just avoid transforming this until the input has been
01495         // normalized.
01496         if (SO1->getType() != GO1->getType())
01497           return nullptr;
01498         // Only do the combine when GO1 and SO1 are both constants. Only in
01499         // this case, we are sure the cost after the merge is never more than
01500         // that before the merge.
01501         if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
01502           return nullptr;
01503         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
01504       }
01505 
01506       // Update the GEP in place if possible.
01507       if (Src->getNumOperands() == 2) {
01508         GEP.setOperand(0, Src->getOperand(0));
01509         GEP.setOperand(1, Sum);
01510         return &GEP;
01511       }
01512       Indices.append(Src->op_begin()+1, Src->op_end()-1);
01513       Indices.push_back(Sum);
01514       Indices.append(GEP.op_begin()+2, GEP.op_end());
01515     } else if (isa<Constant>(*GEP.idx_begin()) &&
01516                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
01517                Src->getNumOperands() != 1) {
01518       // Otherwise we can do the fold if the first index of the GEP is a zero
01519       Indices.append(Src->op_begin()+1, Src->op_end());
01520       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
01521     }
01522 
01523     if (!Indices.empty())
01524       return GEP.isInBounds() && Src->isInBounds()
01525                  ? GetElementPtrInst::CreateInBounds(
01526                        Src->getSourceElementType(), Src->getOperand(0), Indices,
01527                        GEP.getName())
01528                  : GetElementPtrInst::Create(Src->getSourceElementType(),
01529                                              Src->getOperand(0), Indices,
01530                                              GEP.getName());
01531   }
01532 
01533   if (GEP.getNumIndices() == 1) {
01534     unsigned AS = GEP.getPointerAddressSpace();
01535     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
01536         DL.getPointerSizeInBits(AS)) {
01537       Type *PtrTy = GEP.getPointerOperandType();
01538       Type *Ty = PtrTy->getPointerElementType();
01539       uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
01540 
01541       bool Matched = false;
01542       uint64_t C;
01543       Value *V = nullptr;
01544       if (TyAllocSize == 1) {
01545         V = GEP.getOperand(1);
01546         Matched = true;
01547       } else if (match(GEP.getOperand(1),
01548                        m_AShr(m_Value(V), m_ConstantInt(C)))) {
01549         if (TyAllocSize == 1ULL << C)
01550           Matched = true;
01551       } else if (match(GEP.getOperand(1),
01552                        m_SDiv(m_Value(V), m_ConstantInt(C)))) {
01553         if (TyAllocSize == C)
01554           Matched = true;
01555       }
01556 
01557       if (Matched) {
01558         // Canonicalize (gep i8* X, -(ptrtoint Y))
01559         // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
01560         // The GEP pattern is emitted by the SCEV expander for certain kinds of
01561         // pointer arithmetic.
01562         if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
01563           Operator *Index = cast<Operator>(V);
01564           Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
01565           Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
01566           return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
01567         }
01568         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
01569         // to (bitcast Y)
01570         Value *Y;
01571         if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
01572                            m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
01573           return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
01574                                                                GEP.getType());
01575         }
01576       }
01577     }
01578   }
01579 
01580   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
01581   Value *StrippedPtr = PtrOp->stripPointerCasts();
01582   PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
01583 
01584   // We do not handle pointer-vector geps here.
01585   if (!StrippedPtrTy)
01586     return nullptr;
01587 
01588   if (StrippedPtr != PtrOp) {
01589     bool HasZeroPointerIndex = false;
01590     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
01591       HasZeroPointerIndex = C->isZero();
01592 
01593     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
01594     // into     : GEP [10 x i8]* X, i32 0, ...
01595     //
01596     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
01597     //           into     : GEP i8* X, ...
01598     //
01599     // This occurs when the program declares an array extern like "int X[];"
01600     if (HasZeroPointerIndex) {
01601       PointerType *CPTy = cast<PointerType>(PtrOp->getType());
01602       if (ArrayType *CATy =
01603           dyn_cast<ArrayType>(CPTy->getElementType())) {
01604         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
01605         if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
01606           // -> GEP i8* X, ...
01607           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
01608           GetElementPtrInst *Res = GetElementPtrInst::Create(
01609               StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
01610           Res->setIsInBounds(GEP.isInBounds());
01611           if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
01612             return Res;
01613           // Insert Res, and create an addrspacecast.
01614           // e.g.,
01615           // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
01616           // ->
01617           // %0 = GEP i8 addrspace(1)* X, ...
01618           // addrspacecast i8 addrspace(1)* %0 to i8*
01619           return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
01620         }
01621 
01622         if (ArrayType *XATy =
01623               dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
01624           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
01625           if (CATy->getElementType() == XATy->getElementType()) {
01626             // -> GEP [10 x i8]* X, i32 0, ...
01627             // At this point, we know that the cast source type is a pointer
01628             // to an array of the same type as the destination pointer
01629             // array.  Because the array type is never stepped over (there
01630             // is a leading zero) we can fold the cast into this GEP.
01631             if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
01632               GEP.setOperand(0, StrippedPtr);
01633               GEP.setSourceElementType(XATy);
01634               return &GEP;
01635             }
01636             // Cannot replace the base pointer directly because StrippedPtr's
01637             // address space is different. Instead, create a new GEP followed by
01638             // an addrspacecast.
01639             // e.g.,
01640             // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
01641             //   i32 0, ...
01642             // ->
01643             // %0 = GEP [10 x i8] addrspace(1)* X, ...
01644             // addrspacecast i8 addrspace(1)* %0 to i8*
01645             SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
01646             Value *NewGEP = GEP.isInBounds()
01647                                 ? Builder->CreateInBoundsGEP(
01648                                       nullptr, StrippedPtr, Idx, GEP.getName())
01649                                 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
01650                                                      GEP.getName());
01651             return new AddrSpaceCastInst(NewGEP, GEP.getType());
01652           }
01653         }
01654       }
01655     } else if (GEP.getNumOperands() == 2) {
01656       // Transform things like:
01657       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
01658       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
01659       Type *SrcElTy = StrippedPtrTy->getElementType();
01660       Type *ResElTy = PtrOp->getType()->getPointerElementType();
01661       if (SrcElTy->isArrayTy() &&
01662           DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
01663               DL.getTypeAllocSize(ResElTy)) {
01664         Type *IdxType = DL.getIntPtrType(GEP.getType());
01665         Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
01666         Value *NewGEP =
01667             GEP.isInBounds()
01668                 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
01669                                              GEP.getName())
01670                 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
01671 
01672         // V and GEP are both pointer types --> BitCast
01673         return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
01674                                                              GEP.getType());
01675       }
01676 
01677       // Transform things like:
01678       // %V = mul i64 %N, 4
01679       // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
01680       // into:  %t1 = getelementptr i32* %arr, i32 %N; bitcast
01681       if (ResElTy->isSized() && SrcElTy->isSized()) {
01682         // Check that changing the type amounts to dividing the index by a scale
01683         // factor.
01684         uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
01685         uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
01686         if (ResSize && SrcSize % ResSize == 0) {
01687           Value *Idx = GEP.getOperand(1);
01688           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
01689           uint64_t Scale = SrcSize / ResSize;
01690 
01691           // Earlier transforms ensure that the index has type IntPtrType, which
01692           // considerably simplifies the logic by eliminating implicit casts.
01693           assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
01694                  "Index not cast to pointer width?");
01695 
01696           bool NSW;
01697           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
01698             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
01699             // If the multiplication NewIdx * Scale may overflow then the new
01700             // GEP may not be "inbounds".
01701             Value *NewGEP =
01702                 GEP.isInBounds() && NSW
01703                     ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
01704                                                  GEP.getName())
01705                     : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
01706                                          GEP.getName());
01707 
01708             // The NewGEP must be pointer typed, so must the old one -> BitCast
01709             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
01710                                                                  GEP.getType());
01711           }
01712         }
01713       }
01714 
01715       // Similarly, transform things like:
01716       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
01717       //   (where tmp = 8*tmp2) into:
01718       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
01719       if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
01720         // Check that changing to the array element type amounts to dividing the
01721         // index by a scale factor.
01722         uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
01723         uint64_t ArrayEltSize =
01724             DL.getTypeAllocSize(SrcElTy->getArrayElementType());
01725         if (ResSize && ArrayEltSize % ResSize == 0) {
01726           Value *Idx = GEP.getOperand(1);
01727           unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
01728           uint64_t Scale = ArrayEltSize / ResSize;
01729 
01730           // Earlier transforms ensure that the index has type IntPtrType, which
01731           // considerably simplifies the logic by eliminating implicit casts.
01732           assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
01733                  "Index not cast to pointer width?");
01734 
01735           bool NSW;
01736           if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
01737             // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
01738             // If the multiplication NewIdx * Scale may overflow then the new
01739             // GEP may not be "inbounds".
01740             Value *Off[2] = {
01741                 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
01742                 NewIdx};
01743 
01744             Value *NewGEP = GEP.isInBounds() && NSW
01745                                 ? Builder->CreateInBoundsGEP(
01746                                       SrcElTy, StrippedPtr, Off, GEP.getName())
01747                                 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
01748                                                      GEP.getName());
01749             // The NewGEP must be pointer typed, so must the old one -> BitCast
01750             return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
01751                                                                  GEP.getType());
01752           }
01753         }
01754       }
01755     }
01756   }
01757 
01758   // addrspacecast between types is canonicalized as a bitcast, then an
01759   // addrspacecast. To take advantage of the below bitcast + struct GEP, look
01760   // through the addrspacecast.
01761   if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
01762     //   X = bitcast A addrspace(1)* to B addrspace(1)*
01763     //   Y = addrspacecast A addrspace(1)* to B addrspace(2)*
01764     //   Z = gep Y, <...constant indices...>
01765     // Into an addrspacecasted GEP of the struct.
01766     if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
01767       PtrOp = BC;
01768   }
01769 
01770   /// See if we can simplify:
01771   ///   X = bitcast A* to B*
01772   ///   Y = gep X, <...constant indices...>
01773   /// into a gep of the original struct.  This is important for SROA and alias
01774   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
01775   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
01776     Value *Operand = BCI->getOperand(0);
01777     PointerType *OpType = cast<PointerType>(Operand->getType());
01778     unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
01779     APInt Offset(OffsetBits, 0);
01780     if (!isa<BitCastInst>(Operand) &&
01781         GEP.accumulateConstantOffset(DL, Offset)) {
01782 
01783       // If this GEP instruction doesn't move the pointer, just replace the GEP
01784       // with a bitcast of the real input to the dest type.
01785       if (!Offset) {
01786         // If the bitcast is of an allocation, and the allocation will be
01787         // converted to match the type of the cast, don't touch this.
01788         if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
01789           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
01790           if (Instruction *I = visitBitCast(*BCI)) {
01791             if (I != BCI) {
01792               I->takeName(BCI);
01793               BCI->getParent()->getInstList().insert(BCI, I);
01794               ReplaceInstUsesWith(*BCI, I);
01795             }
01796             return &GEP;
01797           }
01798         }
01799 
01800         if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
01801           return new AddrSpaceCastInst(Operand, GEP.getType());
01802         return new BitCastInst(Operand, GEP.getType());
01803       }
01804 
01805       // Otherwise, if the offset is non-zero, we need to find out if there is a
01806       // field at Offset in 'A's type.  If so, we can pull the cast through the
01807       // GEP.
01808       SmallVector<Value*, 8> NewIndices;
01809       if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
01810         Value *NGEP =
01811             GEP.isInBounds()
01812                 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
01813                 : Builder->CreateGEP(nullptr, Operand, NewIndices);
01814 
01815         if (NGEP->getType() == GEP.getType())
01816           return ReplaceInstUsesWith(GEP, NGEP);
01817         NGEP->takeName(&GEP);
01818 
01819         if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
01820           return new AddrSpaceCastInst(NGEP, GEP.getType());
01821         return new BitCastInst(NGEP, GEP.getType());
01822       }
01823     }
01824   }
01825 
01826   return nullptr;
01827 }
01828 
01829 static bool
01830 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
01831                      const TargetLibraryInfo *TLI) {
01832   SmallVector<Instruction*, 4> Worklist;
01833   Worklist.push_back(AI);
01834 
01835   do {
01836     Instruction *PI = Worklist.pop_back_val();
01837     for (User *U : PI->users()) {
01838       Instruction *I = cast<Instruction>(U);
01839       switch (I->getOpcode()) {
01840       default:
01841         // Give up the moment we see something we can't handle.
01842         return false;
01843 
01844       case Instruction::BitCast:
01845       case Instruction::GetElementPtr:
01846         Users.push_back(I);
01847         Worklist.push_back(I);
01848         continue;
01849 
01850       case Instruction::ICmp: {
01851         ICmpInst *ICI = cast<ICmpInst>(I);
01852         // We can fold eq/ne comparisons with null to false/true, respectively.
01853         if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
01854           return false;
01855         Users.push_back(I);
01856         continue;
01857       }
01858 
01859       case Instruction::Call:
01860         // Ignore no-op and store intrinsics.
01861         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01862           switch (II->getIntrinsicID()) {
01863           default:
01864             return false;
01865 
01866           case Intrinsic::memmove:
01867           case Intrinsic::memcpy:
01868           case Intrinsic::memset: {
01869             MemIntrinsic *MI = cast<MemIntrinsic>(II);
01870             if (MI->isVolatile() || MI->getRawDest() != PI)
01871               return false;
01872           }
01873           // fall through
01874           case Intrinsic::dbg_declare:
01875           case Intrinsic::dbg_value:
01876           case Intrinsic::invariant_start:
01877           case Intrinsic::invariant_end:
01878           case Intrinsic::lifetime_start:
01879           case Intrinsic::lifetime_end:
01880           case Intrinsic::objectsize:
01881             Users.push_back(I);
01882             continue;
01883           }
01884         }
01885 
01886         if (isFreeCall(I, TLI)) {
01887           Users.push_back(I);
01888           continue;
01889         }
01890         return false;
01891 
01892       case Instruction::Store: {
01893         StoreInst *SI = cast<StoreInst>(I);
01894         if (SI->isVolatile() || SI->getPointerOperand() != PI)
01895           return false;
01896         Users.push_back(I);
01897         continue;
01898       }
01899       }
01900       llvm_unreachable("missing a return?");
01901     }
01902   } while (!Worklist.empty());
01903   return true;
01904 }
01905 
01906 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
01907   // If we have a malloc call which is only used in any amount of comparisons
01908   // to null and free calls, delete the calls and replace the comparisons with
01909   // true or false as appropriate.
01910   SmallVector<WeakVH, 64> Users;
01911   if (isAllocSiteRemovable(&MI, Users, TLI)) {
01912     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
01913       Instruction *I = cast_or_null<Instruction>(&*Users[i]);
01914       if (!I) continue;
01915 
01916       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
01917         ReplaceInstUsesWith(*C,
01918                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
01919                                              C->isFalseWhenEqual()));
01920       } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
01921         ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
01922       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01923         if (II->getIntrinsicID() == Intrinsic::objectsize) {
01924           ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
01925           uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
01926           ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
01927         }
01928       }
01929       EraseInstFromFunction(*I);
01930     }
01931 
01932     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
01933       // Replace invoke with a NOP intrinsic to maintain the original CFG
01934       Module *M = II->getParent()->getParent()->getParent();
01935       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
01936       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
01937                          None, "", II->getParent());
01938     }
01939     return EraseInstFromFunction(MI);
01940   }
01941   return nullptr;
01942 }
01943 
01944 /// \brief Move the call to free before a NULL test.
01945 ///
01946 /// Check if this free is accessed after its argument has been test
01947 /// against NULL (property 0).
01948 /// If yes, it is legal to move this call in its predecessor block.
01949 ///
01950 /// The move is performed only if the block containing the call to free
01951 /// will be removed, i.e.:
01952 /// 1. it has only one predecessor P, and P has two successors
01953 /// 2. it contains the call and an unconditional branch
01954 /// 3. its successor is the same as its predecessor's successor
01955 ///
01956 /// The profitability is out-of concern here and this function should
01957 /// be called only if the caller knows this transformation would be
01958 /// profitable (e.g., for code size).
01959 static Instruction *
01960 tryToMoveFreeBeforeNullTest(CallInst &FI) {
01961   Value *Op = FI.getArgOperand(0);
01962   BasicBlock *FreeInstrBB = FI.getParent();
01963   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
01964 
01965   // Validate part of constraint #1: Only one predecessor
01966   // FIXME: We can extend the number of predecessor, but in that case, we
01967   //        would duplicate the call to free in each predecessor and it may
01968   //        not be profitable even for code size.
01969   if (!PredBB)
01970     return nullptr;
01971 
01972   // Validate constraint #2: Does this block contains only the call to
01973   //                         free and an unconditional branch?
01974   // FIXME: We could check if we can speculate everything in the
01975   //        predecessor block
01976   if (FreeInstrBB->size() != 2)
01977     return nullptr;
01978   BasicBlock *SuccBB;
01979   if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
01980     return nullptr;
01981 
01982   // Validate the rest of constraint #1 by matching on the pred branch.
01983   TerminatorInst *TI = PredBB->getTerminator();
01984   BasicBlock *TrueBB, *FalseBB;
01985   ICmpInst::Predicate Pred;
01986   if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
01987     return nullptr;
01988   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
01989     return nullptr;
01990 
01991   // Validate constraint #3: Ensure the null case just falls through.
01992   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
01993     return nullptr;
01994   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
01995          "Broken CFG: missing edge from predecessor to successor");
01996 
01997   FI.moveBefore(TI);
01998   return &FI;
01999 }
02000 
02001 
02002 Instruction *InstCombiner::visitFree(CallInst &FI) {
02003   Value *Op = FI.getArgOperand(0);
02004 
02005   // free undef -> unreachable.
02006   if (isa<UndefValue>(Op)) {
02007     // Insert a new store to null because we cannot modify the CFG here.
02008     Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
02009                          UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
02010     return EraseInstFromFunction(FI);
02011   }
02012 
02013   // If we have 'free null' delete the instruction.  This can happen in stl code
02014   // when lots of inlining happens.
02015   if (isa<ConstantPointerNull>(Op))
02016     return EraseInstFromFunction(FI);
02017 
02018   // If we optimize for code size, try to move the call to free before the null
02019   // test so that simplify cfg can remove the empty block and dead code
02020   // elimination the branch. I.e., helps to turn something like:
02021   // if (foo) free(foo);
02022   // into
02023   // free(foo);
02024   if (MinimizeSize)
02025     if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
02026       return I;
02027 
02028   return nullptr;
02029 }
02030 
02031 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
02032   if (RI.getNumOperands() == 0) // ret void
02033     return nullptr;
02034 
02035   Value *ResultOp = RI.getOperand(0);
02036   Type *VTy = ResultOp->getType();
02037   if (!VTy->isIntegerTy())
02038     return nullptr;
02039 
02040   // There might be assume intrinsics dominating this return that completely
02041   // determine the value. If so, constant fold it.
02042   unsigned BitWidth = VTy->getPrimitiveSizeInBits();
02043   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
02044   computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
02045   if ((KnownZero|KnownOne).isAllOnesValue())
02046     RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
02047 
02048   return nullptr;
02049 }
02050 
02051 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
02052   // Change br (not X), label True, label False to: br X, label False, True
02053   Value *X = nullptr;
02054   BasicBlock *TrueDest;
02055   BasicBlock *FalseDest;
02056   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
02057       !isa<Constant>(X)) {
02058     // Swap Destinations and condition...
02059     BI.setCondition(X);
02060     BI.swapSuccessors();
02061     return &BI;
02062   }
02063 
02064   // If the condition is irrelevant, remove the use so that other
02065   // transforms on the condition become more effective.
02066   if (BI.isConditional() &&
02067       BI.getSuccessor(0) == BI.getSuccessor(1) &&
02068       !isa<UndefValue>(BI.getCondition())) {
02069     BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
02070     return &BI;
02071   }
02072 
02073   // Canonicalize fcmp_one -> fcmp_oeq
02074   FCmpInst::Predicate FPred; Value *Y;
02075   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
02076                              TrueDest, FalseDest)) &&
02077       BI.getCondition()->hasOneUse())
02078     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
02079         FPred == FCmpInst::FCMP_OGE) {
02080       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
02081       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
02082 
02083       // Swap Destinations and condition.
02084       BI.swapSuccessors();
02085       Worklist.Add(Cond);
02086       return &BI;
02087     }
02088 
02089   // Canonicalize icmp_ne -> icmp_eq
02090   ICmpInst::Predicate IPred;
02091   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
02092                       TrueDest, FalseDest)) &&
02093       BI.getCondition()->hasOneUse())
02094     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
02095         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
02096         IPred == ICmpInst::ICMP_SGE) {
02097       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
02098       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
02099       // Swap Destinations and condition.
02100       BI.swapSuccessors();
02101       Worklist.Add(Cond);
02102       return &BI;
02103     }
02104 
02105   return nullptr;
02106 }
02107 
02108 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
02109   Value *Cond = SI.getCondition();
02110   unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
02111   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
02112   computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
02113   unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
02114   unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
02115 
02116   // Compute the number of leading bits we can ignore.
02117   for (auto &C : SI.cases()) {
02118     LeadingKnownZeros = std::min(
02119         LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
02120     LeadingKnownOnes = std::min(
02121         LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
02122   }
02123 
02124   unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
02125 
02126   // Truncate the condition operand if the new type is equal to or larger than
02127   // the largest legal integer type. We need to be conservative here since
02128   // x86 generates redundant zero-extenstion instructions if the operand is
02129   // truncated to i8 or i16.
02130   bool TruncCond = false;
02131   if (NewWidth > 0 && BitWidth > NewWidth &&
02132       NewWidth >= DL.getLargestLegalIntTypeSize()) {
02133     TruncCond = true;
02134     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
02135     Builder->SetInsertPoint(&SI);
02136     Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
02137     SI.setCondition(NewCond);
02138 
02139     for (auto &C : SI.cases())
02140       static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
02141           SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
02142   }
02143 
02144   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
02145     if (I->getOpcode() == Instruction::Add)
02146       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
02147         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
02148         // Skip the first item since that's the default case.
02149         for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
02150              i != e; ++i) {
02151           ConstantInt* CaseVal = i.getCaseValue();
02152           Constant *LHS = CaseVal;
02153           if (TruncCond)
02154             LHS = LeadingKnownZeros
02155                       ? ConstantExpr::getZExt(CaseVal, Cond->getType())
02156                       : ConstantExpr::getSExt(CaseVal, Cond->getType());
02157           Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
02158           assert(isa<ConstantInt>(NewCaseVal) &&
02159                  "Result of expression should be constant");
02160           i.setValue(cast<ConstantInt>(NewCaseVal));
02161         }
02162         SI.setCondition(I->getOperand(0));
02163         Worklist.Add(I);
02164         return &SI;
02165       }
02166   }
02167 
02168   return TruncCond ? &SI : nullptr;
02169 }
02170 
02171 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
02172   Value *Agg = EV.getAggregateOperand();
02173 
02174   if (!EV.hasIndices())
02175     return ReplaceInstUsesWith(EV, Agg);
02176 
02177   if (Constant *C = dyn_cast<Constant>(Agg)) {
02178     if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
02179       if (EV.getNumIndices() == 0)
02180         return ReplaceInstUsesWith(EV, C2);
02181       // Extract the remaining indices out of the constant indexed by the
02182       // first index
02183       return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
02184     }
02185     return nullptr; // Can't handle other constants
02186   }
02187 
02188   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
02189     // We're extracting from an insertvalue instruction, compare the indices
02190     const unsigned *exti, *exte, *insi, *inse;
02191     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
02192          exte = EV.idx_end(), inse = IV->idx_end();
02193          exti != exte && insi != inse;
02194          ++exti, ++insi) {
02195       if (*insi != *exti)
02196         // The insert and extract both reference distinctly different elements.
02197         // This means the extract is not influenced by the insert, and we can
02198         // replace the aggregate operand of the extract with the aggregate
02199         // operand of the insert. i.e., replace
02200         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
02201         // %E = extractvalue { i32, { i32 } } %I, 0
02202         // with
02203         // %E = extractvalue { i32, { i32 } } %A, 0
02204         return ExtractValueInst::Create(IV->getAggregateOperand(),
02205                                         EV.getIndices());
02206     }
02207     if (exti == exte && insi == inse)
02208       // Both iterators are at the end: Index lists are identical. Replace
02209       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
02210       // %C = extractvalue { i32, { i32 } } %B, 1, 0
02211       // with "i32 42"
02212       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
02213     if (exti == exte) {
02214       // The extract list is a prefix of the insert list. i.e. replace
02215       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
02216       // %E = extractvalue { i32, { i32 } } %I, 1
02217       // with
02218       // %X = extractvalue { i32, { i32 } } %A, 1
02219       // %E = insertvalue { i32 } %X, i32 42, 0
02220       // by switching the order of the insert and extract (though the
02221       // insertvalue should be left in, since it may have other uses).
02222       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
02223                                                  EV.getIndices());
02224       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
02225                                      makeArrayRef(insi, inse));
02226     }
02227     if (insi == inse)
02228       // The insert list is a prefix of the extract list
02229       // We can simply remove the common indices from the extract and make it
02230       // operate on the inserted value instead of the insertvalue result.
02231       // i.e., replace
02232       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
02233       // %E = extractvalue { i32, { i32 } } %I, 1, 0
02234       // with
02235       // %E extractvalue { i32 } { i32 42 }, 0
02236       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
02237                                       makeArrayRef(exti, exte));
02238   }
02239   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
02240     // We're extracting from an intrinsic, see if we're the only user, which
02241     // allows us to simplify multiple result intrinsics to simpler things that
02242     // just get one value.
02243     if (II->hasOneUse()) {
02244       // Check if we're grabbing the overflow bit or the result of a 'with
02245       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
02246       // and replace it with a traditional binary instruction.
02247       switch (II->getIntrinsicID()) {
02248       case Intrinsic::uadd_with_overflow:
02249       case Intrinsic::sadd_with_overflow:
02250         if (*EV.idx_begin() == 0) {  // Normal result.
02251           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
02252           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
02253           EraseInstFromFunction(*II);
02254           return BinaryOperator::CreateAdd(LHS, RHS);
02255         }
02256 
02257         // If the normal result of the add is dead, and the RHS is a constant,
02258         // we can transform this into a range comparison.
02259         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
02260         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
02261           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
02262             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
02263                                 ConstantExpr::getNot(CI));
02264         break;
02265       case Intrinsic::usub_with_overflow:
02266       case Intrinsic::ssub_with_overflow:
02267         if (*EV.idx_begin() == 0) {  // Normal result.
02268           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
02269           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
02270           EraseInstFromFunction(*II);
02271           return BinaryOperator::CreateSub(LHS, RHS);
02272         }
02273         break;
02274       case Intrinsic::umul_with_overflow:
02275       case Intrinsic::smul_with_overflow:
02276         if (*EV.idx_begin() == 0) {  // Normal result.
02277           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
02278           ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
02279           EraseInstFromFunction(*II);
02280           return BinaryOperator::CreateMul(LHS, RHS);
02281         }
02282         break;
02283       default:
02284         break;
02285       }
02286     }
02287   }
02288   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
02289     // If the (non-volatile) load only has one use, we can rewrite this to a
02290     // load from a GEP. This reduces the size of the load.
02291     // FIXME: If a load is used only by extractvalue instructions then this
02292     //        could be done regardless of having multiple uses.
02293     if (L->isSimple() && L->hasOneUse()) {
02294       // extractvalue has integer indices, getelementptr has Value*s. Convert.
02295       SmallVector<Value*, 4> Indices;
02296       // Prefix an i32 0 since we need the first element.
02297       Indices.push_back(Builder->getInt32(0));
02298       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
02299             I != E; ++I)
02300         Indices.push_back(Builder->getInt32(*I));
02301 
02302       // We need to insert these at the location of the old load, not at that of
02303       // the extractvalue.
02304       Builder->SetInsertPoint(L->getParent(), L);
02305       Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
02306                                               L->getPointerOperand(), Indices);
02307       // Returning the load directly will cause the main loop to insert it in
02308       // the wrong spot, so use ReplaceInstUsesWith().
02309       return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
02310     }
02311   // We could simplify extracts from other values. Note that nested extracts may
02312   // already be simplified implicitly by the above: extract (extract (insert) )
02313   // will be translated into extract ( insert ( extract ) ) first and then just
02314   // the value inserted, if appropriate. Similarly for extracts from single-use
02315   // loads: extract (extract (load)) will be translated to extract (load (gep))
02316   // and if again single-use then via load (gep (gep)) to load (gep).
02317   // However, double extracts from e.g. function arguments or return values
02318   // aren't handled yet.
02319   return nullptr;
02320 }
02321 
02322 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
02323 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
02324   switch (Personality) {
02325   case EHPersonality::GNU_C:
02326     // The GCC C EH personality only exists to support cleanups, so it's not
02327     // clear what the semantics of catch clauses are.
02328     return false;
02329   case EHPersonality::Unknown:
02330     return false;
02331   case EHPersonality::GNU_Ada:
02332     // While __gnat_all_others_value will match any Ada exception, it doesn't
02333     // match foreign exceptions (or didn't, before gcc-4.7).
02334     return false;
02335   case EHPersonality::GNU_CXX:
02336   case EHPersonality::GNU_ObjC:
02337   case EHPersonality::MSVC_X86SEH:
02338   case EHPersonality::MSVC_Win64SEH:
02339   case EHPersonality::MSVC_CXX:
02340     return TypeInfo->isNullValue();
02341   }
02342   llvm_unreachable("invalid enum");
02343 }
02344 
02345 static bool shorter_filter(const Value *LHS, const Value *RHS) {
02346   return
02347     cast<ArrayType>(LHS->getType())->getNumElements()
02348   <
02349     cast<ArrayType>(RHS->getType())->getNumElements();
02350 }
02351 
02352 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
02353   // The logic here should be correct for any real-world personality function.
02354   // However if that turns out not to be true, the offending logic can always
02355   // be conditioned on the personality function, like the catch-all logic is.
02356   EHPersonality Personality = classifyEHPersonality(LI.getPersonalityFn());
02357 
02358   // Simplify the list of clauses, eg by removing repeated catch clauses
02359   // (these are often created by inlining).
02360   bool MakeNewInstruction = false; // If true, recreate using the following:
02361   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
02362   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
02363 
02364   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
02365   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
02366     bool isLastClause = i + 1 == e;
02367     if (LI.isCatch(i)) {
02368       // A catch clause.
02369       Constant *CatchClause = LI.getClause(i);
02370       Constant *TypeInfo = CatchClause->stripPointerCasts();
02371 
02372       // If we already saw this clause, there is no point in having a second
02373       // copy of it.
02374       if (AlreadyCaught.insert(TypeInfo).second) {
02375         // This catch clause was not already seen.
02376         NewClauses.push_back(CatchClause);
02377       } else {
02378         // Repeated catch clause - drop the redundant copy.
02379         MakeNewInstruction = true;
02380       }
02381 
02382       // If this is a catch-all then there is no point in keeping any following
02383       // clauses or marking the landingpad as having a cleanup.
02384       if (isCatchAll(Personality, TypeInfo)) {
02385         if (!isLastClause)
02386           MakeNewInstruction = true;
02387         CleanupFlag = false;
02388         break;
02389       }
02390     } else {
02391       // A filter clause.  If any of the filter elements were already caught
02392       // then they can be dropped from the filter.  It is tempting to try to
02393       // exploit the filter further by saying that any typeinfo that does not
02394       // occur in the filter can't be caught later (and thus can be dropped).
02395       // However this would be wrong, since typeinfos can match without being
02396       // equal (for example if one represents a C++ class, and the other some
02397       // class derived from it).
02398       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
02399       Constant *FilterClause = LI.getClause(i);
02400       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
02401       unsigned NumTypeInfos = FilterType->getNumElements();
02402 
02403       // An empty filter catches everything, so there is no point in keeping any
02404       // following clauses or marking the landingpad as having a cleanup.  By
02405       // dealing with this case here the following code is made a bit simpler.
02406       if (!NumTypeInfos) {
02407         NewClauses.push_back(FilterClause);
02408         if (!isLastClause)
02409           MakeNewInstruction = true;
02410         CleanupFlag = false;
02411         break;
02412       }
02413 
02414       bool MakeNewFilter = false; // If true, make a new filter.
02415       SmallVector<Constant *, 16> NewFilterElts; // New elements.
02416       if (isa<ConstantAggregateZero>(FilterClause)) {
02417         // Not an empty filter - it contains at least one null typeinfo.
02418         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
02419         Constant *TypeInfo =
02420           Constant::getNullValue(FilterType->getElementType());
02421         // If this typeinfo is a catch-all then the filter can never match.
02422         if (isCatchAll(Personality, TypeInfo)) {
02423           // Throw the filter away.
02424           MakeNewInstruction = true;
02425           continue;
02426         }
02427 
02428         // There is no point in having multiple copies of this typeinfo, so
02429         // discard all but the first copy if there is more than one.
02430         NewFilterElts.push_back(TypeInfo);
02431         if (NumTypeInfos > 1)
02432           MakeNewFilter = true;
02433       } else {
02434         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
02435         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
02436         NewFilterElts.reserve(NumTypeInfos);
02437 
02438         // Remove any filter elements that were already caught or that already
02439         // occurred in the filter.  While there, see if any of the elements are
02440         // catch-alls.  If so, the filter can be discarded.
02441         bool SawCatchAll = false;
02442         for (unsigned j = 0; j != NumTypeInfos; ++j) {
02443           Constant *Elt = Filter->getOperand(j);
02444           Constant *TypeInfo = Elt->stripPointerCasts();
02445           if (isCatchAll(Personality, TypeInfo)) {
02446             // This element is a catch-all.  Bail out, noting this fact.
02447             SawCatchAll = true;
02448             break;
02449           }
02450           if (AlreadyCaught.count(TypeInfo))
02451             // Already caught by an earlier clause, so having it in the filter
02452             // is pointless.
02453             continue;
02454           // There is no point in having multiple copies of the same typeinfo in
02455           // a filter, so only add it if we didn't already.
02456           if (SeenInFilter.insert(TypeInfo).second)
02457             NewFilterElts.push_back(cast<Constant>(Elt));
02458         }
02459         // A filter containing a catch-all cannot match anything by definition.
02460         if (SawCatchAll) {
02461           // Throw the filter away.
02462           MakeNewInstruction = true;
02463           continue;
02464         }
02465 
02466         // If we dropped something from the filter, make a new one.
02467         if (NewFilterElts.size() < NumTypeInfos)
02468           MakeNewFilter = true;
02469       }
02470       if (MakeNewFilter) {
02471         FilterType = ArrayType::get(FilterType->getElementType(),
02472                                     NewFilterElts.size());
02473         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
02474         MakeNewInstruction = true;
02475       }
02476 
02477       NewClauses.push_back(FilterClause);
02478 
02479       // If the new filter is empty then it will catch everything so there is
02480       // no point in keeping any following clauses or marking the landingpad
02481       // as having a cleanup.  The case of the original filter being empty was
02482       // already handled above.
02483       if (MakeNewFilter && !NewFilterElts.size()) {
02484         assert(MakeNewInstruction && "New filter but not a new instruction!");
02485         CleanupFlag = false;
02486         break;
02487       }
02488     }
02489   }
02490 
02491   // If several filters occur in a row then reorder them so that the shortest
02492   // filters come first (those with the smallest number of elements).  This is
02493   // advantageous because shorter filters are more likely to match, speeding up
02494   // unwinding, but mostly because it increases the effectiveness of the other
02495   // filter optimizations below.
02496   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
02497     unsigned j;
02498     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
02499     for (j = i; j != e; ++j)
02500       if (!isa<ArrayType>(NewClauses[j]->getType()))
02501         break;
02502 
02503     // Check whether the filters are already sorted by length.  We need to know
02504     // if sorting them is actually going to do anything so that we only make a
02505     // new landingpad instruction if it does.
02506     for (unsigned k = i; k + 1 < j; ++k)
02507       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
02508         // Not sorted, so sort the filters now.  Doing an unstable sort would be
02509         // correct too but reordering filters pointlessly might confuse users.
02510         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
02511                          shorter_filter);
02512         MakeNewInstruction = true;
02513         break;
02514       }
02515 
02516     // Look for the next batch of filters.
02517     i = j + 1;
02518   }
02519 
02520   // If typeinfos matched if and only if equal, then the elements of a filter L
02521   // that occurs later than a filter F could be replaced by the intersection of
02522   // the elements of F and L.  In reality two typeinfos can match without being
02523   // equal (for example if one represents a C++ class, and the other some class
02524   // derived from it) so it would be wrong to perform this transform in general.
02525   // However the transform is correct and useful if F is a subset of L.  In that
02526   // case L can be replaced by F, and thus removed altogether since repeating a
02527   // filter is pointless.  So here we look at all pairs of filters F and L where
02528   // L follows F in the list of clauses, and remove L if every element of F is
02529   // an element of L.  This can occur when inlining C++ functions with exception
02530   // specifications.
02531   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
02532     // Examine each filter in turn.
02533     Value *Filter = NewClauses[i];
02534     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
02535     if (!FTy)
02536       // Not a filter - skip it.
02537       continue;
02538     unsigned FElts = FTy->getNumElements();
02539     // Examine each filter following this one.  Doing this backwards means that
02540     // we don't have to worry about filters disappearing under us when removed.
02541     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
02542       Value *LFilter = NewClauses[j];
02543       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
02544       if (!LTy)
02545         // Not a filter - skip it.
02546         continue;
02547       // If Filter is a subset of LFilter, i.e. every element of Filter is also
02548       // an element of LFilter, then discard LFilter.
02549       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
02550       // If Filter is empty then it is a subset of LFilter.
02551       if (!FElts) {
02552         // Discard LFilter.
02553         NewClauses.erase(J);
02554         MakeNewInstruction = true;
02555         // Move on to the next filter.
02556         continue;
02557       }
02558       unsigned LElts = LTy->getNumElements();
02559       // If Filter is longer than LFilter then it cannot be a subset of it.
02560       if (FElts > LElts)
02561         // Move on to the next filter.
02562         continue;
02563       // At this point we know that LFilter has at least one element.
02564       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
02565         // Filter is a subset of LFilter iff Filter contains only zeros (as we
02566         // already know that Filter is not longer than LFilter).
02567         if (isa<ConstantAggregateZero>(Filter)) {
02568           assert(FElts <= LElts && "Should have handled this case earlier!");
02569           // Discard LFilter.
02570           NewClauses.erase(J);
02571           MakeNewInstruction = true;
02572         }
02573         // Move on to the next filter.
02574         continue;
02575       }
02576       ConstantArray *LArray = cast<ConstantArray>(LFilter);
02577       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
02578         // Since Filter is non-empty and contains only zeros, it is a subset of
02579         // LFilter iff LFilter contains a zero.
02580         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
02581         for (unsigned l = 0; l != LElts; ++l)
02582           if (LArray->getOperand(l)->isNullValue()) {
02583             // LFilter contains a zero - discard it.
02584             NewClauses.erase(J);
02585             MakeNewInstruction = true;
02586             break;
02587           }
02588         // Move on to the next filter.
02589         continue;
02590       }
02591       // At this point we know that both filters are ConstantArrays.  Loop over
02592       // operands to see whether every element of Filter is also an element of
02593       // LFilter.  Since filters tend to be short this is probably faster than
02594       // using a method that scales nicely.
02595       ConstantArray *FArray = cast<ConstantArray>(Filter);
02596       bool AllFound = true;
02597       for (unsigned f = 0; f != FElts; ++f) {
02598         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
02599         AllFound = false;
02600         for (unsigned l = 0; l != LElts; ++l) {
02601           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
02602           if (LTypeInfo == FTypeInfo) {
02603             AllFound = true;
02604             break;
02605           }
02606         }
02607         if (!AllFound)
02608           break;
02609       }
02610       if (AllFound) {
02611         // Discard LFilter.
02612         NewClauses.erase(J);
02613         MakeNewInstruction = true;
02614       }
02615       // Move on to the next filter.
02616     }
02617   }
02618 
02619   // If we changed any of the clauses, replace the old landingpad instruction
02620   // with a new one.
02621   if (MakeNewInstruction) {
02622     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
02623                                                  LI.getPersonalityFn(),
02624                                                  NewClauses.size());
02625     for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
02626       NLI->addClause(NewClauses[i]);
02627     // A landing pad with no clauses must have the cleanup flag set.  It is
02628     // theoretically possible, though highly unlikely, that we eliminated all
02629     // clauses.  If so, force the cleanup flag to true.
02630     if (NewClauses.empty())
02631       CleanupFlag = true;
02632     NLI->setCleanup(CleanupFlag);
02633     return NLI;
02634   }
02635 
02636   // Even if none of the clauses changed, we may nonetheless have understood
02637   // that the cleanup flag is pointless.  Clear it if so.
02638   if (LI.isCleanup() != CleanupFlag) {
02639     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
02640     LI.setCleanup(CleanupFlag);
02641     return &LI;
02642   }
02643 
02644   return nullptr;
02645 }
02646 
02647 /// TryToSinkInstruction - Try to move the specified instruction from its
02648 /// current block into the beginning of DestBlock, which can only happen if it's
02649 /// safe to move the instruction past all of the instructions between it and the
02650 /// end of its block.
02651 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
02652   assert(I->hasOneUse() && "Invariants didn't hold!");
02653 
02654   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
02655   if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
02656       isa<TerminatorInst>(I))
02657     return false;
02658 
02659   // Do not sink alloca instructions out of the entry block.
02660   if (isa<AllocaInst>(I) && I->getParent() ==
02661         &DestBlock->getParent()->getEntryBlock())
02662     return false;
02663 
02664   // We can only sink load instructions if there is nothing between the load and
02665   // the end of block that could change the value.
02666   if (I->mayReadFromMemory()) {
02667     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
02668          Scan != E; ++Scan)
02669       if (Scan->mayWriteToMemory())
02670         return false;
02671   }
02672 
02673   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
02674   I->moveBefore(InsertPos);
02675   ++NumSunkInst;
02676   return true;
02677 }
02678 
02679 bool InstCombiner::run() {
02680   while (!Worklist.isEmpty()) {
02681     Instruction *I = Worklist.RemoveOne();
02682     if (I == nullptr) continue;  // skip null values.
02683 
02684     // Check to see if we can DCE the instruction.
02685     if (isInstructionTriviallyDead(I, TLI)) {
02686       DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
02687       EraseInstFromFunction(*I);
02688       ++NumDeadInst;
02689       MadeIRChange = true;
02690       continue;
02691     }
02692 
02693     // Instruction isn't dead, see if we can constant propagate it.
02694     if (!I->use_empty() && isa<Constant>(I->getOperand(0))) {
02695       if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
02696         DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
02697 
02698         // Add operands to the worklist.
02699         ReplaceInstUsesWith(*I, C);
02700         ++NumConstProp;
02701         EraseInstFromFunction(*I);
02702         MadeIRChange = true;
02703         continue;
02704       }
02705     }
02706 
02707     // See if we can trivially sink this instruction to a successor basic block.
02708     if (I->hasOneUse()) {
02709       BasicBlock *BB = I->getParent();
02710       Instruction *UserInst = cast<Instruction>(*I->user_begin());
02711       BasicBlock *UserParent;
02712 
02713       // Get the block the use occurs in.
02714       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
02715         UserParent = PN->getIncomingBlock(*I->use_begin());
02716       else
02717         UserParent = UserInst->getParent();
02718 
02719       if (UserParent != BB) {
02720         bool UserIsSuccessor = false;
02721         // See if the user is one of our successors.
02722         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
02723           if (*SI == UserParent) {
02724             UserIsSuccessor = true;
02725             break;
02726           }
02727 
02728         // If the user is one of our immediate successors, and if that successor
02729         // only has us as a predecessors (we'd have to split the critical edge
02730         // otherwise), we can keep going.
02731         if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
02732           // Okay, the CFG is simple enough, try to sink this instruction.
02733           if (TryToSinkInstruction(I, UserParent)) {
02734             MadeIRChange = true;
02735             // We'll add uses of the sunk instruction below, but since sinking
02736             // can expose opportunities for it's *operands* add them to the
02737             // worklist
02738             for (Use &U : I->operands())
02739               if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
02740                 Worklist.Add(OpI);
02741           }
02742         }
02743       }
02744     }
02745 
02746     // Now that we have an instruction, try combining it to simplify it.
02747     Builder->SetInsertPoint(I->getParent(), I);
02748     Builder->SetCurrentDebugLocation(I->getDebugLoc());
02749 
02750 #ifndef NDEBUG
02751     std::string OrigI;
02752 #endif
02753     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
02754     DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
02755 
02756     if (Instruction *Result = visit(*I)) {
02757       ++NumCombined;
02758       // Should we replace the old instruction with a new one?
02759       if (Result != I) {
02760         DEBUG(dbgs() << "IC: Old = " << *I << '\n'
02761                      << "    New = " << *Result << '\n');
02762 
02763         if (I->getDebugLoc())
02764           Result->setDebugLoc(I->getDebugLoc());
02765         // Everything uses the new instruction now.
02766         I->replaceAllUsesWith(Result);
02767 
02768         // Move the name to the new instruction first.
02769         Result->takeName(I);
02770 
02771         // Push the new instruction and any users onto the worklist.
02772         Worklist.Add(Result);
02773         Worklist.AddUsersToWorkList(*Result);
02774 
02775         // Insert the new instruction into the basic block...
02776         BasicBlock *InstParent = I->getParent();
02777         BasicBlock::iterator InsertPos = I;
02778 
02779         // If we replace a PHI with something that isn't a PHI, fix up the
02780         // insertion point.
02781         if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
02782           InsertPos = InstParent->getFirstInsertionPt();
02783 
02784         InstParent->getInstList().insert(InsertPos, Result);
02785 
02786         EraseInstFromFunction(*I);
02787       } else {
02788 #ifndef NDEBUG
02789         DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
02790                      << "    New = " << *I << '\n');
02791 #endif
02792 
02793         // If the instruction was modified, it's possible that it is now dead.
02794         // if so, remove it.
02795         if (isInstructionTriviallyDead(I, TLI)) {
02796           EraseInstFromFunction(*I);
02797         } else {
02798           Worklist.Add(I);
02799           Worklist.AddUsersToWorkList(*I);
02800         }
02801       }
02802       MadeIRChange = true;
02803     }
02804   }
02805 
02806   Worklist.Zap();
02807   return MadeIRChange;
02808 }
02809 
02810 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
02811 /// all reachable code to the worklist.
02812 ///
02813 /// This has a couple of tricks to make the code faster and more powerful.  In
02814 /// particular, we constant fold and DCE instructions as we go, to avoid adding
02815 /// them to the worklist (this significantly speeds up instcombine on code where
02816 /// many instructions are dead or constant).  Additionally, if we find a branch
02817 /// whose condition is a known constant, we only visit the reachable successors.
02818 ///
02819 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
02820                                        SmallPtrSetImpl<BasicBlock *> &Visited,
02821                                        InstCombineWorklist &ICWorklist,
02822                                        const TargetLibraryInfo *TLI) {
02823   bool MadeIRChange = false;
02824   SmallVector<BasicBlock*, 256> Worklist;
02825   Worklist.push_back(BB);
02826 
02827   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
02828   DenseMap<ConstantExpr*, Constant*> FoldedConstants;
02829 
02830   do {
02831     BB = Worklist.pop_back_val();
02832 
02833     // We have now visited this block!  If we've already been here, ignore it.
02834     if (!Visited.insert(BB).second)
02835       continue;
02836 
02837     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
02838       Instruction *Inst = BBI++;
02839 
02840       // DCE instruction if trivially dead.
02841       if (isInstructionTriviallyDead(Inst, TLI)) {
02842         ++NumDeadInst;
02843         DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
02844         Inst->eraseFromParent();
02845         continue;
02846       }
02847 
02848       // ConstantProp instruction if trivially constant.
02849       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
02850         if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
02851           DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
02852                        << *Inst << '\n');
02853           Inst->replaceAllUsesWith(C);
02854           ++NumConstProp;
02855           Inst->eraseFromParent();
02856           continue;
02857         }
02858 
02859       // See if we can constant fold its operands.
02860       for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
02861            ++i) {
02862         ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
02863         if (CE == nullptr)
02864           continue;
02865 
02866         Constant *&FoldRes = FoldedConstants[CE];
02867         if (!FoldRes)
02868           FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
02869         if (!FoldRes)
02870           FoldRes = CE;
02871 
02872         if (FoldRes != CE) {
02873           *i = FoldRes;
02874           MadeIRChange = true;
02875         }
02876       }
02877 
02878       InstrsForInstCombineWorklist.push_back(Inst);
02879     }
02880 
02881     // Recursively visit successors.  If this is a branch or switch on a
02882     // constant, only visit the reachable successor.
02883     TerminatorInst *TI = BB->getTerminator();
02884     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
02885       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
02886         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
02887         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
02888         Worklist.push_back(ReachableBB);
02889         continue;
02890       }
02891     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
02892       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
02893         // See if this is an explicit destination.
02894         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
02895              i != e; ++i)
02896           if (i.getCaseValue() == Cond) {
02897             BasicBlock *ReachableBB = i.getCaseSuccessor();
02898             Worklist.push_back(ReachableBB);
02899             continue;
02900           }
02901 
02902         // Otherwise it is the default destination.
02903         Worklist.push_back(SI->getDefaultDest());
02904         continue;
02905       }
02906     }
02907 
02908     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
02909       Worklist.push_back(TI->getSuccessor(i));
02910   } while (!Worklist.empty());
02911 
02912   // Once we've found all of the instructions to add to instcombine's worklist,
02913   // add them in reverse order.  This way instcombine will visit from the top
02914   // of the function down.  This jives well with the way that it adds all uses
02915   // of instructions to the worklist after doing a transformation, thus avoiding
02916   // some N^2 behavior in pathological cases.
02917   ICWorklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
02918                              InstrsForInstCombineWorklist.size());
02919 
02920   return MadeIRChange;
02921 }
02922 
02923 /// \brief Populate the IC worklist from a function, and prune any dead basic
02924 /// blocks discovered in the process.
02925 ///
02926 /// This also does basic constant propagation and other forward fixing to make
02927 /// the combiner itself run much faster.
02928 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
02929                                           TargetLibraryInfo *TLI,
02930                                           InstCombineWorklist &ICWorklist) {
02931   bool MadeIRChange = false;
02932 
02933   // Do a depth-first traversal of the function, populate the worklist with
02934   // the reachable instructions.  Ignore blocks that are not reachable.  Keep
02935   // track of which blocks we visit.
02936   SmallPtrSet<BasicBlock *, 64> Visited;
02937   MadeIRChange |=
02938       AddReachableCodeToWorklist(F.begin(), DL, Visited, ICWorklist, TLI);
02939 
02940   // Do a quick scan over the function.  If we find any blocks that are
02941   // unreachable, remove any instructions inside of them.  This prevents
02942   // the instcombine code from having to deal with some bad special cases.
02943   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
02944     if (Visited.count(BB))
02945       continue;
02946 
02947     // Delete the instructions backwards, as it has a reduced likelihood of
02948     // having to update as many def-use and use-def chains.
02949     Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
02950     while (EndInst != BB->begin()) {
02951       // Delete the next to last instruction.
02952       BasicBlock::iterator I = EndInst;
02953       Instruction *Inst = --I;
02954       if (!Inst->use_empty())
02955         Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
02956       if (isa<LandingPadInst>(Inst)) {
02957         EndInst = Inst;
02958         continue;
02959       }
02960       if (!isa<DbgInfoIntrinsic>(Inst)) {
02961         ++NumDeadInst;
02962         MadeIRChange = true;
02963       }
02964       Inst->eraseFromParent();
02965     }
02966   }
02967 
02968   return MadeIRChange;
02969 }
02970 
02971 static bool
02972 combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
02973                                 AssumptionCache &AC, TargetLibraryInfo &TLI,
02974                                 DominatorTree &DT, LoopInfo *LI = nullptr) {
02975   // Minimizing size?
02976   bool MinimizeSize = F.hasFnAttribute(Attribute::MinSize);
02977   auto &DL = F.getParent()->getDataLayout();
02978 
02979   /// Builder - This is an IRBuilder that automatically inserts new
02980   /// instructions into the worklist when they are created.
02981   IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
02982       F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
02983 
02984   // Lower dbg.declare intrinsics otherwise their value may be clobbered
02985   // by instcombiner.
02986   bool DbgDeclaresChanged = LowerDbgDeclare(F);
02987 
02988   // Iterate while there is work to do.
02989   int Iteration = 0;
02990   for (;;) {
02991     ++Iteration;
02992     DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
02993                  << F.getName() << "\n");
02994 
02995     bool Changed = false;
02996     if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
02997       Changed = true;
02998 
02999     InstCombiner IC(Worklist, &Builder, MinimizeSize, &AC, &TLI, &DT, DL, LI);
03000     if (IC.run())
03001       Changed = true;
03002 
03003     if (!Changed)
03004       break;
03005   }
03006 
03007   return DbgDeclaresChanged || Iteration > 1;
03008 }
03009 
03010 PreservedAnalyses InstCombinePass::run(Function &F,
03011                                        AnalysisManager<Function> *AM) {
03012   auto &AC = AM->getResult<AssumptionAnalysis>(F);
03013   auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
03014   auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
03015 
03016   auto *LI = AM->getCachedResult<LoopAnalysis>(F);
03017 
03018   if (!combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, LI))
03019     // No changes, all analyses are preserved.
03020     return PreservedAnalyses::all();
03021 
03022   // Mark all the analyses that instcombine updates as preserved.
03023   // FIXME: Need a way to preserve CFG analyses here!
03024   PreservedAnalyses PA;
03025   PA.preserve<DominatorTreeAnalysis>();
03026   return PA;
03027 }
03028 
03029 namespace {
03030 /// \brief The legacy pass manager's instcombine pass.
03031 ///
03032 /// This is a basic whole-function wrapper around the instcombine utility. It
03033 /// will try to combine all instructions in the function.
03034 class InstructionCombiningPass : public FunctionPass {
03035   InstCombineWorklist Worklist;
03036 
03037 public:
03038   static char ID; // Pass identification, replacement for typeid
03039 
03040   InstructionCombiningPass() : FunctionPass(ID) {
03041     initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
03042   }
03043 
03044   void getAnalysisUsage(AnalysisUsage &AU) const override;
03045   bool runOnFunction(Function &F) override;
03046 };
03047 }
03048 
03049 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
03050   AU.setPreservesCFG();
03051   AU.addRequired<AssumptionCacheTracker>();
03052   AU.addRequired<TargetLibraryInfoWrapperPass>();
03053   AU.addRequired<DominatorTreeWrapperPass>();
03054   AU.addPreserved<DominatorTreeWrapperPass>();
03055 }
03056 
03057 bool InstructionCombiningPass::runOnFunction(Function &F) {
03058   if (skipOptnoneFunction(F))
03059     return false;
03060 
03061   // Required analyses.
03062   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
03063   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
03064   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
03065 
03066   // Optional analyses.
03067   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
03068   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
03069 
03070   return combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, LI);
03071 }
03072 
03073 char InstructionCombiningPass::ID = 0;
03074 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
03075                       "Combine redundant instructions", false, false)
03076 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
03077 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
03078 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
03079 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
03080                     "Combine redundant instructions", false, false)
03081 
03082 // Initialization Routines
03083 void llvm::initializeInstCombine(PassRegistry &Registry) {
03084   initializeInstructionCombiningPassPass(Registry);
03085 }
03086 
03087 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
03088   initializeInstructionCombiningPassPass(*unwrap(R));
03089 }
03090 
03091 FunctionPass *llvm::createInstructionCombiningPass() {
03092   return new InstructionCombiningPass();
03093 }