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