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