LLVM API Documentation

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