LLVM  mainline
InstCombineVectorOps.cpp
Go to the documentation of this file.
00001 //===- InstCombineVectorOps.cpp -------------------------------------------===//
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 // This file implements instcombine for ExtractElement, InsertElement and
00011 // ShuffleVector.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "InstCombineInternal.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/Analysis/InstructionSimplify.h"
00018 #include "llvm/Analysis/VectorUtils.h"
00019 #include "llvm/IR/PatternMatch.h"
00020 using namespace llvm;
00021 using namespace PatternMatch;
00022 
00023 #define DEBUG_TYPE "instcombine"
00024 
00025 /// Return true if the value is cheaper to scalarize than it is to leave as a
00026 /// vector operation. isConstant indicates whether we're extracting one known
00027 /// element. If false we're extracting a variable index.
00028 static bool cheapToScalarize(Value *V, bool isConstant) {
00029   if (Constant *C = dyn_cast<Constant>(V)) {
00030     if (isConstant) return true;
00031 
00032     // If all elts are the same, we can extract it and use any of the values.
00033     if (Constant *Op0 = C->getAggregateElement(0U)) {
00034       for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
00035            ++i)
00036         if (C->getAggregateElement(i) != Op0)
00037           return false;
00038       return true;
00039     }
00040   }
00041   Instruction *I = dyn_cast<Instruction>(V);
00042   if (!I) return false;
00043 
00044   // Insert element gets simplified to the inserted element or is deleted if
00045   // this is constant idx extract element and its a constant idx insertelt.
00046   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
00047       isa<ConstantInt>(I->getOperand(2)))
00048     return true;
00049   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
00050     return true;
00051   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
00052     if (BO->hasOneUse() &&
00053         (cheapToScalarize(BO->getOperand(0), isConstant) ||
00054          cheapToScalarize(BO->getOperand(1), isConstant)))
00055       return true;
00056   if (CmpInst *CI = dyn_cast<CmpInst>(I))
00057     if (CI->hasOneUse() &&
00058         (cheapToScalarize(CI->getOperand(0), isConstant) ||
00059          cheapToScalarize(CI->getOperand(1), isConstant)))
00060       return true;
00061 
00062   return false;
00063 }
00064 
00065 // If we have a PHI node with a vector type that has only 2 uses: feed
00066 // itself and be an operand of extractelement at a constant location,
00067 // try to replace the PHI of the vector type with a PHI of a scalar type.
00068 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
00069   // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
00070   if (!PN->hasNUses(2))
00071     return nullptr;
00072 
00073   // If so, it's known at this point that one operand is PHI and the other is
00074   // an extractelement node. Find the PHI user that is not the extractelement
00075   // node.
00076   auto iu = PN->user_begin();
00077   Instruction *PHIUser = dyn_cast<Instruction>(*iu);
00078   if (PHIUser == cast<Instruction>(&EI))
00079     PHIUser = cast<Instruction>(*(++iu));
00080 
00081   // Verify that this PHI user has one use, which is the PHI itself,
00082   // and that it is a binary operation which is cheap to scalarize.
00083   // otherwise return NULL.
00084   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
00085       !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
00086     return nullptr;
00087 
00088   // Create a scalar PHI node that will replace the vector PHI node
00089   // just before the current PHI node.
00090   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
00091       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
00092   // Scalarize each PHI operand.
00093   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
00094     Value *PHIInVal = PN->getIncomingValue(i);
00095     BasicBlock *inBB = PN->getIncomingBlock(i);
00096     Value *Elt = EI.getIndexOperand();
00097     // If the operand is the PHI induction variable:
00098     if (PHIInVal == PHIUser) {
00099       // Scalarize the binary operation. Its first operand is the
00100       // scalar PHI, and the second operand is extracted from the other
00101       // vector operand.
00102       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
00103       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
00104       Value *Op = InsertNewInstWith(
00105           ExtractElementInst::Create(B0->getOperand(opId), Elt,
00106                                      B0->getOperand(opId)->getName() + ".Elt"),
00107           *B0);
00108       Value *newPHIUser = InsertNewInstWith(
00109           BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
00110       scalarPHI->addIncoming(newPHIUser, inBB);
00111     } else {
00112       // Scalarize PHI input:
00113       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
00114       // Insert the new instruction into the predecessor basic block.
00115       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
00116       BasicBlock::iterator InsertPos;
00117       if (pos && !isa<PHINode>(pos)) {
00118         InsertPos = ++pos->getIterator();
00119       } else {
00120         InsertPos = inBB->getFirstInsertionPt();
00121       }
00122 
00123       InsertNewInstWith(newEI, *InsertPos);
00124 
00125       scalarPHI->addIncoming(newEI, inBB);
00126     }
00127   }
00128   return ReplaceInstUsesWith(EI, scalarPHI);
00129 }
00130 
00131 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
00132   if (Value *V = SimplifyExtractElementInst(
00133           EI.getVectorOperand(), EI.getIndexOperand(), DL, TLI, DT, AC))
00134     return ReplaceInstUsesWith(EI, V);
00135 
00136   // If vector val is constant with all elements the same, replace EI with
00137   // that element.  We handle a known element # below.
00138   if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
00139     if (cheapToScalarize(C, false))
00140       return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
00141 
00142   // If extracting a specified index from the vector, see if we can recursively
00143   // find a previously computed scalar that was inserted into the vector.
00144   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
00145     unsigned IndexVal = IdxC->getZExtValue();
00146     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
00147 
00148     // InstSimplify handles cases where the index is invalid.
00149     assert(IndexVal < VectorWidth);
00150 
00151     // This instruction only demands the single element from the input vector.
00152     // If the input vector has a single use, simplify it based on this use
00153     // property.
00154     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
00155       APInt UndefElts(VectorWidth, 0);
00156       APInt DemandedMask(VectorWidth, 0);
00157       DemandedMask.setBit(IndexVal);
00158       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
00159                                                 UndefElts)) {
00160         EI.setOperand(0, V);
00161         return &EI;
00162       }
00163     }
00164 
00165     // If this extractelement is directly using a bitcast from a vector of
00166     // the same number of elements, see if we can find the source element from
00167     // it.  In this case, we will end up needing to bitcast the scalars.
00168     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
00169       if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
00170         if (VT->getNumElements() == VectorWidth)
00171           if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
00172             return new BitCastInst(Elt, EI.getType());
00173     }
00174 
00175     // If there's a vector PHI feeding a scalar use through this extractelement
00176     // instruction, try to scalarize the PHI.
00177     if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
00178       Instruction *scalarPHI = scalarizePHI(EI, PN);
00179       if (scalarPHI)
00180         return scalarPHI;
00181     }
00182   }
00183 
00184   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
00185     // Push extractelement into predecessor operation if legal and
00186     // profitable to do so.
00187     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
00188       if (I->hasOneUse() &&
00189           cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
00190         Value *newEI0 =
00191           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
00192                                         EI.getName()+".lhs");
00193         Value *newEI1 =
00194           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
00195                                         EI.getName()+".rhs");
00196         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
00197       }
00198     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
00199       // Extracting the inserted element?
00200       if (IE->getOperand(2) == EI.getOperand(1))
00201         return ReplaceInstUsesWith(EI, IE->getOperand(1));
00202       // If the inserted and extracted elements are constants, they must not
00203       // be the same value, extract from the pre-inserted value instead.
00204       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
00205         Worklist.AddValue(EI.getOperand(0));
00206         EI.setOperand(0, IE->getOperand(0));
00207         return &EI;
00208       }
00209     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
00210       // If this is extracting an element from a shufflevector, figure out where
00211       // it came from and extract from the appropriate input element instead.
00212       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
00213         int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
00214         Value *Src;
00215         unsigned LHSWidth =
00216           SVI->getOperand(0)->getType()->getVectorNumElements();
00217 
00218         if (SrcIdx < 0)
00219           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
00220         if (SrcIdx < (int)LHSWidth)
00221           Src = SVI->getOperand(0);
00222         else {
00223           SrcIdx -= LHSWidth;
00224           Src = SVI->getOperand(1);
00225         }
00226         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
00227         return ExtractElementInst::Create(Src,
00228                                           ConstantInt::get(Int32Ty,
00229                                                            SrcIdx, false));
00230       }
00231     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
00232       // Canonicalize extractelement(cast) -> cast(extractelement).
00233       // Bitcasts can change the number of vector elements, and they cost
00234       // nothing.
00235       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
00236         Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
00237                                                   EI.getIndexOperand());
00238         Worklist.AddValue(EE);
00239         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
00240       }
00241     } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
00242       if (SI->hasOneUse()) {
00243         // TODO: For a select on vectors, it might be useful to do this if it
00244         // has multiple extractelement uses. For vector select, that seems to
00245         // fight the vectorizer.
00246 
00247         // If we are extracting an element from a vector select or a select on
00248         // vectors, create a select on the scalars extracted from the vector
00249         // arguments.
00250         Value *TrueVal = SI->getTrueValue();
00251         Value *FalseVal = SI->getFalseValue();
00252 
00253         Value *Cond = SI->getCondition();
00254         if (Cond->getType()->isVectorTy()) {
00255           Cond = Builder->CreateExtractElement(Cond,
00256                                                EI.getIndexOperand(),
00257                                                Cond->getName() + ".elt");
00258         }
00259 
00260         Value *V1Elem
00261           = Builder->CreateExtractElement(TrueVal,
00262                                           EI.getIndexOperand(),
00263                                           TrueVal->getName() + ".elt");
00264 
00265         Value *V2Elem
00266           = Builder->CreateExtractElement(FalseVal,
00267                                           EI.getIndexOperand(),
00268                                           FalseVal->getName() + ".elt");
00269         return SelectInst::Create(Cond,
00270                                   V1Elem,
00271                                   V2Elem,
00272                                   SI->getName() + ".elt");
00273       }
00274     }
00275   }
00276   return nullptr;
00277 }
00278 
00279 /// If V is a shuffle of values that ONLY returns elements from either LHS or
00280 /// RHS, return the shuffle mask and true. Otherwise, return false.
00281 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
00282                                          SmallVectorImpl<Constant*> &Mask) {
00283   assert(LHS->getType() == RHS->getType() &&
00284          "Invalid CollectSingleShuffleElements");
00285   unsigned NumElts = V->getType()->getVectorNumElements();
00286 
00287   if (isa<UndefValue>(V)) {
00288     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
00289     return true;
00290   }
00291 
00292   if (V == LHS) {
00293     for (unsigned i = 0; i != NumElts; ++i)
00294       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
00295     return true;
00296   }
00297 
00298   if (V == RHS) {
00299     for (unsigned i = 0; i != NumElts; ++i)
00300       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
00301                                       i+NumElts));
00302     return true;
00303   }
00304 
00305   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
00306     // If this is an insert of an extract from some other vector, include it.
00307     Value *VecOp    = IEI->getOperand(0);
00308     Value *ScalarOp = IEI->getOperand(1);
00309     Value *IdxOp    = IEI->getOperand(2);
00310 
00311     if (!isa<ConstantInt>(IdxOp))
00312       return false;
00313     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
00314 
00315     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
00316       // We can handle this if the vector we are inserting into is
00317       // transitively ok.
00318       if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
00319         // If so, update the mask to reflect the inserted undef.
00320         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
00321         return true;
00322       }
00323     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
00324       if (isa<ConstantInt>(EI->getOperand(1))) {
00325         unsigned ExtractedIdx =
00326         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
00327         unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
00328 
00329         // This must be extracting from either LHS or RHS.
00330         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
00331           // We can handle this if the vector we are inserting into is
00332           // transitively ok.
00333           if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
00334             // If so, update the mask to reflect the inserted value.
00335             if (EI->getOperand(0) == LHS) {
00336               Mask[InsertedIdx % NumElts] =
00337               ConstantInt::get(Type::getInt32Ty(V->getContext()),
00338                                ExtractedIdx);
00339             } else {
00340               assert(EI->getOperand(0) == RHS);
00341               Mask[InsertedIdx % NumElts] =
00342               ConstantInt::get(Type::getInt32Ty(V->getContext()),
00343                                ExtractedIdx + NumLHSElts);
00344             }
00345             return true;
00346           }
00347         }
00348       }
00349     }
00350   }
00351 
00352   return false;
00353 }
00354 
00355 /// If we have insertion into a vector that is wider than the vector that we
00356 /// are extracting from, try to widen the source vector to allow a single
00357 /// shufflevector to replace one or more insert/extract pairs.
00358 static void replaceExtractElements(InsertElementInst *InsElt,
00359                                    ExtractElementInst *ExtElt,
00360                                    InstCombiner &IC) {
00361   VectorType *InsVecType = InsElt->getType();
00362   VectorType *ExtVecType = ExtElt->getVectorOperandType();
00363   unsigned NumInsElts = InsVecType->getVectorNumElements();
00364   unsigned NumExtElts = ExtVecType->getVectorNumElements();
00365 
00366   // The inserted-to vector must be wider than the extracted-from vector.
00367   if (InsVecType->getElementType() != ExtVecType->getElementType() ||
00368       NumExtElts >= NumInsElts)
00369     return;
00370 
00371   // Create a shuffle mask to widen the extended-from vector using undefined
00372   // values. The mask selects all of the values of the original vector followed
00373   // by as many undefined values as needed to create a vector of the same length
00374   // as the inserted-to vector.
00375   SmallVector<Constant *, 16> ExtendMask;
00376   IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
00377   for (unsigned i = 0; i < NumExtElts; ++i)
00378     ExtendMask.push_back(ConstantInt::get(IntType, i));
00379   for (unsigned i = NumExtElts; i < NumInsElts; ++i)
00380     ExtendMask.push_back(UndefValue::get(IntType));
00381 
00382   Value *ExtVecOp = ExtElt->getVectorOperand();
00383   auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
00384                                         ConstantVector::get(ExtendMask));
00385 
00386   // Insert the new shuffle after the vector operand of the extract is defined
00387   // (as long as it's not a PHI) or at the start of the basic block of the
00388   // extract, so any subsequent extracts in the same basic block can use it.
00389   // TODO: Insert before the earliest ExtractElementInst that is replaced.
00390   auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
00391   if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
00392     WideVec->insertAfter(ExtVecOpInst);
00393   else
00394     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
00395 
00396   // Replace extracts from the original narrow vector with extracts from the new
00397   // wide vector.
00398   for (User *U : ExtVecOp->users()) {
00399     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
00400     if (!OldExt || OldExt->getParent() != WideVec->getParent())
00401       continue;
00402     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
00403     NewExt->insertAfter(WideVec);
00404     IC.ReplaceInstUsesWith(*OldExt, NewExt);
00405   }
00406 }
00407 
00408 /// We are building a shuffle to create V, which is a sequence of insertelement,
00409 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
00410 /// not rely on the second vector source. Return a std::pair containing the
00411 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
00412 /// parameter as required.
00413 ///
00414 /// Note: we intentionally don't try to fold earlier shuffles since they have
00415 /// often been chosen carefully to be efficiently implementable on the target.
00416 typedef std::pair<Value *, Value *> ShuffleOps;
00417 
00418 static ShuffleOps collectShuffleElements(Value *V,
00419                                          SmallVectorImpl<Constant *> &Mask,
00420                                          Value *PermittedRHS,
00421                                          InstCombiner &IC) {
00422   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
00423   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
00424 
00425   if (isa<UndefValue>(V)) {
00426     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
00427     return std::make_pair(
00428         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
00429   }
00430 
00431   if (isa<ConstantAggregateZero>(V)) {
00432     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
00433     return std::make_pair(V, nullptr);
00434   }
00435 
00436   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
00437     // If this is an insert of an extract from some other vector, include it.
00438     Value *VecOp    = IEI->getOperand(0);
00439     Value *ScalarOp = IEI->getOperand(1);
00440     Value *IdxOp    = IEI->getOperand(2);
00441 
00442     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
00443       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
00444         unsigned ExtractedIdx =
00445           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
00446         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
00447 
00448         // Either the extracted from or inserted into vector must be RHSVec,
00449         // otherwise we'd end up with a shuffle of three inputs.
00450         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
00451           Value *RHS = EI->getOperand(0);
00452           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
00453           assert(LR.second == nullptr || LR.second == RHS);
00454 
00455           if (LR.first->getType() != RHS->getType()) {
00456             // Although we are giving up for now, see if we can create extracts
00457             // that match the inserts for another round of combining.
00458             replaceExtractElements(IEI, EI, IC);
00459 
00460             // We tried our best, but we can't find anything compatible with RHS
00461             // further up the chain. Return a trivial shuffle.
00462             for (unsigned i = 0; i < NumElts; ++i)
00463               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
00464             return std::make_pair(V, nullptr);
00465           }
00466 
00467           unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
00468           Mask[InsertedIdx % NumElts] =
00469             ConstantInt::get(Type::getInt32Ty(V->getContext()),
00470                              NumLHSElts+ExtractedIdx);
00471           return std::make_pair(LR.first, RHS);
00472         }
00473 
00474         if (VecOp == PermittedRHS) {
00475           // We've gone as far as we can: anything on the other side of the
00476           // extractelement will already have been converted into a shuffle.
00477           unsigned NumLHSElts =
00478               EI->getOperand(0)->getType()->getVectorNumElements();
00479           for (unsigned i = 0; i != NumElts; ++i)
00480             Mask.push_back(ConstantInt::get(
00481                 Type::getInt32Ty(V->getContext()),
00482                 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
00483           return std::make_pair(EI->getOperand(0), PermittedRHS);
00484         }
00485 
00486         // If this insertelement is a chain that comes from exactly these two
00487         // vectors, return the vector and the effective shuffle.
00488         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
00489             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
00490                                          Mask))
00491           return std::make_pair(EI->getOperand(0), PermittedRHS);
00492       }
00493     }
00494   }
00495 
00496   // Otherwise, we can't do anything fancy. Return an identity vector.
00497   for (unsigned i = 0; i != NumElts; ++i)
00498     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
00499   return std::make_pair(V, nullptr);
00500 }
00501 
00502 /// Try to find redundant insertvalue instructions, like the following ones:
00503 ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
00504 ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
00505 /// Here the second instruction inserts values at the same indices, as the
00506 /// first one, making the first one redundant.
00507 /// It should be transformed to:
00508 ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
00509 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
00510   bool IsRedundant = false;
00511   ArrayRef<unsigned int> FirstIndices = I.getIndices();
00512 
00513   // If there is a chain of insertvalue instructions (each of them except the
00514   // last one has only one use and it's another insertvalue insn from this
00515   // chain), check if any of the 'children' uses the same indices as the first
00516   // instruction. In this case, the first one is redundant.
00517   Value *V = &I;
00518   unsigned Depth = 0;
00519   while (V->hasOneUse() && Depth < 10) {
00520     User *U = V->user_back();
00521     auto UserInsInst = dyn_cast<InsertValueInst>(U);
00522     if (!UserInsInst || U->getOperand(0) != V)
00523       break;
00524     if (UserInsInst->getIndices() == FirstIndices) {
00525       IsRedundant = true;
00526       break;
00527     }
00528     V = UserInsInst;
00529     Depth++;
00530   }
00531 
00532   if (IsRedundant)
00533     return ReplaceInstUsesWith(I, I.getOperand(0));
00534   return nullptr;
00535 }
00536 
00537 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
00538   Value *VecOp    = IE.getOperand(0);
00539   Value *ScalarOp = IE.getOperand(1);
00540   Value *IdxOp    = IE.getOperand(2);
00541 
00542   // Inserting an undef or into an undefined place, remove this.
00543   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
00544     ReplaceInstUsesWith(IE, VecOp);
00545 
00546   // If the inserted element was extracted from some other vector, and if the
00547   // indexes are constant, try to turn this into a shufflevector operation.
00548   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
00549     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
00550       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
00551       unsigned NumExtractVectorElts =
00552           EI->getOperand(0)->getType()->getVectorNumElements();
00553       unsigned ExtractedIdx =
00554         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
00555       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
00556 
00557       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
00558         return ReplaceInstUsesWith(IE, VecOp);
00559 
00560       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
00561         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
00562 
00563       // If we are extracting a value from a vector, then inserting it right
00564       // back into the same place, just use the input vector.
00565       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
00566         return ReplaceInstUsesWith(IE, VecOp);
00567 
00568       // If this insertelement isn't used by some other insertelement, turn it
00569       // (and any insertelements it points to), into one big shuffle.
00570       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
00571         SmallVector<Constant*, 16> Mask;
00572         ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
00573 
00574         // The proposed shuffle may be trivial, in which case we shouldn't
00575         // perform the combine.
00576         if (LR.first != &IE && LR.second != &IE) {
00577           // We now have a shuffle of LHS, RHS, Mask.
00578           if (LR.second == nullptr)
00579             LR.second = UndefValue::get(LR.first->getType());
00580           return new ShuffleVectorInst(LR.first, LR.second,
00581                                        ConstantVector::get(Mask));
00582         }
00583       }
00584     }
00585   }
00586 
00587   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
00588   APInt UndefElts(VWidth, 0);
00589   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
00590   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
00591     if (V != &IE)
00592       return ReplaceInstUsesWith(IE, V);
00593     return &IE;
00594   }
00595 
00596   return nullptr;
00597 }
00598 
00599 /// Return true if we can evaluate the specified expression tree if the vector
00600 /// elements were shuffled in a different order.
00601 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
00602                                 unsigned Depth = 5) {
00603   // We can always reorder the elements of a constant.
00604   if (isa<Constant>(V))
00605     return true;
00606 
00607   // We won't reorder vector arguments. No IPO here.
00608   Instruction *I = dyn_cast<Instruction>(V);
00609   if (!I) return false;
00610 
00611   // Two users may expect different orders of the elements. Don't try it.
00612   if (!I->hasOneUse())
00613     return false;
00614 
00615   if (Depth == 0) return false;
00616 
00617   switch (I->getOpcode()) {
00618     case Instruction::Add:
00619     case Instruction::FAdd:
00620     case Instruction::Sub:
00621     case Instruction::FSub:
00622     case Instruction::Mul:
00623     case Instruction::FMul:
00624     case Instruction::UDiv:
00625     case Instruction::SDiv:
00626     case Instruction::FDiv:
00627     case Instruction::URem:
00628     case Instruction::SRem:
00629     case Instruction::FRem:
00630     case Instruction::Shl:
00631     case Instruction::LShr:
00632     case Instruction::AShr:
00633     case Instruction::And:
00634     case Instruction::Or:
00635     case Instruction::Xor:
00636     case Instruction::ICmp:
00637     case Instruction::FCmp:
00638     case Instruction::Trunc:
00639     case Instruction::ZExt:
00640     case Instruction::SExt:
00641     case Instruction::FPToUI:
00642     case Instruction::FPToSI:
00643     case Instruction::UIToFP:
00644     case Instruction::SIToFP:
00645     case Instruction::FPTrunc:
00646     case Instruction::FPExt:
00647     case Instruction::GetElementPtr: {
00648       for (Value *Operand : I->operands()) {
00649         if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
00650           return false;
00651       }
00652       return true;
00653     }
00654     case Instruction::InsertElement: {
00655       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
00656       if (!CI) return false;
00657       int ElementNumber = CI->getLimitedValue();
00658 
00659       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
00660       // can't put an element into multiple indices.
00661       bool SeenOnce = false;
00662       for (int i = 0, e = Mask.size(); i != e; ++i) {
00663         if (Mask[i] == ElementNumber) {
00664           if (SeenOnce)
00665             return false;
00666           SeenOnce = true;
00667         }
00668       }
00669       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
00670     }
00671   }
00672   return false;
00673 }
00674 
00675 /// Rebuild a new instruction just like 'I' but with the new operands given.
00676 /// In the event of type mismatch, the type of the operands is correct.
00677 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
00678   // We don't want to use the IRBuilder here because we want the replacement
00679   // instructions to appear next to 'I', not the builder's insertion point.
00680   switch (I->getOpcode()) {
00681     case Instruction::Add:
00682     case Instruction::FAdd:
00683     case Instruction::Sub:
00684     case Instruction::FSub:
00685     case Instruction::Mul:
00686     case Instruction::FMul:
00687     case Instruction::UDiv:
00688     case Instruction::SDiv:
00689     case Instruction::FDiv:
00690     case Instruction::URem:
00691     case Instruction::SRem:
00692     case Instruction::FRem:
00693     case Instruction::Shl:
00694     case Instruction::LShr:
00695     case Instruction::AShr:
00696     case Instruction::And:
00697     case Instruction::Or:
00698     case Instruction::Xor: {
00699       BinaryOperator *BO = cast<BinaryOperator>(I);
00700       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
00701       BinaryOperator *New =
00702           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
00703                                  NewOps[0], NewOps[1], "", BO);
00704       if (isa<OverflowingBinaryOperator>(BO)) {
00705         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
00706         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
00707       }
00708       if (isa<PossiblyExactOperator>(BO)) {
00709         New->setIsExact(BO->isExact());
00710       }
00711       if (isa<FPMathOperator>(BO))
00712         New->copyFastMathFlags(I);
00713       return New;
00714     }
00715     case Instruction::ICmp:
00716       assert(NewOps.size() == 2 && "icmp with #ops != 2");
00717       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
00718                           NewOps[0], NewOps[1]);
00719     case Instruction::FCmp:
00720       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
00721       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
00722                           NewOps[0], NewOps[1]);
00723     case Instruction::Trunc:
00724     case Instruction::ZExt:
00725     case Instruction::SExt:
00726     case Instruction::FPToUI:
00727     case Instruction::FPToSI:
00728     case Instruction::UIToFP:
00729     case Instruction::SIToFP:
00730     case Instruction::FPTrunc:
00731     case Instruction::FPExt: {
00732       // It's possible that the mask has a different number of elements from
00733       // the original cast. We recompute the destination type to match the mask.
00734       Type *DestTy =
00735           VectorType::get(I->getType()->getScalarType(),
00736                           NewOps[0]->getType()->getVectorNumElements());
00737       assert(NewOps.size() == 1 && "cast with #ops != 1");
00738       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
00739                               "", I);
00740     }
00741     case Instruction::GetElementPtr: {
00742       Value *Ptr = NewOps[0];
00743       ArrayRef<Value*> Idx = NewOps.slice(1);
00744       GetElementPtrInst *GEP = GetElementPtrInst::Create(
00745           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
00746       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
00747       return GEP;
00748     }
00749   }
00750   llvm_unreachable("failed to rebuild vector instructions");
00751 }
00752 
00753 Value *
00754 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
00755   // Mask.size() does not need to be equal to the number of vector elements.
00756 
00757   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
00758   if (isa<UndefValue>(V)) {
00759     return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
00760                                            Mask.size()));
00761   }
00762   if (isa<ConstantAggregateZero>(V)) {
00763     return ConstantAggregateZero::get(
00764                VectorType::get(V->getType()->getScalarType(),
00765                                Mask.size()));
00766   }
00767   if (Constant *C = dyn_cast<Constant>(V)) {
00768     SmallVector<Constant *, 16> MaskValues;
00769     for (int i = 0, e = Mask.size(); i != e; ++i) {
00770       if (Mask[i] == -1)
00771         MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
00772       else
00773         MaskValues.push_back(Builder->getInt32(Mask[i]));
00774     }
00775     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
00776                                           ConstantVector::get(MaskValues));
00777   }
00778 
00779   Instruction *I = cast<Instruction>(V);
00780   switch (I->getOpcode()) {
00781     case Instruction::Add:
00782     case Instruction::FAdd:
00783     case Instruction::Sub:
00784     case Instruction::FSub:
00785     case Instruction::Mul:
00786     case Instruction::FMul:
00787     case Instruction::UDiv:
00788     case Instruction::SDiv:
00789     case Instruction::FDiv:
00790     case Instruction::URem:
00791     case Instruction::SRem:
00792     case Instruction::FRem:
00793     case Instruction::Shl:
00794     case Instruction::LShr:
00795     case Instruction::AShr:
00796     case Instruction::And:
00797     case Instruction::Or:
00798     case Instruction::Xor:
00799     case Instruction::ICmp:
00800     case Instruction::FCmp:
00801     case Instruction::Trunc:
00802     case Instruction::ZExt:
00803     case Instruction::SExt:
00804     case Instruction::FPToUI:
00805     case Instruction::FPToSI:
00806     case Instruction::UIToFP:
00807     case Instruction::SIToFP:
00808     case Instruction::FPTrunc:
00809     case Instruction::FPExt:
00810     case Instruction::Select:
00811     case Instruction::GetElementPtr: {
00812       SmallVector<Value*, 8> NewOps;
00813       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
00814       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
00815         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
00816         NewOps.push_back(V);
00817         NeedsRebuild |= (V != I->getOperand(i));
00818       }
00819       if (NeedsRebuild) {
00820         return buildNew(I, NewOps);
00821       }
00822       return I;
00823     }
00824     case Instruction::InsertElement: {
00825       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
00826 
00827       // The insertelement was inserting at Element. Figure out which element
00828       // that becomes after shuffling. The answer is guaranteed to be unique
00829       // by CanEvaluateShuffled.
00830       bool Found = false;
00831       int Index = 0;
00832       for (int e = Mask.size(); Index != e; ++Index) {
00833         if (Mask[Index] == Element) {
00834           Found = true;
00835           break;
00836         }
00837       }
00838 
00839       // If element is not in Mask, no need to handle the operand 1 (element to
00840       // be inserted). Just evaluate values in operand 0 according to Mask.
00841       if (!Found)
00842         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
00843 
00844       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
00845       return InsertElementInst::Create(V, I->getOperand(1),
00846                                        Builder->getInt32(Index), "", I);
00847     }
00848   }
00849   llvm_unreachable("failed to reorder elements of vector instruction!");
00850 }
00851 
00852 static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
00853                                   bool &isLHSID, bool &isRHSID) {
00854   isLHSID = isRHSID = true;
00855 
00856   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
00857     if (Mask[i] < 0) continue;  // Ignore undef values.
00858     // Is this an identity shuffle of the LHS value?
00859     isLHSID &= (Mask[i] == (int)i);
00860 
00861     // Is this an identity shuffle of the RHS value?
00862     isRHSID &= (Mask[i]-e == i);
00863   }
00864 }
00865 
00866 // Returns true if the shuffle is extracting a contiguous range of values from
00867 // LHS, for example:
00868 //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
00869 //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
00870 //   Shuffles to:  |EE|FF|GG|HH|
00871 //                 +--+--+--+--+
00872 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
00873                                        SmallVector<int, 16> &Mask) {
00874   unsigned LHSElems =
00875       cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
00876   unsigned MaskElems = Mask.size();
00877   unsigned BegIdx = Mask.front();
00878   unsigned EndIdx = Mask.back();
00879   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
00880     return false;
00881   for (unsigned I = 0; I != MaskElems; ++I)
00882     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
00883       return false;
00884   return true;
00885 }
00886 
00887 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
00888   Value *LHS = SVI.getOperand(0);
00889   Value *RHS = SVI.getOperand(1);
00890   SmallVector<int, 16> Mask = SVI.getShuffleMask();
00891   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
00892 
00893   bool MadeChange = false;
00894 
00895   // Undefined shuffle mask -> undefined value.
00896   if (isa<UndefValue>(SVI.getOperand(2)))
00897     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
00898 
00899   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
00900 
00901   APInt UndefElts(VWidth, 0);
00902   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
00903   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
00904     if (V != &SVI)
00905       return ReplaceInstUsesWith(SVI, V);
00906     LHS = SVI.getOperand(0);
00907     RHS = SVI.getOperand(1);
00908     MadeChange = true;
00909   }
00910 
00911   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
00912 
00913   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
00914   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
00915   if (LHS == RHS || isa<UndefValue>(LHS)) {
00916     if (isa<UndefValue>(LHS) && LHS == RHS) {
00917       // shuffle(undef,undef,mask) -> undef.
00918       Value *Result = (VWidth == LHSWidth)
00919                       ? LHS : UndefValue::get(SVI.getType());
00920       return ReplaceInstUsesWith(SVI, Result);
00921     }
00922 
00923     // Remap any references to RHS to use LHS.
00924     SmallVector<Constant*, 16> Elts;
00925     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
00926       if (Mask[i] < 0) {
00927         Elts.push_back(UndefValue::get(Int32Ty));
00928         continue;
00929       }
00930 
00931       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
00932           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
00933         Mask[i] = -1;     // Turn into undef.
00934         Elts.push_back(UndefValue::get(Int32Ty));
00935       } else {
00936         Mask[i] = Mask[i] % e;  // Force to LHS.
00937         Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
00938       }
00939     }
00940     SVI.setOperand(0, SVI.getOperand(1));
00941     SVI.setOperand(1, UndefValue::get(RHS->getType()));
00942     SVI.setOperand(2, ConstantVector::get(Elts));
00943     LHS = SVI.getOperand(0);
00944     RHS = SVI.getOperand(1);
00945     MadeChange = true;
00946   }
00947 
00948   if (VWidth == LHSWidth) {
00949     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
00950     bool isLHSID, isRHSID;
00951     recognizeIdentityMask(Mask, isLHSID, isRHSID);
00952 
00953     // Eliminate identity shuffles.
00954     if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
00955     if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
00956   }
00957 
00958   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
00959     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
00960     return ReplaceInstUsesWith(SVI, V);
00961   }
00962 
00963   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
00964   // a non-vector type. We can instead bitcast the original vector followed by
00965   // an extract of the desired element:
00966   //
00967   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
00968   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
00969   //   %1 = bitcast <4 x i8> %sroa to i32
00970   // Becomes:
00971   //   %bc = bitcast <16 x i8> %in to <4 x i32>
00972   //   %ext = extractelement <4 x i32> %bc, i32 0
00973   //
00974   // If the shuffle is extracting a contiguous range of values from the input
00975   // vector then each use which is a bitcast of the extracted size can be
00976   // replaced. This will work if the vector types are compatible, and the begin
00977   // index is aligned to a value in the casted vector type. If the begin index
00978   // isn't aligned then we can shuffle the original vector (keeping the same
00979   // vector type) before extracting.
00980   //
00981   // This code will bail out if the target type is fundamentally incompatible
00982   // with vectors of the source type.
00983   //
00984   // Example of <16 x i8>, target type i32:
00985   // Index range [4,8):         v-----------v Will work.
00986   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
00987   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
00988   //     <4 x i32>: |           |           |           |           |
00989   //                +-----------+-----------+-----------+-----------+
00990   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
00991   // Target type i40:           ^--------------^ Won't work, bail.
00992   if (isShuffleExtractingFromLHS(SVI, Mask)) {
00993     Value *V = LHS;
00994     unsigned MaskElems = Mask.size();
00995     unsigned BegIdx = Mask.front();
00996     VectorType *SrcTy = cast<VectorType>(V->getType());
00997     unsigned VecBitWidth = SrcTy->getBitWidth();
00998     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
00999     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
01000     unsigned SrcNumElems = SrcTy->getNumElements();
01001     SmallVector<BitCastInst *, 8> BCs;
01002     DenseMap<Type *, Value *> NewBCs;
01003     for (User *U : SVI.users())
01004       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
01005         if (!BC->use_empty())
01006           // Only visit bitcasts that weren't previously handled.
01007           BCs.push_back(BC);
01008     for (BitCastInst *BC : BCs) {
01009       Type *TgtTy = BC->getDestTy();
01010       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
01011       if (!TgtElemBitWidth)
01012         continue;
01013       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
01014       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
01015       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
01016       if (!VecBitWidthsEqual)
01017         continue;
01018       if (!VectorType::isValidElementType(TgtTy))
01019         continue;
01020       VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
01021       if (!BegIsAligned) {
01022         // Shuffle the input so [0,NumElements) contains the output, and
01023         // [NumElems,SrcNumElems) is undef.
01024         SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
01025                                                 UndefValue::get(Int32Ty));
01026         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
01027           ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
01028         V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
01029                                          ConstantVector::get(ShuffleMask),
01030                                          SVI.getName() + ".extract");
01031         BegIdx = 0;
01032       }
01033       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
01034       assert(SrcElemsPerTgtElem);
01035       BegIdx /= SrcElemsPerTgtElem;
01036       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
01037       auto *NewBC =
01038           BCAlreadyExists
01039               ? NewBCs[CastSrcTy]
01040               : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
01041       if (!BCAlreadyExists)
01042         NewBCs[CastSrcTy] = NewBC;
01043       auto *Ext = Builder->CreateExtractElement(
01044           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
01045       // The shufflevector isn't being replaced: the bitcast that used it
01046       // is. InstCombine will visit the newly-created instructions.
01047       ReplaceInstUsesWith(*BC, Ext);
01048       MadeChange = true;
01049     }
01050   }
01051 
01052   // If the LHS is a shufflevector itself, see if we can combine it with this
01053   // one without producing an unusual shuffle.
01054   // Cases that might be simplified:
01055   // 1.
01056   // x1=shuffle(v1,v2,mask1)
01057   //  x=shuffle(x1,undef,mask)
01058   //        ==>
01059   //  x=shuffle(v1,undef,newMask)
01060   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
01061   // 2.
01062   // x1=shuffle(v1,undef,mask1)
01063   //  x=shuffle(x1,x2,mask)
01064   // where v1.size() == mask1.size()
01065   //        ==>
01066   //  x=shuffle(v1,x2,newMask)
01067   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
01068   // 3.
01069   // x2=shuffle(v2,undef,mask2)
01070   //  x=shuffle(x1,x2,mask)
01071   // where v2.size() == mask2.size()
01072   //        ==>
01073   //  x=shuffle(x1,v2,newMask)
01074   // newMask[i] = (mask[i] < x1.size())
01075   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
01076   // 4.
01077   // x1=shuffle(v1,undef,mask1)
01078   // x2=shuffle(v2,undef,mask2)
01079   //  x=shuffle(x1,x2,mask)
01080   // where v1.size() == v2.size()
01081   //        ==>
01082   //  x=shuffle(v1,v2,newMask)
01083   // newMask[i] = (mask[i] < x1.size())
01084   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
01085   //
01086   // Here we are really conservative:
01087   // we are absolutely afraid of producing a shuffle mask not in the input
01088   // program, because the code gen may not be smart enough to turn a merged
01089   // shuffle into two specific shuffles: it may produce worse code.  As such,
01090   // we only merge two shuffles if the result is either a splat or one of the
01091   // input shuffle masks.  In this case, merging the shuffles just removes
01092   // one instruction, which we know is safe.  This is good for things like
01093   // turning: (splat(splat)) -> splat, or
01094   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
01095   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
01096   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
01097   if (LHSShuffle)
01098     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
01099       LHSShuffle = nullptr;
01100   if (RHSShuffle)
01101     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
01102       RHSShuffle = nullptr;
01103   if (!LHSShuffle && !RHSShuffle)
01104     return MadeChange ? &SVI : nullptr;
01105 
01106   Value* LHSOp0 = nullptr;
01107   Value* LHSOp1 = nullptr;
01108   Value* RHSOp0 = nullptr;
01109   unsigned LHSOp0Width = 0;
01110   unsigned RHSOp0Width = 0;
01111   if (LHSShuffle) {
01112     LHSOp0 = LHSShuffle->getOperand(0);
01113     LHSOp1 = LHSShuffle->getOperand(1);
01114     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
01115   }
01116   if (RHSShuffle) {
01117     RHSOp0 = RHSShuffle->getOperand(0);
01118     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
01119   }
01120   Value* newLHS = LHS;
01121   Value* newRHS = RHS;
01122   if (LHSShuffle) {
01123     // case 1
01124     if (isa<UndefValue>(RHS)) {
01125       newLHS = LHSOp0;
01126       newRHS = LHSOp1;
01127     }
01128     // case 2 or 4
01129     else if (LHSOp0Width == LHSWidth) {
01130       newLHS = LHSOp0;
01131     }
01132   }
01133   // case 3 or 4
01134   if (RHSShuffle && RHSOp0Width == LHSWidth) {
01135     newRHS = RHSOp0;
01136   }
01137   // case 4
01138   if (LHSOp0 == RHSOp0) {
01139     newLHS = LHSOp0;
01140     newRHS = nullptr;
01141   }
01142 
01143   if (newLHS == LHS && newRHS == RHS)
01144     return MadeChange ? &SVI : nullptr;
01145 
01146   SmallVector<int, 16> LHSMask;
01147   SmallVector<int, 16> RHSMask;
01148   if (newLHS != LHS)
01149     LHSMask = LHSShuffle->getShuffleMask();
01150   if (RHSShuffle && newRHS != RHS)
01151     RHSMask = RHSShuffle->getShuffleMask();
01152 
01153   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
01154   SmallVector<int, 16> newMask;
01155   bool isSplat = true;
01156   int SplatElt = -1;
01157   // Create a new mask for the new ShuffleVectorInst so that the new
01158   // ShuffleVectorInst is equivalent to the original one.
01159   for (unsigned i = 0; i < VWidth; ++i) {
01160     int eltMask;
01161     if (Mask[i] < 0) {
01162       // This element is an undef value.
01163       eltMask = -1;
01164     } else if (Mask[i] < (int)LHSWidth) {
01165       // This element is from left hand side vector operand.
01166       //
01167       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
01168       // new mask value for the element.
01169       if (newLHS != LHS) {
01170         eltMask = LHSMask[Mask[i]];
01171         // If the value selected is an undef value, explicitly specify it
01172         // with a -1 mask value.
01173         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
01174           eltMask = -1;
01175       } else
01176         eltMask = Mask[i];
01177     } else {
01178       // This element is from right hand side vector operand
01179       //
01180       // If the value selected is an undef value, explicitly specify it
01181       // with a -1 mask value. (case 1)
01182       if (isa<UndefValue>(RHS))
01183         eltMask = -1;
01184       // If RHS is going to be replaced (case 3 or 4), calculate the
01185       // new mask value for the element.
01186       else if (newRHS != RHS) {
01187         eltMask = RHSMask[Mask[i]-LHSWidth];
01188         // If the value selected is an undef value, explicitly specify it
01189         // with a -1 mask value.
01190         if (eltMask >= (int)RHSOp0Width) {
01191           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
01192                  && "should have been check above");
01193           eltMask = -1;
01194         }
01195       } else
01196         eltMask = Mask[i]-LHSWidth;
01197 
01198       // If LHS's width is changed, shift the mask value accordingly.
01199       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
01200       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
01201       // If newRHS == newLHS, we want to remap any references from newRHS to
01202       // newLHS so that we can properly identify splats that may occur due to
01203       // obfuscation across the two vectors.
01204       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
01205         eltMask += newLHSWidth;
01206     }
01207 
01208     // Check if this could still be a splat.
01209     if (eltMask >= 0) {
01210       if (SplatElt >= 0 && SplatElt != eltMask)
01211         isSplat = false;
01212       SplatElt = eltMask;
01213     }
01214 
01215     newMask.push_back(eltMask);
01216   }
01217 
01218   // If the result mask is equal to one of the original shuffle masks,
01219   // or is a splat, do the replacement.
01220   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
01221     SmallVector<Constant*, 16> Elts;
01222     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
01223       if (newMask[i] < 0) {
01224         Elts.push_back(UndefValue::get(Int32Ty));
01225       } else {
01226         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
01227       }
01228     }
01229     if (!newRHS)
01230       newRHS = UndefValue::get(newLHS->getType());
01231     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
01232   }
01233 
01234   // If the result mask is an identity, replace uses of this instruction with
01235   // corresponding argument.
01236   bool isLHSID, isRHSID;
01237   recognizeIdentityMask(newMask, isLHSID, isRHSID);
01238   if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
01239   if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
01240 
01241   return MadeChange ? &SVI : nullptr;
01242 }