LLVM API Documentation

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