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