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