blob: e76f41b4794c4131c170753285bae963f1c63f9d [file] [log] [blame]
Chris Lattnerec97a902010-01-05 05:36:20 +00001//===- InstCombineVectorOps.cpp -------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerec97a902010-01-05 05:36:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements instcombine for ExtractElement, InsertElement and
10// ShuffleVector.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
JF Bastiend52c9902015-02-25 22:30:51 +000017#include "llvm/ADT/DenseMap.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000018#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
David Majnemer599ca442015-07-13 01:15:53 +000020#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/VectorUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000022#include "llvm/IR/BasicBlock.h"
23#include "llvm/IR/Constant.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/InstrTypes.h"
27#include "llvm/IR/Instruction.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000030#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000031#include "llvm/IR/Type.h"
32#include "llvm/IR/User.h"
33#include "llvm/IR/Value.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
37#include <cassert>
38#include <cstdint>
39#include <iterator>
40#include <utility>
41
Chris Lattnerec97a902010-01-05 05:36:20 +000042using namespace llvm;
Nadav Rotem7df85092013-01-15 23:43:14 +000043using namespace PatternMatch;
Chris Lattnerec97a902010-01-05 05:36:20 +000044
Chandler Carruth964daaa2014-04-22 02:55:47 +000045#define DEBUG_TYPE "instcombine"
46
Sanjay Patel6eccf482015-09-09 15:24:36 +000047/// Return true if the value is cheaper to scalarize than it is to leave as a
Sanjay Patele51d5bd2018-12-18 19:07:38 +000048/// vector operation. IsConstantExtractIndex indicates whether we are extracting
49/// one known element from a vector constant.
50///
51/// FIXME: It's possible to create more instructions than previously existed.
52static bool cheapToScalarize(Value *V, bool IsConstantExtractIndex) {
53 // If we can pick a scalar constant value out of a vector, that is free.
54 if (auto *C = dyn_cast<Constant>(V))
55 return IsConstantExtractIndex || C->getSplatValue();
Chris Lattner8326bd82012-01-26 00:42:34 +000056
Sanjay Patele51d5bd2018-12-18 19:07:38 +000057 // An insertelement to the same constant index as our extract will simplify
58 // to the scalar inserted element. An insertelement to a different constant
59 // index is irrelevant to our extract.
60 if (match(V, m_InsertElement(m_Value(), m_Value(), m_ConstantInt())))
61 return IsConstantExtractIndex;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000062
Sanjay Patele51d5bd2018-12-18 19:07:38 +000063 if (match(V, m_OneUse(m_Load(m_Value()))))
Chris Lattnerec97a902010-01-05 05:36:20 +000064 return true;
Sanjay Patele51d5bd2018-12-18 19:07:38 +000065
66 Value *V0, *V1;
67 if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
68 if (cheapToScalarize(V0, IsConstantExtractIndex) ||
69 cheapToScalarize(V1, IsConstantExtractIndex))
Chris Lattnerec97a902010-01-05 05:36:20 +000070 return true;
Sanjay Patele51d5bd2018-12-18 19:07:38 +000071
72 CmpInst::Predicate UnusedPred;
73 if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
74 if (cheapToScalarize(V0, IsConstantExtractIndex) ||
75 cheapToScalarize(V1, IsConstantExtractIndex))
Chris Lattnerec97a902010-01-05 05:36:20 +000076 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000077
Chris Lattnerec97a902010-01-05 05:36:20 +000078 return false;
79}
80
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000081// If we have a PHI node with a vector type that is only used to feed
Matt Arsenault38874732013-08-28 22:17:26 +000082// itself and be an operand of extractelement at a constant location,
83// try to replace the PHI of the vector type with a PHI of a scalar type.
Anat Shemer0c95efa2013-04-18 19:35:39 +000084Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000085 SmallVector<Instruction *, 2> Extracts;
86 // The users we want the PHI to have are:
87 // 1) The EI ExtractElement (we already know this)
88 // 2) Possibly more ExtractElements with the same index.
89 // 3) Another operand, which will feed back into the PHI.
90 Instruction *PHIUser = nullptr;
91 for (auto U : PN->users()) {
92 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
93 if (EI.getIndexOperand() == EU->getIndexOperand())
94 Extracts.push_back(EU);
95 else
96 return nullptr;
97 } else if (!PHIUser) {
98 PHIUser = cast<Instruction>(U);
99 } else {
100 return nullptr;
101 }
102 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000103
Michael Kupersteina0c6ae02016-06-06 23:38:33 +0000104 if (!PHIUser)
105 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000106
107 // Verify that this PHI user has one use, which is the PHI itself,
108 // and that it is a binary operation which is cheap to scalarize.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000109 // otherwise return nullptr.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000110 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
Sanjay Patel431e1142015-11-17 17:24:08 +0000111 !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
Craig Topperf40110f2014-04-25 05:29:35 +0000112 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000113
114 // Create a scalar PHI node that will replace the vector PHI node
115 // just before the current PHI node.
Joey Goulyb34294d2013-05-24 12:33:28 +0000116 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
117 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
Anat Shemer0c95efa2013-04-18 19:35:39 +0000118 // Scalarize each PHI operand.
Joey Goulyb34294d2013-05-24 12:33:28 +0000119 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
Anat Shemer0c95efa2013-04-18 19:35:39 +0000120 Value *PHIInVal = PN->getIncomingValue(i);
121 BasicBlock *inBB = PN->getIncomingBlock(i);
122 Value *Elt = EI.getIndexOperand();
123 // If the operand is the PHI induction variable:
124 if (PHIInVal == PHIUser) {
125 // Scalarize the binary operation. Its first operand is the
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000126 // scalar PHI, and the second operand is extracted from the other
Anat Shemer0c95efa2013-04-18 19:35:39 +0000127 // vector operand.
128 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
Joey Goulyb34294d2013-05-24 12:33:28 +0000129 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
Joey Gouly83699282013-05-24 12:29:54 +0000130 Value *Op = InsertNewInstWith(
131 ExtractElementInst::Create(B0->getOperand(opId), Elt,
132 B0->getOperand(opId)->getName() + ".Elt"),
133 *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000134 Value *newPHIUser = InsertNewInstWith(
Owen Anderson7ea02fc2016-03-01 19:35:52 +0000135 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
136 scalarPHI, Op, B0), *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000137 scalarPHI->addIncoming(newPHIUser, inBB);
138 } else {
139 // Scalarize PHI input:
Joey Goulyb34294d2013-05-24 12:33:28 +0000140 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
Anat Shemer0c95efa2013-04-18 19:35:39 +0000141 // Insert the new instruction into the predecessor basic block.
142 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
143 BasicBlock::iterator InsertPos;
144 if (pos && !isa<PHINode>(pos)) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000145 InsertPos = ++pos->getIterator();
Anat Shemer0c95efa2013-04-18 19:35:39 +0000146 } else {
147 InsertPos = inBB->getFirstInsertionPt();
148 }
149
150 InsertNewInstWith(newEI, *InsertPos);
151
152 scalarPHI->addIncoming(newEI, inBB);
153 }
154 }
Michael Kupersteina0c6ae02016-06-06 23:38:33 +0000155
156 for (auto E : Extracts)
157 replaceInstUsesWith(*E, scalarPHI);
158
159 return &EI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000160}
161
Sanjay Patel4674c772018-09-24 20:41:22 +0000162static Instruction *foldBitcastExtElt(ExtractElementInst &Ext,
Sanjay Patel31b07192018-10-01 14:40:00 +0000163 InstCombiner::BuilderTy &Builder,
164 bool IsBigEndian) {
Sanjay Patel4674c772018-09-24 20:41:22 +0000165 Value *X;
166 uint64_t ExtIndexC;
167 if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
168 !X->getType()->isVectorTy() ||
169 !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
170 return nullptr;
171
172 // If this extractelement is using a bitcast from a vector of the same number
173 // of elements, see if we can find the source element from the source vector:
174 // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
175 Type *SrcTy = X->getType();
176 Type *DestTy = Ext.getType();
177 unsigned NumSrcElts = SrcTy->getVectorNumElements();
178 unsigned NumElts = Ext.getVectorOperandType()->getNumElements();
179 if (NumSrcElts == NumElts)
180 if (Value *Elt = findScalarElement(X, ExtIndexC))
181 return new BitCastInst(Elt, DestTy);
182
Sanjay Patel31b07192018-10-01 14:40:00 +0000183 // If the source elements are wider than the destination, try to shift and
184 // truncate a subset of scalar bits of an insert op.
Sanjay Patel3746e112018-10-04 16:25:05 +0000185 if (NumSrcElts < NumElts) {
Sanjay Patel31b07192018-10-01 14:40:00 +0000186 Value *Scalar;
187 uint64_t InsIndexC;
188 if (!match(X, m_InsertElement(m_Value(), m_Value(Scalar),
189 m_ConstantInt(InsIndexC))))
190 return nullptr;
191
192 // The extract must be from the subset of vector elements that we inserted
193 // into. Example: if we inserted element 1 of a <2 x i64> and we are
194 // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
195 // of elements 4-7 of the bitcasted vector.
196 unsigned NarrowingRatio = NumElts / NumSrcElts;
197 if (ExtIndexC / NarrowingRatio != InsIndexC)
198 return nullptr;
199
200 // We are extracting part of the original scalar. How that scalar is
201 // inserted into the vector depends on the endian-ness. Example:
202 // Vector Byte Elt Index: 0 1 2 3 4 5 6 7
203 // +--+--+--+--+--+--+--+--+
204 // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3|
205 // extelt <4 x i16> V', 3: | |S2|S3|
206 // +--+--+--+--+--+--+--+--+
207 // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
208 // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
209 // In this example, we must right-shift little-endian. Big-endian is just a
210 // truncate.
211 unsigned Chunk = ExtIndexC % NarrowingRatio;
212 if (IsBigEndian)
213 Chunk = NarrowingRatio - 1 - Chunk;
Sanjay Patel3746e112018-10-04 16:25:05 +0000214
215 // Bail out if this is an FP vector to FP vector sequence. That would take
216 // more instructions than we started with unless there is no shift, and it
217 // may not be handled as well in the backend.
218 bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
219 bool NeedDestBitcast = DestTy->isFloatingPointTy();
220 if (NeedSrcBitcast && NeedDestBitcast)
221 return nullptr;
222
223 unsigned SrcWidth = SrcTy->getScalarSizeInBits();
224 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
225 unsigned ShAmt = Chunk * DestWidth;
226
227 // TODO: This limitation is more strict than necessary. We could sum the
228 // number of new instructions and subtract the number eliminated to know if
229 // we can proceed.
230 if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
231 if (NeedSrcBitcast || NeedDestBitcast)
232 return nullptr;
233
234 if (NeedSrcBitcast) {
235 Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
236 Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
237 }
238
Sanjay Patel31b07192018-10-01 14:40:00 +0000239 if (ShAmt) {
240 // Bail out if we could end with more instructions than we started with.
241 if (!Ext.getVectorOperand()->hasOneUse())
242 return nullptr;
243 Scalar = Builder.CreateLShr(Scalar, ShAmt);
244 }
Sanjay Patel3746e112018-10-04 16:25:05 +0000245
246 if (NeedDestBitcast) {
247 Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
248 return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
249 }
Sanjay Patel31b07192018-10-01 14:40:00 +0000250 return new TruncInst(Scalar, DestTy);
251 }
252
Sanjay Patel4674c772018-09-24 20:41:22 +0000253 return nullptr;
254}
255
Chris Lattnerec97a902010-01-05 05:36:20 +0000256Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000257 Value *SrcVec = EI.getVectorOperand();
258 Value *Index = EI.getIndexOperand();
259 if (Value *V = SimplifyExtractElementInst(SrcVec, Index,
Craig Toppera4205622017-06-09 03:21:29 +0000260 SQ.getWithInstruction(&EI)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000261 return replaceInstUsesWith(EI, V);
David Majnemer599ca442015-07-13 01:15:53 +0000262
Chris Lattnerec97a902010-01-05 05:36:20 +0000263 // If extracting a specified index from the vector, see if we can recursively
264 // find a previously computed scalar that was inserted into the vector.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000265 auto *IndexC = dyn_cast<ConstantInt>(Index);
266 if (IndexC) {
Sanjay Patel7a526262018-09-24 16:39:03 +0000267 unsigned NumElts = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000268
Simon Pilgrime7d032f2017-12-27 12:00:18 +0000269 // InstSimplify should handle cases where the index is invalid.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000270 if (!IndexC->getValue().ule(NumElts))
Simon Pilgrime7d032f2017-12-27 12:00:18 +0000271 return nullptr;
272
Chris Lattnerec97a902010-01-05 05:36:20 +0000273 // This instruction only demands the single element from the input vector.
274 // If the input vector has a single use, simplify it based on this use
275 // property.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000276 if (SrcVec->hasOneUse() && NumElts != 1) {
Sanjay Patel7a526262018-09-24 16:39:03 +0000277 APInt UndefElts(NumElts, 0);
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000278 APInt DemandedElts(NumElts, 0);
279 DemandedElts.setBit(IndexC->getZExtValue());
280 if (Value *V = SimplifyDemandedVectorElts(SrcVec, DemandedElts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000281 UndefElts)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000282 EI.setOperand(0, V);
283 return &EI;
284 }
285 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000286
Sanjay Patel31b07192018-10-01 14:40:00 +0000287 if (Instruction *I = foldBitcastExtElt(EI, Builder, DL.isBigEndian()))
Sanjay Patel4674c772018-09-24 20:41:22 +0000288 return I;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000289
290 // If there's a vector PHI feeding a scalar use through this extractelement
291 // instruction, try to scalarize the PHI.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000292 if (auto *Phi = dyn_cast<PHINode>(SrcVec))
293 if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
294 return ScalarPHI;
Chris Lattnerec97a902010-01-05 05:36:20 +0000295 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000296
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000297 BinaryOperator *BO;
298 if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, IndexC)) {
299 // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
300 Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
301 Value *E0 = Builder.CreateExtractElement(X, Index);
302 Value *E1 = Builder.CreateExtractElement(Y, Index);
303 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
304 }
305
Matt Arsenault9ccde612018-12-10 21:50:54 +0000306 Value *X, *Y;
307 CmpInst::Predicate Pred;
308 if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
309 cheapToScalarize(SrcVec, IndexC)) {
310 // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
311 Value *E0 = Builder.CreateExtractElement(X, Index);
312 Value *E1 = Builder.CreateExtractElement(Y, Index);
313 return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1);
314 }
315
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000316 if (auto *I = dyn_cast<Instruction>(SrcVec)) {
317 if (auto *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000318 // Extracting the inserted element?
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000319 if (IE->getOperand(2) == Index)
Sanjay Patel4b198802016-02-01 22:23:39 +0000320 return replaceInstUsesWith(EI, IE->getOperand(1));
Chris Lattnerec97a902010-01-05 05:36:20 +0000321 // If the inserted and extracted elements are constants, they must not
322 // be the same value, extract from the pre-inserted value instead.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000323 if (isa<Constant>(IE->getOperand(2)) && IndexC) {
324 Worklist.AddValue(SrcVec);
Chris Lattnerec97a902010-01-05 05:36:20 +0000325 EI.setOperand(0, IE->getOperand(0));
326 return &EI;
327 }
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000328 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000329 // If this is extracting an element from a shufflevector, figure out where
330 // it came from and extract from the appropriate input element instead.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000331 if (auto *Elt = dyn_cast<ConstantInt>(Index)) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000332 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000333 Value *Src;
334 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000335 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000336
Bob Wilson11ee4562010-10-29 22:03:05 +0000337 if (SrcIdx < 0)
Sanjay Patel4b198802016-02-01 22:23:39 +0000338 return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson11ee4562010-10-29 22:03:05 +0000339 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000340 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000341 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000342 SrcIdx -= LHSWidth;
343 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000344 }
Chris Lattner229907c2011-07-18 04:54:35 +0000345 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000346 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000347 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000348 SrcIdx, false));
349 }
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000350 } else if (auto *CI = dyn_cast<CastInst>(I)) {
Sanjay Patelb67076c2015-11-29 22:09:34 +0000351 // Canonicalize extractelement(cast) -> cast(extractelement).
352 // Bitcasts can change the number of vector elements, and they cost
353 // nothing.
Anat Shemer55703182013-04-18 19:56:44 +0000354 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000355 Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
Anat Shemer10260a72013-04-22 20:51:10 +0000356 Worklist.AddValue(EE);
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000357 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
358 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000359 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000360 }
Craig Topperf40110f2014-04-25 05:29:35 +0000361 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000362}
363
Sanjay Patel6eccf482015-09-09 15:24:36 +0000364/// If V is a shuffle of values that ONLY returns elements from either LHS or
365/// RHS, return the shuffle mask and true. Otherwise, return false.
Sanjay Patel431e1142015-11-17 17:24:08 +0000366static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner0256be92012-01-27 03:08:05 +0000367 SmallVectorImpl<Constant*> &Mask) {
Tim Northoverfad27612014-03-07 10:24:44 +0000368 assert(LHS->getType() == RHS->getType() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000369 "Invalid CollectSingleShuffleElements");
Matt Arsenault8227b9f2013-09-06 00:37:24 +0000370 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000371
Chris Lattnerec97a902010-01-05 05:36:20 +0000372 if (isa<UndefValue>(V)) {
373 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
374 return true;
375 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000376
Chris Lattnerec97a902010-01-05 05:36:20 +0000377 if (V == LHS) {
378 for (unsigned i = 0; i != NumElts; ++i)
379 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
380 return true;
381 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000382
Chris Lattnerec97a902010-01-05 05:36:20 +0000383 if (V == RHS) {
384 for (unsigned i = 0; i != NumElts; ++i)
385 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
386 i+NumElts));
387 return true;
388 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000389
Chris Lattnerec97a902010-01-05 05:36:20 +0000390 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
391 // If this is an insert of an extract from some other vector, include it.
392 Value *VecOp = IEI->getOperand(0);
393 Value *ScalarOp = IEI->getOperand(1);
394 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000395
Chris Lattnerec97a902010-01-05 05:36:20 +0000396 if (!isa<ConstantInt>(IdxOp))
397 return false;
398 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000399
Chris Lattnerec97a902010-01-05 05:36:20 +0000400 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000401 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000402 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000403 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000404 // If so, update the mask to reflect the inserted undef.
405 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
406 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000407 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000408 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
Tim Northoverfad27612014-03-07 10:24:44 +0000409 if (isa<ConstantInt>(EI->getOperand(1))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000410 unsigned ExtractedIdx =
411 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Tim Northoverfad27612014-03-07 10:24:44 +0000412 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000413
Chris Lattnerec97a902010-01-05 05:36:20 +0000414 // This must be extracting from either LHS or RHS.
415 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000416 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000417 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000418 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000419 // If so, update the mask to reflect the inserted value.
420 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000421 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000422 ConstantInt::get(Type::getInt32Ty(V->getContext()),
423 ExtractedIdx);
424 } else {
425 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000426 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000427 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000428 ExtractedIdx + NumLHSElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000429 }
430 return true;
431 }
432 }
433 }
434 }
435 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000436
Chris Lattnerec97a902010-01-05 05:36:20 +0000437 return false;
438}
439
Sanjay Patelae945e72015-12-24 21:17:56 +0000440/// If we have insertion into a vector that is wider than the vector that we
441/// are extracting from, try to widen the source vector to allow a single
442/// shufflevector to replace one or more insert/extract pairs.
443static void replaceExtractElements(InsertElementInst *InsElt,
444 ExtractElementInst *ExtElt,
445 InstCombiner &IC) {
446 VectorType *InsVecType = InsElt->getType();
447 VectorType *ExtVecType = ExtElt->getVectorOperandType();
448 unsigned NumInsElts = InsVecType->getVectorNumElements();
449 unsigned NumExtElts = ExtVecType->getVectorNumElements();
450
451 // The inserted-to vector must be wider than the extracted-from vector.
452 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
453 NumExtElts >= NumInsElts)
454 return;
455
456 // Create a shuffle mask to widen the extended-from vector using undefined
457 // values. The mask selects all of the values of the original vector followed
458 // by as many undefined values as needed to create a vector of the same length
459 // as the inserted-to vector.
460 SmallVector<Constant *, 16> ExtendMask;
461 IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
462 for (unsigned i = 0; i < NumExtElts; ++i)
463 ExtendMask.push_back(ConstantInt::get(IntType, i));
464 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
465 ExtendMask.push_back(UndefValue::get(IntType));
466
467 Value *ExtVecOp = ExtElt->getVectorOperand();
Sanjay Patel66fff732016-01-29 20:21:02 +0000468 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
469 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
470 ? ExtVecOpInst->getParent()
471 : ExtElt->getParent();
472
473 // TODO: This restriction matches the basic block check below when creating
474 // new extractelement instructions. If that limitation is removed, this one
475 // could also be removed. But for now, we just bail out to ensure that we
476 // will replace the extractelement instruction that is feeding our
477 // insertelement instruction. This allows the insertelement to then be
478 // replaced by a shufflevector. If the insertelement is not replaced, we can
479 // induce infinite looping because there's an optimization for extractelement
480 // that will delete our widening shuffle. This would trigger another attempt
481 // here to create that shuffle, and we spin forever.
482 if (InsertionBlock != InsElt->getParent())
483 return;
484
Sanjay Patel4e1b5a52016-11-10 00:15:14 +0000485 // TODO: This restriction matches the check in visitInsertElementInst() and
486 // prevents an infinite loop caused by not turning the extract/insert pair
487 // into a shuffle. We really should not need either check, but we're lacking
488 // folds for shufflevectors because we're afraid to generate shuffle masks
489 // that the backend can't handle.
490 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
491 return;
492
Sanjay Patelae945e72015-12-24 21:17:56 +0000493 auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
494 ConstantVector::get(ExtendMask));
495
Sanjay Patela1c53472016-01-05 19:09:47 +0000496 // Insert the new shuffle after the vector operand of the extract is defined
Sanjay Pateld72a4582016-01-08 01:39:16 +0000497 // (as long as it's not a PHI) or at the start of the basic block of the
498 // extract, so any subsequent extracts in the same basic block can use it.
499 // TODO: Insert before the earliest ExtractElementInst that is replaced.
Sanjay Pateld72a4582016-01-08 01:39:16 +0000500 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
Sanjay Patela1c53472016-01-05 19:09:47 +0000501 WideVec->insertAfter(ExtVecOpInst);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000502 else
Sanjay Patela1c53472016-01-05 19:09:47 +0000503 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
Sanjay Patela1c53472016-01-05 19:09:47 +0000504
505 // Replace extracts from the original narrow vector with extracts from the new
506 // wide vector.
Sanjay Patelae945e72015-12-24 21:17:56 +0000507 for (User *U : ExtVecOp->users()) {
Sanjay Patela1c53472016-01-05 19:09:47 +0000508 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000509 if (!OldExt || OldExt->getParent() != WideVec->getParent())
Sanjay Patela1c53472016-01-05 19:09:47 +0000510 continue;
511 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
Sven van Haastregt78819e02017-06-05 09:18:10 +0000512 NewExt->insertAfter(OldExt);
Sanjay Patel4b198802016-02-01 22:23:39 +0000513 IC.replaceInstUsesWith(*OldExt, NewExt);
Sanjay Patelae945e72015-12-24 21:17:56 +0000514 }
515}
Tim Northoverfad27612014-03-07 10:24:44 +0000516
517/// We are building a shuffle to create V, which is a sequence of insertelement,
518/// extractelement pairs. If PermittedRHS is set, then we must either use it or
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000519/// not rely on the second vector source. Return a std::pair containing the
Tim Northoverfad27612014-03-07 10:24:44 +0000520/// left and right vectors of the proposed shuffle (or 0), and set the Mask
521/// parameter as required.
522///
523/// Note: we intentionally don't try to fold earlier shuffles since they have
524/// often been chosen carefully to be efficiently implementable on the target.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000525using ShuffleOps = std::pair<Value *, Value *>;
Tim Northoverfad27612014-03-07 10:24:44 +0000526
Sanjay Patel431e1142015-11-17 17:24:08 +0000527static ShuffleOps collectShuffleElements(Value *V,
Tim Northoverfad27612014-03-07 10:24:44 +0000528 SmallVectorImpl<Constant *> &Mask,
Sanjay Patelae945e72015-12-24 21:17:56 +0000529 Value *PermittedRHS,
530 InstCombiner &IC) {
Tim Northoverfad27612014-03-07 10:24:44 +0000531 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
Craig Topper17b55682016-12-29 07:03:18 +0000532 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000533
Chris Lattnerec97a902010-01-05 05:36:20 +0000534 if (isa<UndefValue>(V)) {
535 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Tim Northoverfad27612014-03-07 10:24:44 +0000536 return std::make_pair(
537 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000538 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000539
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000540 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000541 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Tim Northoverfad27612014-03-07 10:24:44 +0000542 return std::make_pair(V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000543 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000544
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000545 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000546 // If this is an insert of an extract from some other vector, include it.
547 Value *VecOp = IEI->getOperand(0);
548 Value *ScalarOp = IEI->getOperand(1);
549 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000550
Chris Lattnerec97a902010-01-05 05:36:20 +0000551 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000552 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000553 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000554 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000555 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000556
Chris Lattnerec97a902010-01-05 05:36:20 +0000557 // Either the extracted from or inserted into vector must be RHSVec,
558 // otherwise we'd end up with a shuffle of three inputs.
Craig Topperf40110f2014-04-25 05:29:35 +0000559 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Tim Northoverfad27612014-03-07 10:24:44 +0000560 Value *RHS = EI->getOperand(0);
Sanjay Patelae945e72015-12-24 21:17:56 +0000561 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
Craig Toppere73658d2014-04-28 04:05:08 +0000562 assert(LR.second == nullptr || LR.second == RHS);
Tim Northoverfad27612014-03-07 10:24:44 +0000563
564 if (LR.first->getType() != RHS->getType()) {
Sanjay Patelae945e72015-12-24 21:17:56 +0000565 // Although we are giving up for now, see if we can create extracts
566 // that match the inserts for another round of combining.
567 replaceExtractElements(IEI, EI, IC);
568
Tim Northoverfad27612014-03-07 10:24:44 +0000569 // We tried our best, but we can't find anything compatible with RHS
570 // further up the chain. Return a trivial shuffle.
571 for (unsigned i = 0; i < NumElts; ++i)
572 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
573 return std::make_pair(V, nullptr);
574 }
575
576 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000577 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000578 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000579 NumLHSElts+ExtractedIdx);
580 return std::make_pair(LR.first, RHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000581 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000582
Tim Northoverfad27612014-03-07 10:24:44 +0000583 if (VecOp == PermittedRHS) {
584 // We've gone as far as we can: anything on the other side of the
585 // extractelement will already have been converted into a shuffle.
586 unsigned NumLHSElts =
587 EI->getOperand(0)->getType()->getVectorNumElements();
588 for (unsigned i = 0; i != NumElts; ++i)
589 Mask.push_back(ConstantInt::get(
590 Type::getInt32Ty(V->getContext()),
591 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
592 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000593 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000594
Chris Lattnerec97a902010-01-05 05:36:20 +0000595 // If this insertelement is a chain that comes from exactly these two
596 // vectors, return the vector and the effective shuffle.
Tim Northoverfad27612014-03-07 10:24:44 +0000597 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
Sanjay Patel431e1142015-11-17 17:24:08 +0000598 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
Tim Northoverfad27612014-03-07 10:24:44 +0000599 Mask))
600 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000601 }
602 }
603 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000604
Sanjay Patelb67076c2015-11-29 22:09:34 +0000605 // Otherwise, we can't do anything fancy. Return an identity vector.
Chris Lattnerec97a902010-01-05 05:36:20 +0000606 for (unsigned i = 0; i != NumElts; ++i)
607 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Tim Northoverfad27612014-03-07 10:24:44 +0000608 return std::make_pair(V, nullptr);
Chris Lattnerec97a902010-01-05 05:36:20 +0000609}
610
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000611/// Try to find redundant insertvalue instructions, like the following ones:
612/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
613/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
614/// Here the second instruction inserts values at the same indices, as the
615/// first one, making the first one redundant.
616/// It should be transformed to:
617/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
618Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
619 bool IsRedundant = false;
620 ArrayRef<unsigned int> FirstIndices = I.getIndices();
621
622 // If there is a chain of insertvalue instructions (each of them except the
623 // last one has only one use and it's another insertvalue insn from this
624 // chain), check if any of the 'children' uses the same indices as the first
625 // instruction. In this case, the first one is redundant.
626 Value *V = &I;
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000627 unsigned Depth = 0;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000628 while (V->hasOneUse() && Depth < 10) {
629 User *U = V->user_back();
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000630 auto UserInsInst = dyn_cast<InsertValueInst>(U);
631 if (!UserInsInst || U->getOperand(0) != V)
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000632 break;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000633 if (UserInsInst->getIndices() == FirstIndices) {
634 IsRedundant = true;
635 break;
636 }
637 V = UserInsInst;
638 Depth++;
639 }
640
641 if (IsRedundant)
Sanjay Patel4b198802016-02-01 22:23:39 +0000642 return replaceInstUsesWith(I, I.getOperand(0));
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000643 return nullptr;
644}
645
Sanjay Patel521f19f2016-09-02 17:05:43 +0000646static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
647 int MaskSize = Shuf.getMask()->getType()->getVectorNumElements();
648 int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements();
649
650 // A vector select does not change the size of the operands.
651 if (MaskSize != VecSize)
652 return false;
653
654 // Each mask element must be undefined or choose a vector element from one of
655 // the source operands without crossing vector lanes.
656 for (int i = 0; i != MaskSize; ++i) {
657 int Elt = Shuf.getMaskValue(i);
658 if (Elt != -1 && Elt != i && Elt != i + VecSize)
659 return false;
660 }
661
662 return true;
663}
664
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000665// Turn a chain of inserts that splats a value into a canonical insert + shuffle
666// splat. That is:
667// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
668// shufflevector(insertelt(X, %k, 0), undef, zero)
669static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) {
670 // We are interested in the last insert in a chain. So, if this insert
671 // has a single user, and that user is an insert, bail.
672 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
673 return nullptr;
674
675 VectorType *VT = cast<VectorType>(InsElt.getType());
676 int NumElements = VT->getNumElements();
677
678 // Do not try to do this for a one-element vector, since that's a nop,
679 // and will cause an inf-loop.
680 if (NumElements == 1)
681 return nullptr;
682
683 Value *SplatVal = InsElt.getOperand(1);
Fangrui Songf78650a2018-07-30 19:41:25 +0000684 InsertElementInst *CurrIE = &InsElt;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000685 SmallVector<bool, 16> ElementPresent(NumElements, false);
Florian Hahnb992fee2017-08-30 10:54:21 +0000686 InsertElementInst *FirstIE = nullptr;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000687
688 // Walk the chain backwards, keeping track of which indices we inserted into,
689 // until we hit something that isn't an insert of the splatted value.
690 while (CurrIE) {
Sanjay Patel863d4942017-11-27 18:19:32 +0000691 auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000692 if (!Idx || CurrIE->getOperand(1) != SplatVal)
693 return nullptr;
694
Sanjay Patel863d4942017-11-27 18:19:32 +0000695 auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
Florian Hahnb992fee2017-08-30 10:54:21 +0000696 // Check none of the intermediate steps have any additional uses, except
697 // for the root insertelement instruction, which can be re-used, if it
698 // inserts at position 0.
699 if (CurrIE != &InsElt &&
700 (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000701 return nullptr;
702
703 ElementPresent[Idx->getZExtValue()] = true;
Florian Hahnb992fee2017-08-30 10:54:21 +0000704 FirstIE = CurrIE;
705 CurrIE = NextIE;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000706 }
707
708 // Make sure we've seen an insert into every element.
709 if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; }))
710 return nullptr;
711
712 // All right, create the insert + shuffle.
Florian Hahnb992fee2017-08-30 10:54:21 +0000713 Instruction *InsertFirst;
714 if (cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
715 InsertFirst = FirstIE;
716 else
717 InsertFirst = InsertElementInst::Create(
718 UndefValue::get(VT), SplatVal,
719 ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0),
720 "", &InsElt);
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000721
722 Constant *ZeroMask = ConstantAggregateZero::get(
723 VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements));
724
725 return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask);
726}
727
Sanjay Patel2f602ce2017-03-22 17:10:44 +0000728/// If we have an insertelement instruction feeding into another insertelement
729/// and the 2nd is inserting a constant into the vector, canonicalize that
730/// constant insertion before the insertion of a variable:
731///
732/// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
733/// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
734///
735/// This has the potential of eliminating the 2nd insertelement instruction
736/// via constant folding of the scalar constant into a vector constant.
737static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
738 InstCombiner::BuilderTy &Builder) {
739 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
740 if (!InsElt1 || !InsElt1->hasOneUse())
741 return nullptr;
742
743 Value *X, *Y;
744 Constant *ScalarC;
745 ConstantInt *IdxC1, *IdxC2;
746 if (match(InsElt1->getOperand(0), m_Value(X)) &&
747 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
748 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
749 match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
750 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
751 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
752 return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
753 }
754
755 return nullptr;
756}
757
Alexey Bataevfee90782016-09-23 09:14:08 +0000758/// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
759/// --> shufflevector X, CVec', Mask'
Sanjay Patel521f19f2016-09-02 17:05:43 +0000760static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
Alexey Bataevfee90782016-09-23 09:14:08 +0000761 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
762 // Bail out if the parent has more than one use. In that case, we'd be
Sanjay Patel521f19f2016-09-02 17:05:43 +0000763 // replacing the insertelt with a shuffle, and that's not a clear win.
Alexey Bataevfee90782016-09-23 09:14:08 +0000764 if (!Inst || !Inst->hasOneUse())
Sanjay Patel521f19f2016-09-02 17:05:43 +0000765 return nullptr;
Alexey Bataevfee90782016-09-23 09:14:08 +0000766 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
767 // The shuffle must have a constant vector operand. The insertelt must have
768 // a constant scalar being inserted at a constant position in the vector.
769 Constant *ShufConstVec, *InsEltScalar;
770 uint64_t InsEltIndex;
771 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
772 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
773 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
774 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000775
Alexey Bataevfee90782016-09-23 09:14:08 +0000776 // Adding an element to an arbitrary shuffle could be expensive, but a
777 // shuffle that selects elements from vectors without crossing lanes is
778 // assumed cheap.
779 // If we're just adding a constant into that shuffle, it will still be
780 // cheap.
781 if (!isShuffleEquivalentToSelect(*Shuf))
782 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000783
Alexey Bataevfee90782016-09-23 09:14:08 +0000784 // From the above 'select' check, we know that the mask has the same number
785 // of elements as the vector input operands. We also know that each constant
786 // input element is used in its lane and can not be used more than once by
787 // the shuffle. Therefore, replace the constant in the shuffle's constant
788 // vector with the insertelt constant. Replace the constant in the shuffle's
789 // mask vector with the insertelt index plus the length of the vector
790 // (because the constant vector operand of a shuffle is always the 2nd
791 // operand).
792 Constant *Mask = Shuf->getMask();
793 unsigned NumElts = Mask->getType()->getVectorNumElements();
794 SmallVector<Constant *, 16> NewShufElts(NumElts);
795 SmallVector<Constant *, 16> NewMaskElts(NumElts);
796 for (unsigned I = 0; I != NumElts; ++I) {
797 if (I == InsEltIndex) {
798 NewShufElts[I] = InsEltScalar;
799 Type *Int32Ty = Type::getInt32Ty(Shuf->getContext());
800 NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts);
801 } else {
802 // Copy over the existing values.
803 NewShufElts[I] = ShufConstVec->getAggregateElement(I);
804 NewMaskElts[I] = Mask->getAggregateElement(I);
805 }
Sanjay Patel521f19f2016-09-02 17:05:43 +0000806 }
Sanjay Patel521f19f2016-09-02 17:05:43 +0000807
Alexey Bataevfee90782016-09-23 09:14:08 +0000808 // Create new operands for a shuffle that includes the constant of the
809 // original insertelt. The old shuffle will be dead now.
810 return new ShuffleVectorInst(Shuf->getOperand(0),
811 ConstantVector::get(NewShufElts),
812 ConstantVector::get(NewMaskElts));
813 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
814 // Transform sequences of insertelements ops with constant data/indexes into
815 // a single shuffle op.
816 unsigned NumElts = InsElt.getType()->getNumElements();
817
818 uint64_t InsertIdx[2];
819 Constant *Val[2];
820 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
821 !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
822 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
823 !match(IEI->getOperand(1), m_Constant(Val[1])))
824 return nullptr;
825 SmallVector<Constant *, 16> Values(NumElts);
826 SmallVector<Constant *, 16> Mask(NumElts);
827 auto ValI = std::begin(Val);
828 // Generate new constant vector and mask.
829 // We have 2 values/masks from the insertelements instructions. Insert them
830 // into new value/mask vectors.
831 for (uint64_t I : InsertIdx) {
832 if (!Values[I]) {
833 assert(!Mask[I]);
834 Values[I] = *ValI;
835 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()),
836 NumElts + I);
837 }
838 ++ValI;
839 }
840 // Remaining values are filled with 'undef' values.
841 for (unsigned I = 0; I < NumElts; ++I) {
842 if (!Values[I]) {
843 assert(!Mask[I]);
844 Values[I] = UndefValue::get(InsElt.getType()->getElementType());
845 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I);
846 }
847 }
848 // Create new operands for a shuffle that includes the constant of the
849 // original insertelt.
850 return new ShuffleVectorInst(IEI->getOperand(0),
851 ConstantVector::get(Values),
852 ConstantVector::get(Mask));
853 }
854 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000855}
856
Chris Lattnerec97a902010-01-05 05:36:20 +0000857Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
858 Value *VecOp = IE.getOperand(0);
859 Value *ScalarOp = IE.getOperand(1);
860 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000861
Igor Laevskye0edb662017-12-13 11:21:18 +0000862 if (auto *V = SimplifyInsertElementInst(
863 VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
864 return replaceInstUsesWith(IE, V);
865
Chris Lattnerec97a902010-01-05 05:36:20 +0000866 // Inserting an undef or into an undefined place, remove this.
867 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
Sanjay Patel4b198802016-02-01 22:23:39 +0000868 replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000869
Sanjay Patel926e4772019-05-17 18:06:12 +0000870 // If the vector and scalar are both bitcast from the same element type, do
871 // the insert in that source type followed by bitcast.
872 Value *VecSrc, *ScalarSrc;
873 if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
874 match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
875 (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
876 VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
877 VecSrc->getType()->getVectorElementType() == ScalarSrc->getType()) {
878 // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
879 // bitcast (inselt VecSrc, ScalarSrc, IdxOp)
880 Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
881 return new BitCastInst(NewInsElt, IE.getType());
882 }
883
Sanjay Patel0522b0d2018-10-20 17:15:57 +0000884 // If the inserted element was extracted from some other vector and both
885 // indexes are constant, try to turn this into a shuffle.
886 uint64_t InsertedIdx, ExtractedIdx;
887 Value *ExtVecOp;
888 if (match(IdxOp, m_ConstantInt(InsertedIdx)) &&
889 match(ScalarOp, m_ExtractElement(m_Value(ExtVecOp),
890 m_ConstantInt(ExtractedIdx)))) {
891 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
892 unsigned NumExtractVectorElts = ExtVecOp->getType()->getVectorNumElements();
893 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
894 return replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000895
Sanjay Patel0522b0d2018-10-20 17:15:57 +0000896 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
897 return replaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000898
Sanjay Patel0522b0d2018-10-20 17:15:57 +0000899 // If we are extracting a value from a vector, then inserting it right
900 // back into the same place, just use the input vector.
901 if (ExtVecOp == VecOp && ExtractedIdx == InsertedIdx)
902 return replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000903
Sanjay Patel0522b0d2018-10-20 17:15:57 +0000904 // TODO: Looking at the user(s) to determine if this insert is a
905 // fold-to-shuffle opportunity does not match the usual instcombine
906 // constraints. We should decide if the transform is worthy based only
907 // on this instruction and its operands, but that may not work currently.
908 //
909 // Here, we are trying to avoid creating shuffles before reaching
910 // the end of a chain of extract-insert pairs. This is complicated because
911 // we do not generally form arbitrary shuffle masks in instcombine
912 // (because those may codegen poorly), but collectShuffleElements() does
913 // exactly that.
914 //
915 // The rules for determining what is an acceptable target-independent
916 // shuffle mask are fuzzy because they evolve based on the backend's
917 // capabilities and real-world impact.
918 auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
919 if (!Insert.hasOneUse())
920 return true;
921 auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
922 if (!InsertUser)
923 return true;
924 return false;
925 };
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000926
Sanjay Patel0522b0d2018-10-20 17:15:57 +0000927 // Try to form a shuffle from a chain of extract-insert ops.
928 if (isShuffleRootCandidate(IE)) {
929 SmallVector<Constant*, 16> Mask;
930 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
Sanjay Patel729c4362018-10-20 16:25:55 +0000931
Sanjay Patel0522b0d2018-10-20 17:15:57 +0000932 // The proposed shuffle may be trivial, in which case we shouldn't
933 // perform the combine.
934 if (LR.first != &IE && LR.second != &IE) {
935 // We now have a shuffle of LHS, RHS, Mask.
936 if (LR.second == nullptr)
937 LR.second = UndefValue::get(LR.first->getType());
938 return new ShuffleVectorInst(LR.first, LR.second,
939 ConstantVector::get(Mask));
Chris Lattnerec97a902010-01-05 05:36:20 +0000940 }
941 }
942 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000943
Craig Topper17b55682016-12-29 07:03:18 +0000944 unsigned VWidth = VecOp->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000945 APInt UndefElts(VWidth, 0);
946 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000947 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
948 if (V != &IE)
Sanjay Patel4b198802016-02-01 22:23:39 +0000949 return replaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000950 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000951 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000952
Sanjay Patel521f19f2016-09-02 17:05:43 +0000953 if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
954 return Shuf;
955
Craig Topperbb4069e2017-07-07 23:16:26 +0000956 if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
Sanjay Patel2f602ce2017-03-22 17:10:44 +0000957 return NewInsElt;
958
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000959 // Turn a sequence of inserts that broadcasts a scalar into a single
960 // insert + shufflevector.
961 if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE))
962 return Broadcast;
963
Craig Topperf40110f2014-04-25 05:29:35 +0000964 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000965}
966
Nick Lewyckya2b77202013-05-31 00:59:42 +0000967/// Return true if we can evaluate the specified expression tree if the vector
968/// elements were shuffled in a different order.
Sanjay Patel54d31ef2018-09-29 15:05:24 +0000969static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask,
Nick Lewycky3f715e22013-06-01 20:51:31 +0000970 unsigned Depth = 5) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000971 // We can always reorder the elements of a constant.
972 if (isa<Constant>(V))
973 return true;
974
975 // We won't reorder vector arguments. No IPO here.
976 Instruction *I = dyn_cast<Instruction>(V);
977 if (!I) return false;
978
979 // Two users may expect different orders of the elements. Don't try it.
980 if (!I->hasOneUse())
981 return false;
982
983 if (Depth == 0) return false;
984
985 switch (I->getOpcode()) {
986 case Instruction::Add:
987 case Instruction::FAdd:
988 case Instruction::Sub:
989 case Instruction::FSub:
990 case Instruction::Mul:
991 case Instruction::FMul:
992 case Instruction::UDiv:
993 case Instruction::SDiv:
994 case Instruction::FDiv:
995 case Instruction::URem:
996 case Instruction::SRem:
997 case Instruction::FRem:
998 case Instruction::Shl:
999 case Instruction::LShr:
1000 case Instruction::AShr:
1001 case Instruction::And:
1002 case Instruction::Or:
1003 case Instruction::Xor:
1004 case Instruction::ICmp:
1005 case Instruction::FCmp:
1006 case Instruction::Trunc:
1007 case Instruction::ZExt:
1008 case Instruction::SExt:
1009 case Instruction::FPToUI:
1010 case Instruction::FPToSI:
1011 case Instruction::UIToFP:
1012 case Instruction::SIToFP:
1013 case Instruction::FPTrunc:
1014 case Instruction::FPExt:
1015 case Instruction::GetElementPtr: {
Sanjay Patel26c119a2018-09-30 13:50:42 +00001016 // Bail out if we would create longer vector ops. We could allow creating
1017 // longer vector ops, but that may result in more expensive codegen. We
1018 // would also need to limit the transform to avoid undefined behavior for
1019 // integer div/rem.
1020 Type *ITy = I->getType();
1021 if (ITy->isVectorTy() && Mask.size() > ITy->getVectorNumElements())
1022 return false;
Sanjay Patel4e28753142015-11-16 22:16:52 +00001023 for (Value *Operand : I->operands()) {
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001024 if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
Nick Lewyckya2b77202013-05-31 00:59:42 +00001025 return false;
1026 }
1027 return true;
1028 }
1029 case Instruction::InsertElement: {
1030 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
1031 if (!CI) return false;
1032 int ElementNumber = CI->getLimitedValue();
1033
1034 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
1035 // can't put an element into multiple indices.
1036 bool SeenOnce = false;
1037 for (int i = 0, e = Mask.size(); i != e; ++i) {
1038 if (Mask[i] == ElementNumber) {
1039 if (SeenOnce)
1040 return false;
1041 SeenOnce = true;
1042 }
1043 }
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001044 return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001045 }
1046 }
1047 return false;
1048}
1049
1050/// Rebuild a new instruction just like 'I' but with the new operands given.
1051/// In the event of type mismatch, the type of the operands is correct.
Sanjay Patel431e1142015-11-17 17:24:08 +00001052static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
Nick Lewyckya2b77202013-05-31 00:59:42 +00001053 // We don't want to use the IRBuilder here because we want the replacement
1054 // instructions to appear next to 'I', not the builder's insertion point.
1055 switch (I->getOpcode()) {
1056 case Instruction::Add:
1057 case Instruction::FAdd:
1058 case Instruction::Sub:
1059 case Instruction::FSub:
1060 case Instruction::Mul:
1061 case Instruction::FMul:
1062 case Instruction::UDiv:
1063 case Instruction::SDiv:
1064 case Instruction::FDiv:
1065 case Instruction::URem:
1066 case Instruction::SRem:
1067 case Instruction::FRem:
1068 case Instruction::Shl:
1069 case Instruction::LShr:
1070 case Instruction::AShr:
1071 case Instruction::And:
1072 case Instruction::Or:
1073 case Instruction::Xor: {
1074 BinaryOperator *BO = cast<BinaryOperator>(I);
1075 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
1076 BinaryOperator *New =
1077 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
1078 NewOps[0], NewOps[1], "", BO);
1079 if (isa<OverflowingBinaryOperator>(BO)) {
1080 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
1081 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
1082 }
1083 if (isa<PossiblyExactOperator>(BO)) {
1084 New->setIsExact(BO->isExact());
1085 }
Owen Anderson48b842e2014-01-18 00:48:14 +00001086 if (isa<FPMathOperator>(BO))
1087 New->copyFastMathFlags(I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001088 return New;
1089 }
1090 case Instruction::ICmp:
1091 assert(NewOps.size() == 2 && "icmp with #ops != 2");
1092 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
1093 NewOps[0], NewOps[1]);
1094 case Instruction::FCmp:
1095 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
1096 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
1097 NewOps[0], NewOps[1]);
1098 case Instruction::Trunc:
1099 case Instruction::ZExt:
1100 case Instruction::SExt:
1101 case Instruction::FPToUI:
1102 case Instruction::FPToSI:
1103 case Instruction::UIToFP:
1104 case Instruction::SIToFP:
1105 case Instruction::FPTrunc:
1106 case Instruction::FPExt: {
1107 // It's possible that the mask has a different number of elements from
1108 // the original cast. We recompute the destination type to match the mask.
1109 Type *DestTy =
1110 VectorType::get(I->getType()->getScalarType(),
1111 NewOps[0]->getType()->getVectorNumElements());
1112 assert(NewOps.size() == 1 && "cast with #ops != 1");
1113 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
1114 "", I);
1115 }
1116 case Instruction::GetElementPtr: {
1117 Value *Ptr = NewOps[0];
1118 ArrayRef<Value*> Idx = NewOps.slice(1);
David Blaikie22319eb2015-03-14 19:24:04 +00001119 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1120 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001121 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1122 return GEP;
1123 }
1124 }
1125 llvm_unreachable("failed to rebuild vector instructions");
1126}
1127
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001128static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
Nick Lewyckya2b77202013-05-31 00:59:42 +00001129 // Mask.size() does not need to be equal to the number of vector elements.
1130
1131 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
Sanjay Patelce36b032017-10-09 17:54:46 +00001132 Type *EltTy = V->getType()->getScalarType();
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001133 Type *I32Ty = IntegerType::getInt32Ty(V->getContext());
Sanjay Patelce36b032017-10-09 17:54:46 +00001134 if (isa<UndefValue>(V))
1135 return UndefValue::get(VectorType::get(EltTy, Mask.size()));
1136
1137 if (isa<ConstantAggregateZero>(V))
1138 return ConstantAggregateZero::get(VectorType::get(EltTy, Mask.size()));
1139
Nick Lewyckya2b77202013-05-31 00:59:42 +00001140 if (Constant *C = dyn_cast<Constant>(V)) {
1141 SmallVector<Constant *, 16> MaskValues;
1142 for (int i = 0, e = Mask.size(); i != e; ++i) {
1143 if (Mask[i] == -1)
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001144 MaskValues.push_back(UndefValue::get(I32Ty));
Nick Lewyckya2b77202013-05-31 00:59:42 +00001145 else
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001146 MaskValues.push_back(ConstantInt::get(I32Ty, Mask[i]));
Nick Lewyckya2b77202013-05-31 00:59:42 +00001147 }
1148 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
1149 ConstantVector::get(MaskValues));
1150 }
1151
1152 Instruction *I = cast<Instruction>(V);
1153 switch (I->getOpcode()) {
1154 case Instruction::Add:
1155 case Instruction::FAdd:
1156 case Instruction::Sub:
1157 case Instruction::FSub:
1158 case Instruction::Mul:
1159 case Instruction::FMul:
1160 case Instruction::UDiv:
1161 case Instruction::SDiv:
1162 case Instruction::FDiv:
1163 case Instruction::URem:
1164 case Instruction::SRem:
1165 case Instruction::FRem:
1166 case Instruction::Shl:
1167 case Instruction::LShr:
1168 case Instruction::AShr:
1169 case Instruction::And:
1170 case Instruction::Or:
1171 case Instruction::Xor:
1172 case Instruction::ICmp:
1173 case Instruction::FCmp:
1174 case Instruction::Trunc:
1175 case Instruction::ZExt:
1176 case Instruction::SExt:
1177 case Instruction::FPToUI:
1178 case Instruction::FPToSI:
1179 case Instruction::UIToFP:
1180 case Instruction::SIToFP:
1181 case Instruction::FPTrunc:
1182 case Instruction::FPExt:
1183 case Instruction::Select:
1184 case Instruction::GetElementPtr: {
1185 SmallVector<Value*, 8> NewOps;
1186 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
1187 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
Mikael Holmen150a7ec2019-04-01 14:10:10 +00001188 Value *V;
1189 // Recursively call evaluateInDifferentElementOrder on vector arguments
1190 // as well. E.g. GetElementPtr may have scalar operands even if the
1191 // return value is a vector, so we need to examine the operand type.
1192 if (I->getOperand(i)->getType()->isVectorTy())
1193 V = evaluateInDifferentElementOrder(I->getOperand(i), Mask);
1194 else
1195 V = I->getOperand(i);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001196 NewOps.push_back(V);
1197 NeedsRebuild |= (V != I->getOperand(i));
1198 }
1199 if (NeedsRebuild) {
Sanjay Patel431e1142015-11-17 17:24:08 +00001200 return buildNew(I, NewOps);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001201 }
1202 return I;
1203 }
1204 case Instruction::InsertElement: {
1205 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
Nick Lewyckya2b77202013-05-31 00:59:42 +00001206
1207 // The insertelement was inserting at Element. Figure out which element
1208 // that becomes after shuffling. The answer is guaranteed to be unique
1209 // by CanEvaluateShuffled.
Nick Lewycky3f715e22013-06-01 20:51:31 +00001210 bool Found = false;
Nick Lewyckya2b77202013-05-31 00:59:42 +00001211 int Index = 0;
Nick Lewycky3f715e22013-06-01 20:51:31 +00001212 for (int e = Mask.size(); Index != e; ++Index) {
1213 if (Mask[Index] == Element) {
1214 Found = true;
Nick Lewyckya2b77202013-05-31 00:59:42 +00001215 break;
Nick Lewycky3f715e22013-06-01 20:51:31 +00001216 }
1217 }
Nick Lewyckya2b77202013-05-31 00:59:42 +00001218
Hao Liu26abebb2014-01-08 03:06:15 +00001219 // If element is not in Mask, no need to handle the operand 1 (element to
1220 // be inserted). Just evaluate values in operand 0 according to Mask.
Nick Lewycky3f715e22013-06-01 20:51:31 +00001221 if (!Found)
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001222 return evaluateInDifferentElementOrder(I->getOperand(0), Mask);
Joey Goulya3250f22013-07-12 23:08:06 +00001223
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001224 Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001225 return InsertElementInst::Create(V, I->getOperand(1),
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001226 ConstantInt::get(I32Ty, Index), "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001227 }
1228 }
1229 llvm_unreachable("failed to reorder elements of vector instruction!");
1230}
Chris Lattnerec97a902010-01-05 05:36:20 +00001231
Sanjay Patel431e1142015-11-17 17:24:08 +00001232static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001233 bool &isLHSID, bool &isRHSID) {
1234 isLHSID = isRHSID = true;
1235
1236 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
1237 if (Mask[i] < 0) continue; // Ignore undef values.
1238 // Is this an identity shuffle of the LHS value?
1239 isLHSID &= (Mask[i] == (int)i);
1240
1241 // Is this an identity shuffle of the RHS value?
1242 isRHSID &= (Mask[i]-e == i);
1243 }
1244}
1245
JF Bastiend52c9902015-02-25 22:30:51 +00001246// Returns true if the shuffle is extracting a contiguous range of values from
1247// LHS, for example:
1248// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1249// Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1250// Shuffles to: |EE|FF|GG|HH|
1251// +--+--+--+--+
1252static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1253 SmallVector<int, 16> &Mask) {
Craig Topper17b55682016-12-29 07:03:18 +00001254 unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements();
JF Bastiend52c9902015-02-25 22:30:51 +00001255 unsigned MaskElems = Mask.size();
1256 unsigned BegIdx = Mask.front();
1257 unsigned EndIdx = Mask.back();
1258 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1259 return false;
1260 for (unsigned I = 0; I != MaskElems; ++I)
1261 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
1262 return false;
1263 return true;
1264}
1265
Sanjay Patelb999d742018-07-02 17:42:29 +00001266/// These are the ingredients in an alternate form binary operator as described
1267/// below.
1268struct BinopElts {
1269 BinaryOperator::BinaryOps Opcode;
1270 Value *Op0;
1271 Value *Op1;
1272 BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0,
1273 Value *V0 = nullptr, Value *V1 = nullptr) :
1274 Opcode(Opc), Op0(V0), Op1(V1) {}
1275 operator bool() const { return Opcode != 0; }
1276};
1277
1278/// Binops may be transformed into binops with different opcodes and operands.
1279/// Reverse the usual canonicalization to enable folds with the non-canonical
1280/// form of the binop. If a transform is possible, return the elements of the
1281/// new binop. If not, return invalid elements.
1282static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) {
1283 Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
1284 Type *Ty = BO->getType();
1285 switch (BO->getOpcode()) {
1286 case Instruction::Shl: {
1287 // shl X, C --> mul X, (1 << C)
1288 Constant *C;
1289 if (match(BO1, m_Constant(C))) {
1290 Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C);
1291 return { Instruction::Mul, BO0, ShlOne };
1292 }
1293 break;
1294 }
1295 case Instruction::Or: {
1296 // or X, C --> add X, C (when X and C have no common bits set)
1297 const APInt *C;
1298 if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL))
1299 return { Instruction::Add, BO0, BO1 };
1300 break;
1301 }
1302 default:
1303 break;
1304 }
1305 return {};
1306}
1307
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001308static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) {
1309 assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
1310
1311 // Are we shuffling together some value and that same value after it has been
1312 // modified by a binop with a constant?
1313 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
1314 Constant *C;
1315 bool Op0IsBinop;
1316 if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
1317 Op0IsBinop = true;
1318 else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
1319 Op0IsBinop = false;
1320 else
1321 return nullptr;
1322
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001323 // The identity constant for a binop leaves a variable operand unchanged. For
1324 // a vector, this is a splat of something like 0, -1, or 1.
1325 // If there's no identity constant for this binop, we're done.
Sanjay Patel509a1e72018-07-10 15:12:31 +00001326 auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001327 BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
Sanjay Patel509a1e72018-07-10 15:12:31 +00001328 Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001329 if (!IdC)
1330 return nullptr;
1331
1332 // Shuffle identity constants into the lanes that return the original value.
1333 // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
1334 // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
1335 // The existing binop constant vector remains in the same operand position.
1336 Constant *Mask = Shuf.getMask();
1337 Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
1338 ConstantExpr::getShuffleVector(IdC, C, Mask);
1339
Sanjay Patel509a1e72018-07-10 15:12:31 +00001340 bool MightCreatePoisonOrUB =
1341 Mask->containsUndefElement() &&
1342 (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
1343 if (MightCreatePoisonOrUB)
1344 NewC = getSafeVectorConstantForBinop(BOpcode, NewC, true);
1345
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001346 // shuf (bop X, C), X, M --> bop X, C'
1347 // shuf X, (bop X, C), M --> bop X, C'
Sanjay Patel509a1e72018-07-10 15:12:31 +00001348 Value *X = Op0IsBinop ? Op1 : Op0;
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001349 Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
1350 NewBO->copyIRFlags(BO);
Sanjay Patel33331062018-07-10 14:27:55 +00001351
1352 // An undef shuffle mask element may propagate as an undef constant element in
1353 // the new binop. That would produce poison where the original code might not.
Sanjay Patel509a1e72018-07-10 15:12:31 +00001354 // If we already made a safe constant, then there's no danger.
1355 if (Mask->containsUndefElement() && !MightCreatePoisonOrUB)
Sanjay Patel33331062018-07-10 14:27:55 +00001356 NewBO->dropPoisonGeneratingFlags();
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001357 return NewBO;
1358}
1359
Sanjay Patelb999d742018-07-02 17:42:29 +00001360/// Try to fold shuffles that are the equivalent of a vector select.
Sanjay Patelda667532018-06-29 13:44:06 +00001361static Instruction *foldSelectShuffle(ShuffleVectorInst &Shuf,
Sanjay Patelb999d742018-07-02 17:42:29 +00001362 InstCombiner::BuilderTy &Builder,
1363 const DataLayout &DL) {
Sanjay Patela76b7002018-06-21 20:15:09 +00001364 if (!Shuf.isSelect())
1365 return nullptr;
1366
Sanjay Patelb276dd12019-03-31 15:01:30 +00001367 // Canonicalize to choose from operand 0 first.
1368 unsigned NumElts = Shuf.getType()->getVectorNumElements();
1369 if (Shuf.getMaskValue(0) >= (int)NumElts) {
Sanjay Patelb33938d2019-04-08 13:28:29 +00001370 // TODO: Can we assert that both operands of a shuffle-select are not undef
1371 // (otherwise, it would have been folded by instsimplify?
Sanjay Patelb276dd12019-03-31 15:01:30 +00001372 Shuf.commute();
1373 return &Shuf;
1374 }
1375
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001376 if (Instruction *I = foldSelectShuffleWith1Binop(Shuf))
1377 return I;
1378
Sanjay Patela76b7002018-06-21 20:15:09 +00001379 BinaryOperator *B0, *B1;
1380 if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
1381 !match(Shuf.getOperand(1), m_BinOp(B1)))
1382 return nullptr;
1383
Sanjay Patelda667532018-06-29 13:44:06 +00001384 Value *X, *Y;
Sanjay Patela76b7002018-06-21 20:15:09 +00001385 Constant *C0, *C1;
Sanjay Patela52963b2018-06-22 12:46:16 +00001386 bool ConstantsAreOp1;
1387 if (match(B0, m_BinOp(m_Value(X), m_Constant(C0))) &&
Sanjay Patelda667532018-06-29 13:44:06 +00001388 match(B1, m_BinOp(m_Value(Y), m_Constant(C1))))
Sanjay Patela52963b2018-06-22 12:46:16 +00001389 ConstantsAreOp1 = true;
1390 else if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
Sanjay Patelda667532018-06-29 13:44:06 +00001391 match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
Sanjay Patela52963b2018-06-22 12:46:16 +00001392 ConstantsAreOp1 = false;
1393 else
Sanjay Patela76b7002018-06-21 20:15:09 +00001394 return nullptr;
1395
Sanjay Patel57bda362018-06-28 17:48:04 +00001396 // We need matching binops to fold the lanes together.
1397 BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
1398 BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
1399 bool DropNSW = false;
1400 if (ConstantsAreOp1 && Opc0 != Opc1) {
Sanjay Patel57bda362018-06-28 17:48:04 +00001401 // TODO: We drop "nsw" if shift is converted into multiply because it may
1402 // not be correct when the shift amount is BitWidth - 1. We could examine
1403 // each vector element to determine if it is safe to keep that flag.
Sanjay Patelb999d742018-07-02 17:42:29 +00001404 if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
Sanjay Patel57bda362018-06-28 17:48:04 +00001405 DropNSW = true;
Sanjay Patelb999d742018-07-02 17:42:29 +00001406 if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
1407 assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
1408 Opc0 = AltB0.Opcode;
1409 C0 = cast<Constant>(AltB0.Op1);
1410 } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
1411 assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
1412 Opc1 = AltB1.Opcode;
1413 C1 = cast<Constant>(AltB1.Op1);
Sanjay Patel57bda362018-06-28 17:48:04 +00001414 }
1415 }
1416
1417 if (Opc0 != Opc1)
Sanjay Patel4784e152018-06-21 23:56:59 +00001418 return nullptr;
1419
Sanjay Patel57bda362018-06-28 17:48:04 +00001420 // The opcodes must be the same. Use a new name to make that clear.
1421 BinaryOperator::BinaryOps BOpc = Opc0;
1422
Sanjay Patel06ea4202018-07-10 13:33:26 +00001423 // Select the constant elements needed for the single binop.
1424 Constant *Mask = Shuf.getMask();
1425 Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
1426
Sanjay Patel5bd36642018-07-09 13:21:46 +00001427 // We are moving a binop after a shuffle. When a shuffle has an undefined
1428 // mask element, the result is undefined, but it is not poison or undefined
1429 // behavior. That is not necessarily true for div/rem/shift.
Sanjay Patel5bd36642018-07-09 13:21:46 +00001430 bool MightCreatePoisonOrUB =
1431 Mask->containsUndefElement() &&
1432 (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc));
Sanjay Patel06ea4202018-07-10 13:33:26 +00001433 if (MightCreatePoisonOrUB)
1434 NewC = getSafeVectorConstantForBinop(BOpc, NewC, ConstantsAreOp1);
Sanjay Patel5bd36642018-07-09 13:21:46 +00001435
Sanjay Patelda667532018-06-29 13:44:06 +00001436 Value *V;
1437 if (X == Y) {
1438 // Remove a binop and the shuffle by rearranging the constant:
1439 // shuffle (op V, C0), (op V, C1), M --> op V, C'
1440 // shuffle (op C0, V), (op C1, V), M --> op C', V
1441 V = X;
Sanjay Patel5bd36642018-07-09 13:21:46 +00001442 } else {
Sanjay Patelda667532018-06-29 13:44:06 +00001443 // If there are 2 different variable operands, we must create a new shuffle
1444 // (select) first, so check uses to ensure that we don't end up with more
1445 // instructions than we started with.
Sanjay Patel5bd36642018-07-09 13:21:46 +00001446 if (!B0->hasOneUse() && !B1->hasOneUse())
1447 return nullptr;
1448
Sanjay Patel06ea4202018-07-10 13:33:26 +00001449 // If we use the original shuffle mask and op1 is *variable*, we would be
1450 // putting an undef into operand 1 of div/rem/shift. This is either UB or
1451 // poison. We do not have to guard against UB when *constants* are op1
1452 // because safe constants guarantee that we do not overflow sdiv/srem (and
1453 // there's no danger for other opcodes).
1454 // TODO: To allow this case, create a new shuffle mask with no undefs.
1455 if (MightCreatePoisonOrUB && !ConstantsAreOp1)
Sanjay Patel5bd36642018-07-09 13:21:46 +00001456 return nullptr;
1457
Sanjay Patelda667532018-06-29 13:44:06 +00001458 // Note: In general, we do not create new shuffles in InstCombine because we
1459 // do not know if a target can lower an arbitrary shuffle optimally. In this
1460 // case, the shuffle uses the existing mask, so there is no additional risk.
Sanjay Patelda667532018-06-29 13:44:06 +00001461
1462 // Select the variable vectors first, then perform the binop:
1463 // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
1464 // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
Sanjay Patel5bd36642018-07-09 13:21:46 +00001465 V = Builder.CreateShuffleVector(X, Y, Mask);
Sanjay Patelda667532018-06-29 13:44:06 +00001466 }
1467
Sanjay Patelda667532018-06-29 13:44:06 +00001468 Instruction *NewBO = ConstantsAreOp1 ? BinaryOperator::Create(BOpc, V, NewC) :
1469 BinaryOperator::Create(BOpc, NewC, V);
Sanjay Patela76b7002018-06-21 20:15:09 +00001470
Sanjay Patel5bd36642018-07-09 13:21:46 +00001471 // Flags are intersected from the 2 source binops. But there are 2 exceptions:
1472 // 1. If we changed an opcode, poison conditions might have changed.
1473 // 2. If the shuffle had undef mask elements, the new binop might have undefs
Sanjay Patelc8d9d812018-07-10 16:09:49 +00001474 // where the original code did not. But if we already made a safe constant,
1475 // then there's no danger.
Sanjay Patela76b7002018-06-21 20:15:09 +00001476 NewBO->copyIRFlags(B0);
1477 NewBO->andIRFlags(B1);
Sanjay Patel57bda362018-06-28 17:48:04 +00001478 if (DropNSW)
1479 NewBO->setHasNoSignedWrap(false);
Sanjay Patelc8d9d812018-07-10 16:09:49 +00001480 if (Mask->containsUndefElement() && !MightCreatePoisonOrUB)
Sanjay Patel5bd36642018-07-09 13:21:46 +00001481 NewBO->dropPoisonGeneratingFlags();
Sanjay Patela76b7002018-06-21 20:15:09 +00001482 return NewBO;
1483}
1484
Sanjay Patelc1416b62018-09-07 21:03:34 +00001485/// Match a shuffle-select-shuffle pattern where the shuffles are widening and
1486/// narrowing (concatenating with undef and extracting back to the original
1487/// length). This allows replacing the wide select with a narrow select.
Sanjay Patel88194df2018-10-09 15:29:26 +00001488static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf,
1489 InstCombiner::BuilderTy &Builder) {
Sanjay Patelc1416b62018-09-07 21:03:34 +00001490 // This must be a narrowing identity shuffle. It extracts the 1st N elements
1491 // of the 1st vector operand of a shuffle.
1492 if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract())
1493 return nullptr;
1494
1495 // The vector being shuffled must be a vector select that we can eliminate.
1496 // TODO: The one-use requirement could be eased if X and/or Y are constants.
1497 Value *Cond, *X, *Y;
1498 if (!match(Shuf.getOperand(0),
1499 m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))))
1500 return nullptr;
1501
1502 // We need a narrow condition value. It must be extended with undef elements
1503 // and have the same number of elements as this shuffle.
1504 unsigned NarrowNumElts = Shuf.getType()->getVectorNumElements();
1505 Value *NarrowCond;
1506 if (!match(Cond, m_OneUse(m_ShuffleVector(m_Value(NarrowCond), m_Undef(),
1507 m_Constant()))) ||
1508 NarrowCond->getType()->getVectorNumElements() != NarrowNumElts ||
1509 !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
1510 return nullptr;
1511
1512 // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) -->
1513 // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask)
1514 Value *Undef = UndefValue::get(X->getType());
1515 Value *NarrowX = Builder.CreateShuffleVector(X, Undef, Shuf.getMask());
1516 Value *NarrowY = Builder.CreateShuffleVector(Y, Undef, Shuf.getMask());
1517 return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
1518}
1519
Sanjay Patel71811462018-10-14 15:25:06 +00001520/// Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
1521static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) {
1522 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
1523 if (!Shuf.isIdentityWithExtract() || !isa<UndefValue>(Op1))
1524 return nullptr;
1525
1526 Value *X, *Y;
1527 Constant *Mask;
1528 if (!match(Op0, m_ShuffleVector(m_Value(X), m_Value(Y), m_Constant(Mask))))
1529 return nullptr;
1530
Sanjay Patelcddb1e52019-02-05 22:58:45 +00001531 // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
1532 // then combining may result in worse codegen.
1533 if (!Op0->hasOneUse())
1534 return nullptr;
1535
Sanjay Patel71811462018-10-14 15:25:06 +00001536 // We are extracting a subvector from a shuffle. Remove excess elements from
1537 // the 1st shuffle mask to eliminate the extract.
1538 //
1539 // This transform is conservatively limited to identity extracts because we do
1540 // not allow arbitrary shuffle mask creation as a target-independent transform
1541 // (because we can't guarantee that will lower efficiently).
1542 //
1543 // If the extracting shuffle has an undef mask element, it transfers to the
1544 // new shuffle mask. Otherwise, copy the original mask element. Example:
1545 // shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> -->
1546 // shuf X, Y, <C0, undef, C2, undef>
1547 unsigned NumElts = Shuf.getType()->getVectorNumElements();
1548 SmallVector<Constant *, 16> NewMask(NumElts);
1549 assert(NumElts < Mask->getType()->getVectorNumElements() &&
1550 "Identity with extract must have less elements than its inputs");
1551
1552 for (unsigned i = 0; i != NumElts; ++i) {
1553 Constant *ExtractMaskElt = Shuf.getMask()->getAggregateElement(i);
1554 Constant *MaskElt = Mask->getAggregateElement(i);
1555 NewMask[i] = isa<UndefValue>(ExtractMaskElt) ? ExtractMaskElt : MaskElt;
1556 }
1557 return new ShuffleVectorInst(X, Y, ConstantVector::get(NewMask));
1558}
1559
Sanjay Patelb12e4102018-10-30 15:26:39 +00001560/// Try to replace a shuffle with an insertelement.
1561static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf) {
1562 Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
1563 SmallVector<int, 16> Mask = Shuf.getShuffleMask();
1564
1565 // The shuffle must not change vector sizes.
1566 // TODO: This restriction could be removed if the insert has only one use
1567 // (because the transform would require a new length-changing shuffle).
1568 int NumElts = Mask.size();
1569 if (NumElts != (int)(V0->getType()->getVectorNumElements()))
1570 return nullptr;
1571
1572 // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
1573 auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
1574 // We need an insertelement with a constant index.
1575 if (!match(V0, m_InsertElement(m_Value(), m_Value(Scalar),
1576 m_ConstantInt(IndexC))))
1577 return false;
1578
1579 // Test the shuffle mask to see if it splices the inserted scalar into the
1580 // operand 1 vector of the shuffle.
1581 int NewInsIndex = -1;
1582 for (int i = 0; i != NumElts; ++i) {
1583 // Ignore undef mask elements.
1584 if (Mask[i] == -1)
1585 continue;
1586
1587 // The shuffle takes elements of operand 1 without lane changes.
1588 if (Mask[i] == NumElts + i)
1589 continue;
1590
1591 // The shuffle must choose the inserted scalar exactly once.
1592 if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
1593 return false;
1594
1595 // The shuffle is placing the inserted scalar into element i.
1596 NewInsIndex = i;
1597 }
1598
1599 assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
1600
1601 // Index is updated to the potentially translated insertion lane.
1602 IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex);
1603 return true;
1604 };
1605
1606 // If the shuffle is unnecessary, insert the scalar operand directly into
1607 // operand 1 of the shuffle. Example:
1608 // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
1609 Value *Scalar;
1610 ConstantInt *IndexC;
1611 if (isShufflingScalarIntoOp1(Scalar, IndexC))
1612 return InsertElementInst::Create(V1, Scalar, IndexC);
1613
1614 // Try again after commuting shuffle. Example:
1615 // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
1616 // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
1617 std::swap(V0, V1);
1618 ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
1619 if (isShufflingScalarIntoOp1(Scalar, IndexC))
1620 return InsertElementInst::Create(V1, Scalar, IndexC);
1621
1622 return nullptr;
1623}
1624
Chris Lattnerec97a902010-01-05 05:36:20 +00001625Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
1626 Value *LHS = SVI.getOperand(0);
1627 Value *RHS = SVI.getOperand(1);
Craig Toppera4205622017-06-09 03:21:29 +00001628 if (auto *V = SimplifyShuffleVectorInst(
1629 LHS, RHS, SVI.getMask(), SVI.getType(), SQ.getWithInstruction(&SVI)))
Zvi Rackover82bf48d2017-04-04 04:47:57 +00001630 return replaceInstUsesWith(SVI, V);
1631
Chris Lattnerec97a902010-01-05 05:36:20 +00001632 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
1633 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001634 unsigned VWidth = SVI.getType()->getVectorNumElements();
1635 unsigned LHSWidth = LHS->getType()->getVectorNumElements();
1636 SmallVector<int, 16> Mask = SVI.getShuffleMask();
1637 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +00001638 if (LHS == RHS || isa<UndefValue>(LHS)) {
Chris Lattnerec97a902010-01-05 05:36:20 +00001639 // Remap any references to RHS to use LHS.
Chris Lattner0256be92012-01-27 03:08:05 +00001640 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00001641 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00001642 if (Mask[i] < 0) {
JF Bastiend52c9902015-02-25 22:30:51 +00001643 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +00001644 continue;
1645 }
1646
1647 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
1648 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
1649 Mask[i] = -1; // Turn into undef.
JF Bastiend52c9902015-02-25 22:30:51 +00001650 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +00001651 } else {
1652 Mask[i] = Mask[i] % e; // Force to LHS.
JF Bastiend52c9902015-02-25 22:30:51 +00001653 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
Chris Lattnerec97a902010-01-05 05:36:20 +00001654 }
1655 }
1656 SVI.setOperand(0, SVI.getOperand(1));
1657 SVI.setOperand(1, UndefValue::get(RHS->getType()));
1658 SVI.setOperand(2, ConstantVector::get(Elts));
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001659 return &SVI;
Chris Lattnerec97a902010-01-05 05:36:20 +00001660 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001661
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001662 if (Instruction *I = foldSelectShuffle(SVI, Builder, DL))
1663 return I;
1664
1665 if (Instruction *I = narrowVectorSelect(SVI, Builder))
1666 return I;
1667
1668 APInt UndefElts(VWidth, 0);
1669 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1670 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
1671 if (V != &SVI)
1672 return replaceInstUsesWith(SVI, V);
1673 return &SVI;
1674 }
1675
1676 if (Instruction *I = foldIdentityExtractShuffle(SVI))
1677 return I;
1678
1679 // This transform has the potential to lose undef knowledge, so it is
1680 // intentionally placed after SimplifyDemandedVectorElts().
1681 if (Instruction *I = foldShuffleWithInsert(SVI))
1682 return I;
1683
Eli Friedmance818272011-10-21 19:06:29 +00001684 if (VWidth == LHSWidth) {
1685 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001686 bool isLHSID, isRHSID;
Sanjay Patel431e1142015-11-17 17:24:08 +00001687 recognizeIdentityMask(Mask, isLHSID, isRHSID);
Eli Friedmance818272011-10-21 19:06:29 +00001688
1689 // Eliminate identity shuffles.
Sanjay Patel4b198802016-02-01 22:23:39 +00001690 if (isLHSID) return replaceInstUsesWith(SVI, LHS);
1691 if (isRHSID) return replaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +00001692 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001693
Sanjay Patel26c119a2018-09-30 13:50:42 +00001694 if (isa<UndefValue>(RHS) && canEvaluateShuffled(LHS, Mask)) {
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001695 Value *V = evaluateInDifferentElementOrder(LHS, Mask);
Sanjay Patel4b198802016-02-01 22:23:39 +00001696 return replaceInstUsesWith(SVI, V);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001697 }
1698
JF Bastiend52c9902015-02-25 22:30:51 +00001699 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
1700 // a non-vector type. We can instead bitcast the original vector followed by
1701 // an extract of the desired element:
1702 //
1703 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
1704 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
1705 // %1 = bitcast <4 x i8> %sroa to i32
1706 // Becomes:
1707 // %bc = bitcast <16 x i8> %in to <4 x i32>
1708 // %ext = extractelement <4 x i32> %bc, i32 0
1709 //
1710 // If the shuffle is extracting a contiguous range of values from the input
1711 // vector then each use which is a bitcast of the extracted size can be
1712 // replaced. This will work if the vector types are compatible, and the begin
1713 // index is aligned to a value in the casted vector type. If the begin index
1714 // isn't aligned then we can shuffle the original vector (keeping the same
1715 // vector type) before extracting.
1716 //
1717 // This code will bail out if the target type is fundamentally incompatible
1718 // with vectors of the source type.
1719 //
1720 // Example of <16 x i8>, target type i32:
1721 // Index range [4,8): v-----------v Will work.
1722 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1723 // <16 x i8>: | | | | | | | | | | | | | | | | |
1724 // <4 x i32>: | | | | |
1725 // +-----------+-----------+-----------+-----------+
1726 // Index range [6,10): ^-----------^ Needs an extra shuffle.
1727 // Target type i40: ^--------------^ Won't work, bail.
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001728 bool MadeChange = false;
JF Bastiend52c9902015-02-25 22:30:51 +00001729 if (isShuffleExtractingFromLHS(SVI, Mask)) {
1730 Value *V = LHS;
1731 unsigned MaskElems = Mask.size();
JF Bastiend52c9902015-02-25 22:30:51 +00001732 VectorType *SrcTy = cast<VectorType>(V->getType());
1733 unsigned VecBitWidth = SrcTy->getBitWidth();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001734 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
JF Bastiend52c9902015-02-25 22:30:51 +00001735 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1736 unsigned SrcNumElems = SrcTy->getNumElements();
1737 SmallVector<BitCastInst *, 8> BCs;
1738 DenseMap<Type *, Value *> NewBCs;
1739 for (User *U : SVI.users())
1740 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1741 if (!BC->use_empty())
1742 // Only visit bitcasts that weren't previously handled.
1743 BCs.push_back(BC);
1744 for (BitCastInst *BC : BCs) {
Eugene Leviant958fcd72017-02-17 07:36:03 +00001745 unsigned BegIdx = Mask.front();
JF Bastiend52c9902015-02-25 22:30:51 +00001746 Type *TgtTy = BC->getDestTy();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001747 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
JF Bastiend52c9902015-02-25 22:30:51 +00001748 if (!TgtElemBitWidth)
1749 continue;
1750 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1751 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1752 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1753 if (!VecBitWidthsEqual)
1754 continue;
1755 if (!VectorType::isValidElementType(TgtTy))
1756 continue;
1757 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1758 if (!BegIsAligned) {
1759 // Shuffle the input so [0,NumElements) contains the output, and
1760 // [NumElems,SrcNumElems) is undef.
1761 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1762 UndefValue::get(Int32Ty));
1763 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1764 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
Craig Topperbb4069e2017-07-07 23:16:26 +00001765 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
1766 ConstantVector::get(ShuffleMask),
1767 SVI.getName() + ".extract");
JF Bastiend52c9902015-02-25 22:30:51 +00001768 BegIdx = 0;
1769 }
1770 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1771 assert(SrcElemsPerTgtElem);
1772 BegIdx /= SrcElemsPerTgtElem;
1773 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1774 auto *NewBC =
1775 BCAlreadyExists
1776 ? NewBCs[CastSrcTy]
Craig Topperbb4069e2017-07-07 23:16:26 +00001777 : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
JF Bastiend52c9902015-02-25 22:30:51 +00001778 if (!BCAlreadyExists)
1779 NewBCs[CastSrcTy] = NewBC;
Craig Topperbb4069e2017-07-07 23:16:26 +00001780 auto *Ext = Builder.CreateExtractElement(
JF Bastiend52c9902015-02-25 22:30:51 +00001781 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1782 // The shufflevector isn't being replaced: the bitcast that used it
1783 // is. InstCombine will visit the newly-created instructions.
Sanjay Patel4b198802016-02-01 22:23:39 +00001784 replaceInstUsesWith(*BC, Ext);
JF Bastiend52c9902015-02-25 22:30:51 +00001785 MadeChange = true;
1786 }
1787 }
1788
Eric Christopher51edc7b2010-08-17 22:55:27 +00001789 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +00001790 // one without producing an unusual shuffle.
1791 // Cases that might be simplified:
1792 // 1.
1793 // x1=shuffle(v1,v2,mask1)
1794 // x=shuffle(x1,undef,mask)
1795 // ==>
1796 // x=shuffle(v1,undef,newMask)
1797 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1798 // 2.
1799 // x1=shuffle(v1,undef,mask1)
1800 // x=shuffle(x1,x2,mask)
1801 // where v1.size() == mask1.size()
1802 // ==>
1803 // x=shuffle(v1,x2,newMask)
1804 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1805 // 3.
1806 // x2=shuffle(v2,undef,mask2)
1807 // x=shuffle(x1,x2,mask)
1808 // where v2.size() == mask2.size()
1809 // ==>
1810 // x=shuffle(x1,v2,newMask)
1811 // newMask[i] = (mask[i] < x1.size())
1812 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1813 // 4.
1814 // x1=shuffle(v1,undef,mask1)
1815 // x2=shuffle(v2,undef,mask2)
1816 // x=shuffle(x1,x2,mask)
1817 // where v1.size() == v2.size()
1818 // ==>
1819 // x=shuffle(v1,v2,newMask)
1820 // newMask[i] = (mask[i] < x1.size())
1821 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1822 //
1823 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +00001824 // we are absolutely afraid of producing a shuffle mask not in the input
1825 // program, because the code gen may not be smart enough to turn a merged
1826 // shuffle into two specific shuffles: it may produce worse code. As such,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001827 // we only merge two shuffles if the result is either a splat or one of the
1828 // input shuffle masks. In this case, merging the shuffles just removes
1829 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +00001830 // turning: (splat(splat)) -> splat, or
1831 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1832 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1833 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1834 if (LHSShuffle)
1835 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
Craig Topperf40110f2014-04-25 05:29:35 +00001836 LHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001837 if (RHSShuffle)
1838 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +00001839 RHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001840 if (!LHSShuffle && !RHSShuffle)
Craig Topperf40110f2014-04-25 05:29:35 +00001841 return MadeChange ? &SVI : nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001842
Craig Topperf40110f2014-04-25 05:29:35 +00001843 Value* LHSOp0 = nullptr;
1844 Value* LHSOp1 = nullptr;
1845 Value* RHSOp0 = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001846 unsigned LHSOp0Width = 0;
1847 unsigned RHSOp0Width = 0;
1848 if (LHSShuffle) {
1849 LHSOp0 = LHSShuffle->getOperand(0);
1850 LHSOp1 = LHSShuffle->getOperand(1);
Craig Topper17b55682016-12-29 07:03:18 +00001851 LHSOp0Width = LHSOp0->getType()->getVectorNumElements();
Eli Friedmance818272011-10-21 19:06:29 +00001852 }
1853 if (RHSShuffle) {
1854 RHSOp0 = RHSShuffle->getOperand(0);
Craig Topper17b55682016-12-29 07:03:18 +00001855 RHSOp0Width = RHSOp0->getType()->getVectorNumElements();
Eli Friedmance818272011-10-21 19:06:29 +00001856 }
1857 Value* newLHS = LHS;
1858 Value* newRHS = RHS;
1859 if (LHSShuffle) {
1860 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +00001861 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +00001862 newLHS = LHSOp0;
1863 newRHS = LHSOp1;
1864 }
1865 // case 2 or 4
1866 else if (LHSOp0Width == LHSWidth) {
1867 newLHS = LHSOp0;
1868 }
1869 }
1870 // case 3 or 4
1871 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1872 newRHS = RHSOp0;
1873 }
1874 // case 4
1875 if (LHSOp0 == RHSOp0) {
1876 newLHS = LHSOp0;
Craig Topperf40110f2014-04-25 05:29:35 +00001877 newRHS = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001878 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001879
Eli Friedmance818272011-10-21 19:06:29 +00001880 if (newLHS == LHS && newRHS == RHS)
Craig Topperf40110f2014-04-25 05:29:35 +00001881 return MadeChange ? &SVI : nullptr;
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001882
Eli Friedmance818272011-10-21 19:06:29 +00001883 SmallVector<int, 16> LHSMask;
1884 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +00001885 if (newLHS != LHS)
1886 LHSMask = LHSShuffle->getShuffleMask();
1887 if (RHSShuffle && newRHS != RHS)
1888 RHSMask = RHSShuffle->getShuffleMask();
1889
Eli Friedmance818272011-10-21 19:06:29 +00001890 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1891 SmallVector<int, 16> newMask;
1892 bool isSplat = true;
1893 int SplatElt = -1;
1894 // Create a new mask for the new ShuffleVectorInst so that the new
1895 // ShuffleVectorInst is equivalent to the original one.
1896 for (unsigned i = 0; i < VWidth; ++i) {
1897 int eltMask;
Craig Topper45d9f4b2013-01-18 05:30:07 +00001898 if (Mask[i] < 0) {
Eli Friedmance818272011-10-21 19:06:29 +00001899 // This element is an undef value.
1900 eltMask = -1;
1901 } else if (Mask[i] < (int)LHSWidth) {
1902 // This element is from left hand side vector operand.
Craig Topper2ea22b02013-01-18 05:09:16 +00001903 //
Eli Friedmance818272011-10-21 19:06:29 +00001904 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1905 // new mask value for the element.
1906 if (newLHS != LHS) {
1907 eltMask = LHSMask[Mask[i]];
1908 // If the value selected is an undef value, explicitly specify it
1909 // with a -1 mask value.
1910 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1911 eltMask = -1;
Craig Topper2ea22b02013-01-18 05:09:16 +00001912 } else
Eli Friedmance818272011-10-21 19:06:29 +00001913 eltMask = Mask[i];
1914 } else {
1915 // This element is from right hand side vector operand
1916 //
1917 // If the value selected is an undef value, explicitly specify it
1918 // with a -1 mask value. (case 1)
1919 if (isa<UndefValue>(RHS))
1920 eltMask = -1;
1921 // If RHS is going to be replaced (case 3 or 4), calculate the
1922 // new mask value for the element.
1923 else if (newRHS != RHS) {
1924 eltMask = RHSMask[Mask[i]-LHSWidth];
1925 // If the value selected is an undef value, explicitly specify it
1926 // with a -1 mask value.
1927 if (eltMask >= (int)RHSOp0Width) {
1928 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1929 && "should have been check above");
1930 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001931 }
Craig Topper2ea22b02013-01-18 05:09:16 +00001932 } else
Eli Friedmance818272011-10-21 19:06:29 +00001933 eltMask = Mask[i]-LHSWidth;
1934
1935 // If LHS's width is changed, shift the mask value accordingly.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001936 // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
Michael Gottesman02a11412012-10-16 21:29:38 +00001937 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1938 // If newRHS == newLHS, we want to remap any references from newRHS to
1939 // newLHS so that we can properly identify splats that may occur due to
Alp Tokercb402912014-01-24 17:20:08 +00001940 // obfuscation across the two vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001941 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001942 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001943 }
Eli Friedmance818272011-10-21 19:06:29 +00001944
1945 // Check if this could still be a splat.
1946 if (eltMask >= 0) {
1947 if (SplatElt >= 0 && SplatElt != eltMask)
1948 isSplat = false;
1949 SplatElt = eltMask;
1950 }
1951
1952 newMask.push_back(eltMask);
1953 }
1954
1955 // If the result mask is equal to one of the original shuffle masks,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001956 // or is a splat, do the replacement.
1957 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
Eli Friedmance818272011-10-21 19:06:29 +00001958 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00001959 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1960 if (newMask[i] < 0) {
1961 Elts.push_back(UndefValue::get(Int32Ty));
1962 } else {
1963 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1964 }
1965 }
Craig Topperf40110f2014-04-25 05:29:35 +00001966 if (!newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001967 newRHS = UndefValue::get(newLHS->getType());
1968 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001969 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001970
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001971 // If the result mask is an identity, replace uses of this instruction with
1972 // corresponding argument.
Serge Pavlovb575ee82014-05-13 06:07:21 +00001973 bool isLHSID, isRHSID;
Sanjay Patel431e1142015-11-17 17:24:08 +00001974 recognizeIdentityMask(newMask, isLHSID, isRHSID);
Sanjay Patel4b198802016-02-01 22:23:39 +00001975 if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS);
1976 if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001977
Craig Topperf40110f2014-04-25 05:29:35 +00001978 return MadeChange ? &SVI : nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +00001979}