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