blob: 945664de686a24b486935d12590390653bb926ce [file] [log] [blame]
Chris Lattnerec97a902010-01-05 05:36:20 +00001//===- InstCombineVectorOps.cpp -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements instcombine for ExtractElement, InsertElement and
11// ShuffleVector.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carrutha9174582015-01-22 05:25:13 +000015#include "InstCombineInternal.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
JF Bastiend52c9902015-02-25 22:30:51 +000018#include "llvm/ADT/DenseMap.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
David Majnemer599ca442015-07-13 01:15:53 +000021#include "llvm/Analysis/InstructionSimplify.h"
22#include "llvm/Analysis/VectorUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000031#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000032#include "llvm/IR/Type.h"
33#include "llvm/IR/User.h"
34#include "llvm/IR/Value.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
38#include <cassert>
39#include <cstdint>
40#include <iterator>
41#include <utility>
42
Chris Lattnerec97a902010-01-05 05:36:20 +000043using namespace llvm;
Nadav Rotem7df85092013-01-15 23:43:14 +000044using namespace PatternMatch;
Chris Lattnerec97a902010-01-05 05:36:20 +000045
Chandler Carruth964daaa2014-04-22 02:55:47 +000046#define DEBUG_TYPE "instcombine"
47
Sanjay Patel6eccf482015-09-09 15:24:36 +000048/// Return true if the value is cheaper to scalarize than it is to leave as a
49/// vector operation. isConstant indicates whether we're extracting one known
50/// element. If false we're extracting a variable index.
Sanjay Patel431e1142015-11-17 17:24:08 +000051static bool cheapToScalarize(Value *V, bool isConstant) {
Chris Lattner8326bd82012-01-26 00:42:34 +000052 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000053 if (isConstant) return true;
Chris Lattner8326bd82012-01-26 00:42:34 +000054
55 // If all elts are the same, we can extract it and use any of the values.
Benjamin Kramer09b0f882014-01-24 19:02:37 +000056 if (Constant *Op0 = C->getAggregateElement(0U)) {
57 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
58 ++i)
59 if (C->getAggregateElement(i) != Op0)
60 return false;
61 return true;
62 }
Chris Lattnerec97a902010-01-05 05:36:20 +000063 }
64 Instruction *I = dyn_cast<Instruction>(V);
65 if (!I) return false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000066
Chris Lattnerec97a902010-01-05 05:36:20 +000067 // Insert element gets simplified to the inserted element or is deleted if
68 // this is constant idx extract element and its a constant idx insertelt.
69 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
70 isa<ConstantInt>(I->getOperand(2)))
71 return true;
72 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
73 return true;
74 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
75 if (BO->hasOneUse() &&
Sanjay Patel431e1142015-11-17 17:24:08 +000076 (cheapToScalarize(BO->getOperand(0), isConstant) ||
77 cheapToScalarize(BO->getOperand(1), isConstant)))
Chris Lattnerec97a902010-01-05 05:36:20 +000078 return true;
79 if (CmpInst *CI = dyn_cast<CmpInst>(I))
80 if (CI->hasOneUse() &&
Sanjay Patel431e1142015-11-17 17:24:08 +000081 (cheapToScalarize(CI->getOperand(0), isConstant) ||
82 cheapToScalarize(CI->getOperand(1), isConstant)))
Chris Lattnerec97a902010-01-05 05:36:20 +000083 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000084
Chris Lattnerec97a902010-01-05 05:36:20 +000085 return false;
86}
87
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000088// If we have a PHI node with a vector type that is only used to feed
Matt Arsenault38874732013-08-28 22:17:26 +000089// itself and be an operand of extractelement at a constant location,
90// try to replace the PHI of the vector type with a PHI of a scalar type.
Anat Shemer0c95efa2013-04-18 19:35:39 +000091Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000092 SmallVector<Instruction *, 2> Extracts;
93 // The users we want the PHI to have are:
94 // 1) The EI ExtractElement (we already know this)
95 // 2) Possibly more ExtractElements with the same index.
96 // 3) Another operand, which will feed back into the PHI.
97 Instruction *PHIUser = nullptr;
98 for (auto U : PN->users()) {
99 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
100 if (EI.getIndexOperand() == EU->getIndexOperand())
101 Extracts.push_back(EU);
102 else
103 return nullptr;
104 } else if (!PHIUser) {
105 PHIUser = cast<Instruction>(U);
106 } else {
107 return nullptr;
108 }
109 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000110
Michael Kupersteina0c6ae02016-06-06 23:38:33 +0000111 if (!PHIUser)
112 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000113
114 // Verify that this PHI user has one use, which is the PHI itself,
115 // and that it is a binary operation which is cheap to scalarize.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000116 // otherwise return nullptr.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000117 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
Sanjay Patel431e1142015-11-17 17:24:08 +0000118 !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000120
121 // Create a scalar PHI node that will replace the vector PHI node
122 // just before the current PHI node.
Joey Goulyb34294d2013-05-24 12:33:28 +0000123 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
124 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
Anat Shemer0c95efa2013-04-18 19:35:39 +0000125 // Scalarize each PHI operand.
Joey Goulyb34294d2013-05-24 12:33:28 +0000126 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
Anat Shemer0c95efa2013-04-18 19:35:39 +0000127 Value *PHIInVal = PN->getIncomingValue(i);
128 BasicBlock *inBB = PN->getIncomingBlock(i);
129 Value *Elt = EI.getIndexOperand();
130 // If the operand is the PHI induction variable:
131 if (PHIInVal == PHIUser) {
132 // Scalarize the binary operation. Its first operand is the
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000133 // scalar PHI, and the second operand is extracted from the other
Anat Shemer0c95efa2013-04-18 19:35:39 +0000134 // vector operand.
135 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
Joey Goulyb34294d2013-05-24 12:33:28 +0000136 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
Joey Gouly83699282013-05-24 12:29:54 +0000137 Value *Op = InsertNewInstWith(
138 ExtractElementInst::Create(B0->getOperand(opId), Elt,
139 B0->getOperand(opId)->getName() + ".Elt"),
140 *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000141 Value *newPHIUser = InsertNewInstWith(
Owen Anderson7ea02fc2016-03-01 19:35:52 +0000142 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
143 scalarPHI, Op, B0), *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000144 scalarPHI->addIncoming(newPHIUser, inBB);
145 } else {
146 // Scalarize PHI input:
Joey Goulyb34294d2013-05-24 12:33:28 +0000147 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
Anat Shemer0c95efa2013-04-18 19:35:39 +0000148 // Insert the new instruction into the predecessor basic block.
149 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
150 BasicBlock::iterator InsertPos;
151 if (pos && !isa<PHINode>(pos)) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000152 InsertPos = ++pos->getIterator();
Anat Shemer0c95efa2013-04-18 19:35:39 +0000153 } else {
154 InsertPos = inBB->getFirstInsertionPt();
155 }
156
157 InsertNewInstWith(newEI, *InsertPos);
158
159 scalarPHI->addIncoming(newEI, inBB);
160 }
161 }
Michael Kupersteina0c6ae02016-06-06 23:38:33 +0000162
163 for (auto E : Extracts)
164 replaceInstUsesWith(*E, scalarPHI);
165
166 return &EI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000167}
168
Sanjay Patel4674c772018-09-24 20:41:22 +0000169static Instruction *foldBitcastExtElt(ExtractElementInst &Ext,
Sanjay Patel31b07192018-10-01 14:40:00 +0000170 InstCombiner::BuilderTy &Builder,
171 bool IsBigEndian) {
Sanjay Patel4674c772018-09-24 20:41:22 +0000172 Value *X;
173 uint64_t ExtIndexC;
174 if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
175 !X->getType()->isVectorTy() ||
176 !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
177 return nullptr;
178
179 // If this extractelement is using a bitcast from a vector of the same number
180 // of elements, see if we can find the source element from the source vector:
181 // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
182 Type *SrcTy = X->getType();
183 Type *DestTy = Ext.getType();
184 unsigned NumSrcElts = SrcTy->getVectorNumElements();
185 unsigned NumElts = Ext.getVectorOperandType()->getNumElements();
186 if (NumSrcElts == NumElts)
187 if (Value *Elt = findScalarElement(X, ExtIndexC))
188 return new BitCastInst(Elt, DestTy);
189
Sanjay Patel31b07192018-10-01 14:40:00 +0000190 // If the source elements are wider than the destination, try to shift and
191 // truncate a subset of scalar bits of an insert op.
192 // TODO: This is limited to integer types, but we could bitcast to/from FP.
193 if (NumSrcElts < NumElts && SrcTy->getScalarType()->isIntegerTy() &&
194 DestTy->getScalarType()->isIntegerTy()) {
195 Value *Scalar;
196 uint64_t InsIndexC;
197 if (!match(X, m_InsertElement(m_Value(), m_Value(Scalar),
198 m_ConstantInt(InsIndexC))))
199 return nullptr;
200
201 // The extract must be from the subset of vector elements that we inserted
202 // into. Example: if we inserted element 1 of a <2 x i64> and we are
203 // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
204 // of elements 4-7 of the bitcasted vector.
205 unsigned NarrowingRatio = NumElts / NumSrcElts;
206 if (ExtIndexC / NarrowingRatio != InsIndexC)
207 return nullptr;
208
209 // We are extracting part of the original scalar. How that scalar is
210 // inserted into the vector depends on the endian-ness. Example:
211 // Vector Byte Elt Index: 0 1 2 3 4 5 6 7
212 // +--+--+--+--+--+--+--+--+
213 // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3|
214 // extelt <4 x i16> V', 3: | |S2|S3|
215 // +--+--+--+--+--+--+--+--+
216 // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
217 // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
218 // In this example, we must right-shift little-endian. Big-endian is just a
219 // truncate.
220 unsigned Chunk = ExtIndexC % NarrowingRatio;
221 if (IsBigEndian)
222 Chunk = NarrowingRatio - 1 - Chunk;
223 unsigned ShAmt = Chunk * DestTy->getPrimitiveSizeInBits();
224 if (ShAmt) {
225 // Bail out if we could end with more instructions than we started with.
226 if (!Ext.getVectorOperand()->hasOneUse())
227 return nullptr;
228 Scalar = Builder.CreateLShr(Scalar, ShAmt);
229 }
230 return new TruncInst(Scalar, DestTy);
231 }
232
Sanjay Patel4674c772018-09-24 20:41:22 +0000233 return nullptr;
234}
235
Chris Lattnerec97a902010-01-05 05:36:20 +0000236Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Daniel Berlin2c75c632017-04-26 20:56:07 +0000237 if (Value *V = SimplifyExtractElementInst(EI.getVectorOperand(),
Craig Toppera4205622017-06-09 03:21:29 +0000238 EI.getIndexOperand(),
239 SQ.getWithInstruction(&EI)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000240 return replaceInstUsesWith(EI, V);
David Majnemer599ca442015-07-13 01:15:53 +0000241
Chris Lattner8326bd82012-01-26 00:42:34 +0000242 // If vector val is constant with all elements the same, replace EI with
243 // that element. We handle a known element # below.
244 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
Sanjay Patel431e1142015-11-17 17:24:08 +0000245 if (cheapToScalarize(C, false))
Sanjay Patel4b198802016-02-01 22:23:39 +0000246 return replaceInstUsesWith(EI, C->getAggregateElement(0U));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000247
Chris Lattnerec97a902010-01-05 05:36:20 +0000248 // If extracting a specified index from the vector, see if we can recursively
249 // find a previously computed scalar that was inserted into the vector.
250 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Sanjay Patel7a526262018-09-24 16:39:03 +0000251 unsigned NumElts = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000252
Simon Pilgrime7d032f2017-12-27 12:00:18 +0000253 // InstSimplify should handle cases where the index is invalid.
Sanjay Patel7a526262018-09-24 16:39:03 +0000254 if (!IdxC->getValue().ule(NumElts))
Simon Pilgrime7d032f2017-12-27 12:00:18 +0000255 return nullptr;
256
Chris Lattnerec97a902010-01-05 05:36:20 +0000257 // This instruction only demands the single element from the input vector.
258 // If the input vector has a single use, simplify it based on this use
259 // property.
Sanjay Patel7a526262018-09-24 16:39:03 +0000260 if (EI.getOperand(0)->hasOneUse() && NumElts != 1) {
261 APInt UndefElts(NumElts, 0);
262 APInt DemandedMask(NumElts, 0);
Sanjay Patel4674c772018-09-24 20:41:22 +0000263 DemandedMask.setBit(IdxC->getZExtValue());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000264 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
265 UndefElts)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000266 EI.setOperand(0, V);
267 return &EI;
268 }
269 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000270
Sanjay Patel31b07192018-10-01 14:40:00 +0000271 if (Instruction *I = foldBitcastExtElt(EI, Builder, DL.isBigEndian()))
Sanjay Patel4674c772018-09-24 20:41:22 +0000272 return I;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000273
274 // If there's a vector PHI feeding a scalar use through this extractelement
275 // instruction, try to scalarize the PHI.
276 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
Nick Lewycky881e9d62013-05-04 01:08:15 +0000277 Instruction *scalarPHI = scalarizePHI(EI, PN);
278 if (scalarPHI)
Joey Goulyb34294d2013-05-24 12:33:28 +0000279 return scalarPHI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000280 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000281 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000282
Chris Lattnerec97a902010-01-05 05:36:20 +0000283 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
284 // Push extractelement into predecessor operation if legal and
Sanjay Patelb67076c2015-11-29 22:09:34 +0000285 // profitable to do so.
Chris Lattnerec97a902010-01-05 05:36:20 +0000286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
287 if (I->hasOneUse() &&
Sanjay Patel431e1142015-11-17 17:24:08 +0000288 cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000289 Value *newEI0 =
Craig Topperbb4069e2017-07-07 23:16:26 +0000290 Builder.CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
291 EI.getName()+".lhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000292 Value *newEI1 =
Craig Topperbb4069e2017-07-07 23:16:26 +0000293 Builder.CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
294 EI.getName()+".rhs");
Owen Anderson7ea02fc2016-03-01 19:35:52 +0000295 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(),
296 newEI0, newEI1, BO);
Chris Lattnerec97a902010-01-05 05:36:20 +0000297 }
298 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
299 // Extracting the inserted element?
300 if (IE->getOperand(2) == EI.getOperand(1))
Sanjay Patel4b198802016-02-01 22:23:39 +0000301 return replaceInstUsesWith(EI, IE->getOperand(1));
Chris Lattnerec97a902010-01-05 05:36:20 +0000302 // If the inserted and extracted elements are constants, they must not
303 // be the same value, extract from the pre-inserted value instead.
304 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
305 Worklist.AddValue(EI.getOperand(0));
306 EI.setOperand(0, IE->getOperand(0));
307 return &EI;
308 }
309 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
310 // If this is extracting an element from a shufflevector, figure out where
311 // it came from and extract from the appropriate input element instead.
312 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000313 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000314 Value *Src;
315 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000316 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000317
Bob Wilson11ee4562010-10-29 22:03:05 +0000318 if (SrcIdx < 0)
Sanjay Patel4b198802016-02-01 22:23:39 +0000319 return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson11ee4562010-10-29 22:03:05 +0000320 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000321 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000322 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000323 SrcIdx -= LHSWidth;
324 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000325 }
Chris Lattner229907c2011-07-18 04:54:35 +0000326 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000327 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000328 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000329 SrcIdx, false));
330 }
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000331 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Sanjay Patelb67076c2015-11-29 22:09:34 +0000332 // Canonicalize extractelement(cast) -> cast(extractelement).
333 // Bitcasts can change the number of vector elements, and they cost
334 // nothing.
Anat Shemer55703182013-04-18 19:56:44 +0000335 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000336 Value *EE = Builder.CreateExtractElement(CI->getOperand(0),
337 EI.getIndexOperand());
Anat Shemer10260a72013-04-22 20:51:10 +0000338 Worklist.AddValue(EE);
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000339 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
340 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000341 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000342 }
Craig Topperf40110f2014-04-25 05:29:35 +0000343 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000344}
345
Sanjay Patel6eccf482015-09-09 15:24:36 +0000346/// If V is a shuffle of values that ONLY returns elements from either LHS or
347/// RHS, return the shuffle mask and true. Otherwise, return false.
Sanjay Patel431e1142015-11-17 17:24:08 +0000348static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner0256be92012-01-27 03:08:05 +0000349 SmallVectorImpl<Constant*> &Mask) {
Tim Northoverfad27612014-03-07 10:24:44 +0000350 assert(LHS->getType() == RHS->getType() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000351 "Invalid CollectSingleShuffleElements");
Matt Arsenault8227b9f2013-09-06 00:37:24 +0000352 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000353
Chris Lattnerec97a902010-01-05 05:36:20 +0000354 if (isa<UndefValue>(V)) {
355 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
356 return true;
357 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000358
Chris Lattnerec97a902010-01-05 05:36:20 +0000359 if (V == LHS) {
360 for (unsigned i = 0; i != NumElts; ++i)
361 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
362 return true;
363 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000364
Chris Lattnerec97a902010-01-05 05:36:20 +0000365 if (V == RHS) {
366 for (unsigned i = 0; i != NumElts; ++i)
367 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
368 i+NumElts));
369 return true;
370 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000371
Chris Lattnerec97a902010-01-05 05:36:20 +0000372 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
373 // If this is an insert of an extract from some other vector, include it.
374 Value *VecOp = IEI->getOperand(0);
375 Value *ScalarOp = IEI->getOperand(1);
376 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000377
Chris Lattnerec97a902010-01-05 05:36:20 +0000378 if (!isa<ConstantInt>(IdxOp))
379 return false;
380 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000381
Chris Lattnerec97a902010-01-05 05:36:20 +0000382 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000383 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000384 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000385 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000386 // If so, update the mask to reflect the inserted undef.
387 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
388 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000389 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000390 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
Tim Northoverfad27612014-03-07 10:24:44 +0000391 if (isa<ConstantInt>(EI->getOperand(1))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000392 unsigned ExtractedIdx =
393 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Tim Northoverfad27612014-03-07 10:24:44 +0000394 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000395
Chris Lattnerec97a902010-01-05 05:36:20 +0000396 // This must be extracting from either LHS or RHS.
397 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000398 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000399 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000400 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000401 // If so, update the mask to reflect the inserted value.
402 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000403 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000404 ConstantInt::get(Type::getInt32Ty(V->getContext()),
405 ExtractedIdx);
406 } else {
407 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000408 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000409 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000410 ExtractedIdx + NumLHSElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000411 }
412 return true;
413 }
414 }
415 }
416 }
417 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000418
Chris Lattnerec97a902010-01-05 05:36:20 +0000419 return false;
420}
421
Sanjay Patelae945e72015-12-24 21:17:56 +0000422/// If we have insertion into a vector that is wider than the vector that we
423/// are extracting from, try to widen the source vector to allow a single
424/// shufflevector to replace one or more insert/extract pairs.
425static void replaceExtractElements(InsertElementInst *InsElt,
426 ExtractElementInst *ExtElt,
427 InstCombiner &IC) {
428 VectorType *InsVecType = InsElt->getType();
429 VectorType *ExtVecType = ExtElt->getVectorOperandType();
430 unsigned NumInsElts = InsVecType->getVectorNumElements();
431 unsigned NumExtElts = ExtVecType->getVectorNumElements();
432
433 // The inserted-to vector must be wider than the extracted-from vector.
434 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
435 NumExtElts >= NumInsElts)
436 return;
437
438 // Create a shuffle mask to widen the extended-from vector using undefined
439 // values. The mask selects all of the values of the original vector followed
440 // by as many undefined values as needed to create a vector of the same length
441 // as the inserted-to vector.
442 SmallVector<Constant *, 16> ExtendMask;
443 IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
444 for (unsigned i = 0; i < NumExtElts; ++i)
445 ExtendMask.push_back(ConstantInt::get(IntType, i));
446 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
447 ExtendMask.push_back(UndefValue::get(IntType));
448
449 Value *ExtVecOp = ExtElt->getVectorOperand();
Sanjay Patel66fff732016-01-29 20:21:02 +0000450 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
451 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
452 ? ExtVecOpInst->getParent()
453 : ExtElt->getParent();
454
455 // TODO: This restriction matches the basic block check below when creating
456 // new extractelement instructions. If that limitation is removed, this one
457 // could also be removed. But for now, we just bail out to ensure that we
458 // will replace the extractelement instruction that is feeding our
459 // insertelement instruction. This allows the insertelement to then be
460 // replaced by a shufflevector. If the insertelement is not replaced, we can
461 // induce infinite looping because there's an optimization for extractelement
462 // that will delete our widening shuffle. This would trigger another attempt
463 // here to create that shuffle, and we spin forever.
464 if (InsertionBlock != InsElt->getParent())
465 return;
466
Sanjay Patel4e1b5a52016-11-10 00:15:14 +0000467 // TODO: This restriction matches the check in visitInsertElementInst() and
468 // prevents an infinite loop caused by not turning the extract/insert pair
469 // into a shuffle. We really should not need either check, but we're lacking
470 // folds for shufflevectors because we're afraid to generate shuffle masks
471 // that the backend can't handle.
472 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
473 return;
474
Sanjay Patelae945e72015-12-24 21:17:56 +0000475 auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
476 ConstantVector::get(ExtendMask));
477
Sanjay Patela1c53472016-01-05 19:09:47 +0000478 // Insert the new shuffle after the vector operand of the extract is defined
Sanjay Pateld72a4582016-01-08 01:39:16 +0000479 // (as long as it's not a PHI) or at the start of the basic block of the
480 // extract, so any subsequent extracts in the same basic block can use it.
481 // TODO: Insert before the earliest ExtractElementInst that is replaced.
Sanjay Pateld72a4582016-01-08 01:39:16 +0000482 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
Sanjay Patela1c53472016-01-05 19:09:47 +0000483 WideVec->insertAfter(ExtVecOpInst);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000484 else
Sanjay Patela1c53472016-01-05 19:09:47 +0000485 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
Sanjay Patela1c53472016-01-05 19:09:47 +0000486
487 // Replace extracts from the original narrow vector with extracts from the new
488 // wide vector.
Sanjay Patelae945e72015-12-24 21:17:56 +0000489 for (User *U : ExtVecOp->users()) {
Sanjay Patela1c53472016-01-05 19:09:47 +0000490 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000491 if (!OldExt || OldExt->getParent() != WideVec->getParent())
Sanjay Patela1c53472016-01-05 19:09:47 +0000492 continue;
493 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
Sven van Haastregt78819e02017-06-05 09:18:10 +0000494 NewExt->insertAfter(OldExt);
Sanjay Patel4b198802016-02-01 22:23:39 +0000495 IC.replaceInstUsesWith(*OldExt, NewExt);
Sanjay Patelae945e72015-12-24 21:17:56 +0000496 }
497}
Tim Northoverfad27612014-03-07 10:24:44 +0000498
499/// We are building a shuffle to create V, which is a sequence of insertelement,
500/// extractelement pairs. If PermittedRHS is set, then we must either use it or
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000501/// not rely on the second vector source. Return a std::pair containing the
Tim Northoverfad27612014-03-07 10:24:44 +0000502/// left and right vectors of the proposed shuffle (or 0), and set the Mask
503/// parameter as required.
504///
505/// Note: we intentionally don't try to fold earlier shuffles since they have
506/// often been chosen carefully to be efficiently implementable on the target.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000507using ShuffleOps = std::pair<Value *, Value *>;
Tim Northoverfad27612014-03-07 10:24:44 +0000508
Sanjay Patel431e1142015-11-17 17:24:08 +0000509static ShuffleOps collectShuffleElements(Value *V,
Tim Northoverfad27612014-03-07 10:24:44 +0000510 SmallVectorImpl<Constant *> &Mask,
Sanjay Patelae945e72015-12-24 21:17:56 +0000511 Value *PermittedRHS,
512 InstCombiner &IC) {
Tim Northoverfad27612014-03-07 10:24:44 +0000513 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
Craig Topper17b55682016-12-29 07:03:18 +0000514 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000515
Chris Lattnerec97a902010-01-05 05:36:20 +0000516 if (isa<UndefValue>(V)) {
517 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Tim Northoverfad27612014-03-07 10:24:44 +0000518 return std::make_pair(
519 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000520 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000521
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000522 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000523 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Tim Northoverfad27612014-03-07 10:24:44 +0000524 return std::make_pair(V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000525 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000526
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000527 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000528 // If this is an insert of an extract from some other vector, include it.
529 Value *VecOp = IEI->getOperand(0);
530 Value *ScalarOp = IEI->getOperand(1);
531 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000532
Chris Lattnerec97a902010-01-05 05:36:20 +0000533 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000534 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000535 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000536 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000537 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000538
Chris Lattnerec97a902010-01-05 05:36:20 +0000539 // Either the extracted from or inserted into vector must be RHSVec,
540 // otherwise we'd end up with a shuffle of three inputs.
Craig Topperf40110f2014-04-25 05:29:35 +0000541 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Tim Northoverfad27612014-03-07 10:24:44 +0000542 Value *RHS = EI->getOperand(0);
Sanjay Patelae945e72015-12-24 21:17:56 +0000543 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
Craig Toppere73658d2014-04-28 04:05:08 +0000544 assert(LR.second == nullptr || LR.second == RHS);
Tim Northoverfad27612014-03-07 10:24:44 +0000545
546 if (LR.first->getType() != RHS->getType()) {
Sanjay Patelae945e72015-12-24 21:17:56 +0000547 // Although we are giving up for now, see if we can create extracts
548 // that match the inserts for another round of combining.
549 replaceExtractElements(IEI, EI, IC);
550
Tim Northoverfad27612014-03-07 10:24:44 +0000551 // We tried our best, but we can't find anything compatible with RHS
552 // further up the chain. Return a trivial shuffle.
553 for (unsigned i = 0; i < NumElts; ++i)
554 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
555 return std::make_pair(V, nullptr);
556 }
557
558 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000559 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000560 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000561 NumLHSElts+ExtractedIdx);
562 return std::make_pair(LR.first, RHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000563 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000564
Tim Northoverfad27612014-03-07 10:24:44 +0000565 if (VecOp == PermittedRHS) {
566 // We've gone as far as we can: anything on the other side of the
567 // extractelement will already have been converted into a shuffle.
568 unsigned NumLHSElts =
569 EI->getOperand(0)->getType()->getVectorNumElements();
570 for (unsigned i = 0; i != NumElts; ++i)
571 Mask.push_back(ConstantInt::get(
572 Type::getInt32Ty(V->getContext()),
573 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
574 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000575 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000576
Chris Lattnerec97a902010-01-05 05:36:20 +0000577 // If this insertelement is a chain that comes from exactly these two
578 // vectors, return the vector and the effective shuffle.
Tim Northoverfad27612014-03-07 10:24:44 +0000579 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
Sanjay Patel431e1142015-11-17 17:24:08 +0000580 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
Tim Northoverfad27612014-03-07 10:24:44 +0000581 Mask))
582 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000583 }
584 }
585 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000586
Sanjay Patelb67076c2015-11-29 22:09:34 +0000587 // Otherwise, we can't do anything fancy. Return an identity vector.
Chris Lattnerec97a902010-01-05 05:36:20 +0000588 for (unsigned i = 0; i != NumElts; ++i)
589 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Tim Northoverfad27612014-03-07 10:24:44 +0000590 return std::make_pair(V, nullptr);
Chris Lattnerec97a902010-01-05 05:36:20 +0000591}
592
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000593/// Try to find redundant insertvalue instructions, like the following ones:
594/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
595/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
596/// Here the second instruction inserts values at the same indices, as the
597/// first one, making the first one redundant.
598/// It should be transformed to:
599/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
600Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
601 bool IsRedundant = false;
602 ArrayRef<unsigned int> FirstIndices = I.getIndices();
603
604 // If there is a chain of insertvalue instructions (each of them except the
605 // last one has only one use and it's another insertvalue insn from this
606 // chain), check if any of the 'children' uses the same indices as the first
607 // instruction. In this case, the first one is redundant.
608 Value *V = &I;
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000609 unsigned Depth = 0;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000610 while (V->hasOneUse() && Depth < 10) {
611 User *U = V->user_back();
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000612 auto UserInsInst = dyn_cast<InsertValueInst>(U);
613 if (!UserInsInst || U->getOperand(0) != V)
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000614 break;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000615 if (UserInsInst->getIndices() == FirstIndices) {
616 IsRedundant = true;
617 break;
618 }
619 V = UserInsInst;
620 Depth++;
621 }
622
623 if (IsRedundant)
Sanjay Patel4b198802016-02-01 22:23:39 +0000624 return replaceInstUsesWith(I, I.getOperand(0));
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000625 return nullptr;
626}
627
Sanjay Patel521f19f2016-09-02 17:05:43 +0000628static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
629 int MaskSize = Shuf.getMask()->getType()->getVectorNumElements();
630 int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements();
631
632 // A vector select does not change the size of the operands.
633 if (MaskSize != VecSize)
634 return false;
635
636 // Each mask element must be undefined or choose a vector element from one of
637 // the source operands without crossing vector lanes.
638 for (int i = 0; i != MaskSize; ++i) {
639 int Elt = Shuf.getMaskValue(i);
640 if (Elt != -1 && Elt != i && Elt != i + VecSize)
641 return false;
642 }
643
644 return true;
645}
646
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000647// Turn a chain of inserts that splats a value into a canonical insert + shuffle
648// splat. That is:
649// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
650// shufflevector(insertelt(X, %k, 0), undef, zero)
651static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) {
652 // We are interested in the last insert in a chain. So, if this insert
653 // has a single user, and that user is an insert, bail.
654 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
655 return nullptr;
656
657 VectorType *VT = cast<VectorType>(InsElt.getType());
658 int NumElements = VT->getNumElements();
659
660 // Do not try to do this for a one-element vector, since that's a nop,
661 // and will cause an inf-loop.
662 if (NumElements == 1)
663 return nullptr;
664
665 Value *SplatVal = InsElt.getOperand(1);
Fangrui Songf78650a2018-07-30 19:41:25 +0000666 InsertElementInst *CurrIE = &InsElt;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000667 SmallVector<bool, 16> ElementPresent(NumElements, false);
Florian Hahnb992fee2017-08-30 10:54:21 +0000668 InsertElementInst *FirstIE = nullptr;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000669
670 // Walk the chain backwards, keeping track of which indices we inserted into,
671 // until we hit something that isn't an insert of the splatted value.
672 while (CurrIE) {
Sanjay Patel863d4942017-11-27 18:19:32 +0000673 auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000674 if (!Idx || CurrIE->getOperand(1) != SplatVal)
675 return nullptr;
676
Sanjay Patel863d4942017-11-27 18:19:32 +0000677 auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
Florian Hahnb992fee2017-08-30 10:54:21 +0000678 // Check none of the intermediate steps have any additional uses, except
679 // for the root insertelement instruction, which can be re-used, if it
680 // inserts at position 0.
681 if (CurrIE != &InsElt &&
682 (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000683 return nullptr;
684
685 ElementPresent[Idx->getZExtValue()] = true;
Florian Hahnb992fee2017-08-30 10:54:21 +0000686 FirstIE = CurrIE;
687 CurrIE = NextIE;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000688 }
689
690 // Make sure we've seen an insert into every element.
691 if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; }))
692 return nullptr;
693
694 // All right, create the insert + shuffle.
Florian Hahnb992fee2017-08-30 10:54:21 +0000695 Instruction *InsertFirst;
696 if (cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
697 InsertFirst = FirstIE;
698 else
699 InsertFirst = InsertElementInst::Create(
700 UndefValue::get(VT), SplatVal,
701 ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0),
702 "", &InsElt);
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000703
704 Constant *ZeroMask = ConstantAggregateZero::get(
705 VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements));
706
707 return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask);
708}
709
Sanjay Patel2f602ce2017-03-22 17:10:44 +0000710/// If we have an insertelement instruction feeding into another insertelement
711/// and the 2nd is inserting a constant into the vector, canonicalize that
712/// constant insertion before the insertion of a variable:
713///
714/// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
715/// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
716///
717/// This has the potential of eliminating the 2nd insertelement instruction
718/// via constant folding of the scalar constant into a vector constant.
719static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
720 InstCombiner::BuilderTy &Builder) {
721 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
722 if (!InsElt1 || !InsElt1->hasOneUse())
723 return nullptr;
724
725 Value *X, *Y;
726 Constant *ScalarC;
727 ConstantInt *IdxC1, *IdxC2;
728 if (match(InsElt1->getOperand(0), m_Value(X)) &&
729 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
730 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
731 match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
732 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
733 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
734 return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
735 }
736
737 return nullptr;
738}
739
Alexey Bataevfee90782016-09-23 09:14:08 +0000740/// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
741/// --> shufflevector X, CVec', Mask'
Sanjay Patel521f19f2016-09-02 17:05:43 +0000742static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
Alexey Bataevfee90782016-09-23 09:14:08 +0000743 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
744 // Bail out if the parent has more than one use. In that case, we'd be
Sanjay Patel521f19f2016-09-02 17:05:43 +0000745 // replacing the insertelt with a shuffle, and that's not a clear win.
Alexey Bataevfee90782016-09-23 09:14:08 +0000746 if (!Inst || !Inst->hasOneUse())
Sanjay Patel521f19f2016-09-02 17:05:43 +0000747 return nullptr;
Alexey Bataevfee90782016-09-23 09:14:08 +0000748 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
749 // The shuffle must have a constant vector operand. The insertelt must have
750 // a constant scalar being inserted at a constant position in the vector.
751 Constant *ShufConstVec, *InsEltScalar;
752 uint64_t InsEltIndex;
753 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
754 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
755 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
756 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000757
Alexey Bataevfee90782016-09-23 09:14:08 +0000758 // Adding an element to an arbitrary shuffle could be expensive, but a
759 // shuffle that selects elements from vectors without crossing lanes is
760 // assumed cheap.
761 // If we're just adding a constant into that shuffle, it will still be
762 // cheap.
763 if (!isShuffleEquivalentToSelect(*Shuf))
764 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000765
Alexey Bataevfee90782016-09-23 09:14:08 +0000766 // From the above 'select' check, we know that the mask has the same number
767 // of elements as the vector input operands. We also know that each constant
768 // input element is used in its lane and can not be used more than once by
769 // the shuffle. Therefore, replace the constant in the shuffle's constant
770 // vector with the insertelt constant. Replace the constant in the shuffle's
771 // mask vector with the insertelt index plus the length of the vector
772 // (because the constant vector operand of a shuffle is always the 2nd
773 // operand).
774 Constant *Mask = Shuf->getMask();
775 unsigned NumElts = Mask->getType()->getVectorNumElements();
776 SmallVector<Constant *, 16> NewShufElts(NumElts);
777 SmallVector<Constant *, 16> NewMaskElts(NumElts);
778 for (unsigned I = 0; I != NumElts; ++I) {
779 if (I == InsEltIndex) {
780 NewShufElts[I] = InsEltScalar;
781 Type *Int32Ty = Type::getInt32Ty(Shuf->getContext());
782 NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts);
783 } else {
784 // Copy over the existing values.
785 NewShufElts[I] = ShufConstVec->getAggregateElement(I);
786 NewMaskElts[I] = Mask->getAggregateElement(I);
787 }
Sanjay Patel521f19f2016-09-02 17:05:43 +0000788 }
Sanjay Patel521f19f2016-09-02 17:05:43 +0000789
Alexey Bataevfee90782016-09-23 09:14:08 +0000790 // Create new operands for a shuffle that includes the constant of the
791 // original insertelt. The old shuffle will be dead now.
792 return new ShuffleVectorInst(Shuf->getOperand(0),
793 ConstantVector::get(NewShufElts),
794 ConstantVector::get(NewMaskElts));
795 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
796 // Transform sequences of insertelements ops with constant data/indexes into
797 // a single shuffle op.
798 unsigned NumElts = InsElt.getType()->getNumElements();
799
800 uint64_t InsertIdx[2];
801 Constant *Val[2];
802 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
803 !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
804 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
805 !match(IEI->getOperand(1), m_Constant(Val[1])))
806 return nullptr;
807 SmallVector<Constant *, 16> Values(NumElts);
808 SmallVector<Constant *, 16> Mask(NumElts);
809 auto ValI = std::begin(Val);
810 // Generate new constant vector and mask.
811 // We have 2 values/masks from the insertelements instructions. Insert them
812 // into new value/mask vectors.
813 for (uint64_t I : InsertIdx) {
814 if (!Values[I]) {
815 assert(!Mask[I]);
816 Values[I] = *ValI;
817 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()),
818 NumElts + I);
819 }
820 ++ValI;
821 }
822 // Remaining values are filled with 'undef' values.
823 for (unsigned I = 0; I < NumElts; ++I) {
824 if (!Values[I]) {
825 assert(!Mask[I]);
826 Values[I] = UndefValue::get(InsElt.getType()->getElementType());
827 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I);
828 }
829 }
830 // Create new operands for a shuffle that includes the constant of the
831 // original insertelt.
832 return new ShuffleVectorInst(IEI->getOperand(0),
833 ConstantVector::get(Values),
834 ConstantVector::get(Mask));
835 }
836 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000837}
838
Chris Lattnerec97a902010-01-05 05:36:20 +0000839Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
840 Value *VecOp = IE.getOperand(0);
841 Value *ScalarOp = IE.getOperand(1);
842 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000843
Igor Laevskye0edb662017-12-13 11:21:18 +0000844 if (auto *V = SimplifyInsertElementInst(
845 VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
846 return replaceInstUsesWith(IE, V);
847
Chris Lattnerec97a902010-01-05 05:36:20 +0000848 // Inserting an undef or into an undefined place, remove this.
849 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
Sanjay Patel4b198802016-02-01 22:23:39 +0000850 replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000851
852 // If the inserted element was extracted from some other vector, and if the
Chris Lattnerec97a902010-01-05 05:36:20 +0000853 // indexes are constant, try to turn this into a shufflevector operation.
854 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000855 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
856 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
857 unsigned NumExtractVectorElts =
858 EI->getOperand(0)->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000859 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000860 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000861 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000862
Tim Northoverfad27612014-03-07 10:24:44 +0000863 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
Sanjay Patel4b198802016-02-01 22:23:39 +0000864 return replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000865
Tim Northoverfad27612014-03-07 10:24:44 +0000866 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
Sanjay Patel4b198802016-02-01 22:23:39 +0000867 return replaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000868
Chris Lattnerec97a902010-01-05 05:36:20 +0000869 // If we are extracting a value from a vector, then inserting it right
870 // back into the same place, just use the input vector.
871 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
Sanjay Patel4b198802016-02-01 22:23:39 +0000872 return replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000873
Chris Lattnerec97a902010-01-05 05:36:20 +0000874 // If this insertelement isn't used by some other insertelement, turn it
875 // (and any insertelements it points to), into one big shuffle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000876 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
Chris Lattner0256be92012-01-27 03:08:05 +0000877 SmallVector<Constant*, 16> Mask;
Sanjay Patelae945e72015-12-24 21:17:56 +0000878 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
Tim Northoverfad27612014-03-07 10:24:44 +0000879
880 // The proposed shuffle may be trivial, in which case we shouldn't
881 // perform the combine.
882 if (LR.first != &IE && LR.second != &IE) {
883 // We now have a shuffle of LHS, RHS, Mask.
Craig Topperf40110f2014-04-25 05:29:35 +0000884 if (LR.second == nullptr)
885 LR.second = UndefValue::get(LR.first->getType());
Tim Northoverfad27612014-03-07 10:24:44 +0000886 return new ShuffleVectorInst(LR.first, LR.second,
887 ConstantVector::get(Mask));
888 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000889 }
890 }
891 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000892
Craig Topper17b55682016-12-29 07:03:18 +0000893 unsigned VWidth = VecOp->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000894 APInt UndefElts(VWidth, 0);
895 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000896 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
897 if (V != &IE)
Sanjay Patel4b198802016-02-01 22:23:39 +0000898 return replaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000899 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000900 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000901
Sanjay Patel521f19f2016-09-02 17:05:43 +0000902 if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
903 return Shuf;
904
Craig Topperbb4069e2017-07-07 23:16:26 +0000905 if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
Sanjay Patel2f602ce2017-03-22 17:10:44 +0000906 return NewInsElt;
907
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000908 // Turn a sequence of inserts that broadcasts a scalar into a single
909 // insert + shufflevector.
910 if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE))
911 return Broadcast;
912
Craig Topperf40110f2014-04-25 05:29:35 +0000913 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000914}
915
Nick Lewyckya2b77202013-05-31 00:59:42 +0000916/// Return true if we can evaluate the specified expression tree if the vector
917/// elements were shuffled in a different order.
Sanjay Patel54d31ef2018-09-29 15:05:24 +0000918static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask,
Nick Lewycky3f715e22013-06-01 20:51:31 +0000919 unsigned Depth = 5) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000920 // We can always reorder the elements of a constant.
921 if (isa<Constant>(V))
922 return true;
923
924 // We won't reorder vector arguments. No IPO here.
925 Instruction *I = dyn_cast<Instruction>(V);
926 if (!I) return false;
927
928 // Two users may expect different orders of the elements. Don't try it.
929 if (!I->hasOneUse())
930 return false;
931
932 if (Depth == 0) return false;
933
934 switch (I->getOpcode()) {
935 case Instruction::Add:
936 case Instruction::FAdd:
937 case Instruction::Sub:
938 case Instruction::FSub:
939 case Instruction::Mul:
940 case Instruction::FMul:
941 case Instruction::UDiv:
942 case Instruction::SDiv:
943 case Instruction::FDiv:
944 case Instruction::URem:
945 case Instruction::SRem:
946 case Instruction::FRem:
947 case Instruction::Shl:
948 case Instruction::LShr:
949 case Instruction::AShr:
950 case Instruction::And:
951 case Instruction::Or:
952 case Instruction::Xor:
953 case Instruction::ICmp:
954 case Instruction::FCmp:
955 case Instruction::Trunc:
956 case Instruction::ZExt:
957 case Instruction::SExt:
958 case Instruction::FPToUI:
959 case Instruction::FPToSI:
960 case Instruction::UIToFP:
961 case Instruction::SIToFP:
962 case Instruction::FPTrunc:
963 case Instruction::FPExt:
964 case Instruction::GetElementPtr: {
Sanjay Patel26c119a2018-09-30 13:50:42 +0000965 // Bail out if we would create longer vector ops. We could allow creating
966 // longer vector ops, but that may result in more expensive codegen. We
967 // would also need to limit the transform to avoid undefined behavior for
968 // integer div/rem.
969 Type *ITy = I->getType();
970 if (ITy->isVectorTy() && Mask.size() > ITy->getVectorNumElements())
971 return false;
Sanjay Patel4e28753142015-11-16 22:16:52 +0000972 for (Value *Operand : I->operands()) {
Sanjay Patel54d31ef2018-09-29 15:05:24 +0000973 if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
Nick Lewyckya2b77202013-05-31 00:59:42 +0000974 return false;
975 }
976 return true;
977 }
978 case Instruction::InsertElement: {
979 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
980 if (!CI) return false;
981 int ElementNumber = CI->getLimitedValue();
982
983 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
984 // can't put an element into multiple indices.
985 bool SeenOnce = false;
986 for (int i = 0, e = Mask.size(); i != e; ++i) {
987 if (Mask[i] == ElementNumber) {
988 if (SeenOnce)
989 return false;
990 SeenOnce = true;
991 }
992 }
Sanjay Patel54d31ef2018-09-29 15:05:24 +0000993 return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000994 }
995 }
996 return false;
997}
998
999/// Rebuild a new instruction just like 'I' but with the new operands given.
1000/// In the event of type mismatch, the type of the operands is correct.
Sanjay Patel431e1142015-11-17 17:24:08 +00001001static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
Nick Lewyckya2b77202013-05-31 00:59:42 +00001002 // We don't want to use the IRBuilder here because we want the replacement
1003 // instructions to appear next to 'I', not the builder's insertion point.
1004 switch (I->getOpcode()) {
1005 case Instruction::Add:
1006 case Instruction::FAdd:
1007 case Instruction::Sub:
1008 case Instruction::FSub:
1009 case Instruction::Mul:
1010 case Instruction::FMul:
1011 case Instruction::UDiv:
1012 case Instruction::SDiv:
1013 case Instruction::FDiv:
1014 case Instruction::URem:
1015 case Instruction::SRem:
1016 case Instruction::FRem:
1017 case Instruction::Shl:
1018 case Instruction::LShr:
1019 case Instruction::AShr:
1020 case Instruction::And:
1021 case Instruction::Or:
1022 case Instruction::Xor: {
1023 BinaryOperator *BO = cast<BinaryOperator>(I);
1024 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
1025 BinaryOperator *New =
1026 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
1027 NewOps[0], NewOps[1], "", BO);
1028 if (isa<OverflowingBinaryOperator>(BO)) {
1029 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
1030 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
1031 }
1032 if (isa<PossiblyExactOperator>(BO)) {
1033 New->setIsExact(BO->isExact());
1034 }
Owen Anderson48b842e2014-01-18 00:48:14 +00001035 if (isa<FPMathOperator>(BO))
1036 New->copyFastMathFlags(I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001037 return New;
1038 }
1039 case Instruction::ICmp:
1040 assert(NewOps.size() == 2 && "icmp with #ops != 2");
1041 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
1042 NewOps[0], NewOps[1]);
1043 case Instruction::FCmp:
1044 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
1045 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
1046 NewOps[0], NewOps[1]);
1047 case Instruction::Trunc:
1048 case Instruction::ZExt:
1049 case Instruction::SExt:
1050 case Instruction::FPToUI:
1051 case Instruction::FPToSI:
1052 case Instruction::UIToFP:
1053 case Instruction::SIToFP:
1054 case Instruction::FPTrunc:
1055 case Instruction::FPExt: {
1056 // It's possible that the mask has a different number of elements from
1057 // the original cast. We recompute the destination type to match the mask.
1058 Type *DestTy =
1059 VectorType::get(I->getType()->getScalarType(),
1060 NewOps[0]->getType()->getVectorNumElements());
1061 assert(NewOps.size() == 1 && "cast with #ops != 1");
1062 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
1063 "", I);
1064 }
1065 case Instruction::GetElementPtr: {
1066 Value *Ptr = NewOps[0];
1067 ArrayRef<Value*> Idx = NewOps.slice(1);
David Blaikie22319eb2015-03-14 19:24:04 +00001068 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1069 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001070 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1071 return GEP;
1072 }
1073 }
1074 llvm_unreachable("failed to rebuild vector instructions");
1075}
1076
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001077static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
Nick Lewyckya2b77202013-05-31 00:59:42 +00001078 // Mask.size() does not need to be equal to the number of vector elements.
1079
1080 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
Sanjay Patelce36b032017-10-09 17:54:46 +00001081 Type *EltTy = V->getType()->getScalarType();
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001082 Type *I32Ty = IntegerType::getInt32Ty(V->getContext());
Sanjay Patelce36b032017-10-09 17:54:46 +00001083 if (isa<UndefValue>(V))
1084 return UndefValue::get(VectorType::get(EltTy, Mask.size()));
1085
1086 if (isa<ConstantAggregateZero>(V))
1087 return ConstantAggregateZero::get(VectorType::get(EltTy, Mask.size()));
1088
Nick Lewyckya2b77202013-05-31 00:59:42 +00001089 if (Constant *C = dyn_cast<Constant>(V)) {
1090 SmallVector<Constant *, 16> MaskValues;
1091 for (int i = 0, e = Mask.size(); i != e; ++i) {
1092 if (Mask[i] == -1)
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001093 MaskValues.push_back(UndefValue::get(I32Ty));
Nick Lewyckya2b77202013-05-31 00:59:42 +00001094 else
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001095 MaskValues.push_back(ConstantInt::get(I32Ty, Mask[i]));
Nick Lewyckya2b77202013-05-31 00:59:42 +00001096 }
1097 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
1098 ConstantVector::get(MaskValues));
1099 }
1100
1101 Instruction *I = cast<Instruction>(V);
1102 switch (I->getOpcode()) {
1103 case Instruction::Add:
1104 case Instruction::FAdd:
1105 case Instruction::Sub:
1106 case Instruction::FSub:
1107 case Instruction::Mul:
1108 case Instruction::FMul:
1109 case Instruction::UDiv:
1110 case Instruction::SDiv:
1111 case Instruction::FDiv:
1112 case Instruction::URem:
1113 case Instruction::SRem:
1114 case Instruction::FRem:
1115 case Instruction::Shl:
1116 case Instruction::LShr:
1117 case Instruction::AShr:
1118 case Instruction::And:
1119 case Instruction::Or:
1120 case Instruction::Xor:
1121 case Instruction::ICmp:
1122 case Instruction::FCmp:
1123 case Instruction::Trunc:
1124 case Instruction::ZExt:
1125 case Instruction::SExt:
1126 case Instruction::FPToUI:
1127 case Instruction::FPToSI:
1128 case Instruction::UIToFP:
1129 case Instruction::SIToFP:
1130 case Instruction::FPTrunc:
1131 case Instruction::FPExt:
1132 case Instruction::Select:
1133 case Instruction::GetElementPtr: {
1134 SmallVector<Value*, 8> NewOps;
1135 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
1136 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001137 Value *V = evaluateInDifferentElementOrder(I->getOperand(i), Mask);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001138 NewOps.push_back(V);
1139 NeedsRebuild |= (V != I->getOperand(i));
1140 }
1141 if (NeedsRebuild) {
Sanjay Patel431e1142015-11-17 17:24:08 +00001142 return buildNew(I, NewOps);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001143 }
1144 return I;
1145 }
1146 case Instruction::InsertElement: {
1147 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
Nick Lewyckya2b77202013-05-31 00:59:42 +00001148
1149 // The insertelement was inserting at Element. Figure out which element
1150 // that becomes after shuffling. The answer is guaranteed to be unique
1151 // by CanEvaluateShuffled.
Nick Lewycky3f715e22013-06-01 20:51:31 +00001152 bool Found = false;
Nick Lewyckya2b77202013-05-31 00:59:42 +00001153 int Index = 0;
Nick Lewycky3f715e22013-06-01 20:51:31 +00001154 for (int e = Mask.size(); Index != e; ++Index) {
1155 if (Mask[Index] == Element) {
1156 Found = true;
Nick Lewyckya2b77202013-05-31 00:59:42 +00001157 break;
Nick Lewycky3f715e22013-06-01 20:51:31 +00001158 }
1159 }
Nick Lewyckya2b77202013-05-31 00:59:42 +00001160
Hao Liu26abebb2014-01-08 03:06:15 +00001161 // If element is not in Mask, no need to handle the operand 1 (element to
1162 // be inserted). Just evaluate values in operand 0 according to Mask.
Nick Lewycky3f715e22013-06-01 20:51:31 +00001163 if (!Found)
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001164 return evaluateInDifferentElementOrder(I->getOperand(0), Mask);
Joey Goulya3250f22013-07-12 23:08:06 +00001165
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001166 Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001167 return InsertElementInst::Create(V, I->getOperand(1),
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001168 ConstantInt::get(I32Ty, Index), "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001169 }
1170 }
1171 llvm_unreachable("failed to reorder elements of vector instruction!");
1172}
Chris Lattnerec97a902010-01-05 05:36:20 +00001173
Sanjay Patel431e1142015-11-17 17:24:08 +00001174static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001175 bool &isLHSID, bool &isRHSID) {
1176 isLHSID = isRHSID = true;
1177
1178 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
1179 if (Mask[i] < 0) continue; // Ignore undef values.
1180 // Is this an identity shuffle of the LHS value?
1181 isLHSID &= (Mask[i] == (int)i);
1182
1183 // Is this an identity shuffle of the RHS value?
1184 isRHSID &= (Mask[i]-e == i);
1185 }
1186}
1187
JF Bastiend52c9902015-02-25 22:30:51 +00001188// Returns true if the shuffle is extracting a contiguous range of values from
1189// LHS, for example:
1190// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1191// Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1192// Shuffles to: |EE|FF|GG|HH|
1193// +--+--+--+--+
1194static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1195 SmallVector<int, 16> &Mask) {
Craig Topper17b55682016-12-29 07:03:18 +00001196 unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements();
JF Bastiend52c9902015-02-25 22:30:51 +00001197 unsigned MaskElems = Mask.size();
1198 unsigned BegIdx = Mask.front();
1199 unsigned EndIdx = Mask.back();
1200 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1201 return false;
1202 for (unsigned I = 0; I != MaskElems; ++I)
1203 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
1204 return false;
1205 return true;
1206}
1207
Sanjay Patelb999d742018-07-02 17:42:29 +00001208/// These are the ingredients in an alternate form binary operator as described
1209/// below.
1210struct BinopElts {
1211 BinaryOperator::BinaryOps Opcode;
1212 Value *Op0;
1213 Value *Op1;
1214 BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0,
1215 Value *V0 = nullptr, Value *V1 = nullptr) :
1216 Opcode(Opc), Op0(V0), Op1(V1) {}
1217 operator bool() const { return Opcode != 0; }
1218};
1219
1220/// Binops may be transformed into binops with different opcodes and operands.
1221/// Reverse the usual canonicalization to enable folds with the non-canonical
1222/// form of the binop. If a transform is possible, return the elements of the
1223/// new binop. If not, return invalid elements.
1224static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) {
1225 Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
1226 Type *Ty = BO->getType();
1227 switch (BO->getOpcode()) {
1228 case Instruction::Shl: {
1229 // shl X, C --> mul X, (1 << C)
1230 Constant *C;
1231 if (match(BO1, m_Constant(C))) {
1232 Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C);
1233 return { Instruction::Mul, BO0, ShlOne };
1234 }
1235 break;
1236 }
1237 case Instruction::Or: {
1238 // or X, C --> add X, C (when X and C have no common bits set)
1239 const APInt *C;
1240 if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL))
1241 return { Instruction::Add, BO0, BO1 };
1242 break;
1243 }
1244 default:
1245 break;
1246 }
1247 return {};
1248}
1249
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001250static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) {
1251 assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
1252
1253 // Are we shuffling together some value and that same value after it has been
1254 // modified by a binop with a constant?
1255 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
1256 Constant *C;
1257 bool Op0IsBinop;
1258 if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
1259 Op0IsBinop = true;
1260 else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
1261 Op0IsBinop = false;
1262 else
1263 return nullptr;
1264
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001265 // The identity constant for a binop leaves a variable operand unchanged. For
1266 // a vector, this is a splat of something like 0, -1, or 1.
1267 // If there's no identity constant for this binop, we're done.
Sanjay Patel509a1e72018-07-10 15:12:31 +00001268 auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001269 BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
Sanjay Patel509a1e72018-07-10 15:12:31 +00001270 Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001271 if (!IdC)
1272 return nullptr;
1273
1274 // Shuffle identity constants into the lanes that return the original value.
1275 // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
1276 // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
1277 // The existing binop constant vector remains in the same operand position.
1278 Constant *Mask = Shuf.getMask();
1279 Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
1280 ConstantExpr::getShuffleVector(IdC, C, Mask);
1281
Sanjay Patel509a1e72018-07-10 15:12:31 +00001282 bool MightCreatePoisonOrUB =
1283 Mask->containsUndefElement() &&
1284 (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
1285 if (MightCreatePoisonOrUB)
1286 NewC = getSafeVectorConstantForBinop(BOpcode, NewC, true);
1287
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001288 // shuf (bop X, C), X, M --> bop X, C'
1289 // shuf X, (bop X, C), M --> bop X, C'
Sanjay Patel509a1e72018-07-10 15:12:31 +00001290 Value *X = Op0IsBinop ? Op1 : Op0;
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001291 Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
1292 NewBO->copyIRFlags(BO);
Sanjay Patel33331062018-07-10 14:27:55 +00001293
1294 // An undef shuffle mask element may propagate as an undef constant element in
1295 // the new binop. That would produce poison where the original code might not.
Sanjay Patel509a1e72018-07-10 15:12:31 +00001296 // If we already made a safe constant, then there's no danger.
1297 if (Mask->containsUndefElement() && !MightCreatePoisonOrUB)
Sanjay Patel33331062018-07-10 14:27:55 +00001298 NewBO->dropPoisonGeneratingFlags();
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001299 return NewBO;
1300}
1301
Sanjay Patelb999d742018-07-02 17:42:29 +00001302/// Try to fold shuffles that are the equivalent of a vector select.
Sanjay Patelda667532018-06-29 13:44:06 +00001303static Instruction *foldSelectShuffle(ShuffleVectorInst &Shuf,
Sanjay Patelb999d742018-07-02 17:42:29 +00001304 InstCombiner::BuilderTy &Builder,
1305 const DataLayout &DL) {
Sanjay Patela76b7002018-06-21 20:15:09 +00001306 if (!Shuf.isSelect())
1307 return nullptr;
1308
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001309 if (Instruction *I = foldSelectShuffleWith1Binop(Shuf))
1310 return I;
1311
Sanjay Patela76b7002018-06-21 20:15:09 +00001312 BinaryOperator *B0, *B1;
1313 if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
1314 !match(Shuf.getOperand(1), m_BinOp(B1)))
1315 return nullptr;
1316
Sanjay Patelda667532018-06-29 13:44:06 +00001317 Value *X, *Y;
Sanjay Patela76b7002018-06-21 20:15:09 +00001318 Constant *C0, *C1;
Sanjay Patela52963b2018-06-22 12:46:16 +00001319 bool ConstantsAreOp1;
1320 if (match(B0, m_BinOp(m_Value(X), m_Constant(C0))) &&
Sanjay Patelda667532018-06-29 13:44:06 +00001321 match(B1, m_BinOp(m_Value(Y), m_Constant(C1))))
Sanjay Patela52963b2018-06-22 12:46:16 +00001322 ConstantsAreOp1 = true;
1323 else if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
Sanjay Patelda667532018-06-29 13:44:06 +00001324 match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
Sanjay Patela52963b2018-06-22 12:46:16 +00001325 ConstantsAreOp1 = false;
1326 else
Sanjay Patela76b7002018-06-21 20:15:09 +00001327 return nullptr;
1328
Sanjay Patel57bda362018-06-28 17:48:04 +00001329 // We need matching binops to fold the lanes together.
1330 BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
1331 BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
1332 bool DropNSW = false;
1333 if (ConstantsAreOp1 && Opc0 != Opc1) {
Sanjay Patel57bda362018-06-28 17:48:04 +00001334 // TODO: We drop "nsw" if shift is converted into multiply because it may
1335 // not be correct when the shift amount is BitWidth - 1. We could examine
1336 // each vector element to determine if it is safe to keep that flag.
Sanjay Patelb999d742018-07-02 17:42:29 +00001337 if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
Sanjay Patel57bda362018-06-28 17:48:04 +00001338 DropNSW = true;
Sanjay Patelb999d742018-07-02 17:42:29 +00001339 if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
1340 assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
1341 Opc0 = AltB0.Opcode;
1342 C0 = cast<Constant>(AltB0.Op1);
1343 } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
1344 assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
1345 Opc1 = AltB1.Opcode;
1346 C1 = cast<Constant>(AltB1.Op1);
Sanjay Patel57bda362018-06-28 17:48:04 +00001347 }
1348 }
1349
1350 if (Opc0 != Opc1)
Sanjay Patel4784e152018-06-21 23:56:59 +00001351 return nullptr;
1352
Sanjay Patel57bda362018-06-28 17:48:04 +00001353 // The opcodes must be the same. Use a new name to make that clear.
1354 BinaryOperator::BinaryOps BOpc = Opc0;
1355
Sanjay Patel06ea4202018-07-10 13:33:26 +00001356 // Select the constant elements needed for the single binop.
1357 Constant *Mask = Shuf.getMask();
1358 Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
1359
Sanjay Patel5bd36642018-07-09 13:21:46 +00001360 // We are moving a binop after a shuffle. When a shuffle has an undefined
1361 // mask element, the result is undefined, but it is not poison or undefined
1362 // behavior. That is not necessarily true for div/rem/shift.
Sanjay Patel5bd36642018-07-09 13:21:46 +00001363 bool MightCreatePoisonOrUB =
1364 Mask->containsUndefElement() &&
1365 (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc));
Sanjay Patel06ea4202018-07-10 13:33:26 +00001366 if (MightCreatePoisonOrUB)
1367 NewC = getSafeVectorConstantForBinop(BOpc, NewC, ConstantsAreOp1);
Sanjay Patel5bd36642018-07-09 13:21:46 +00001368
Sanjay Patelda667532018-06-29 13:44:06 +00001369 Value *V;
1370 if (X == Y) {
1371 // Remove a binop and the shuffle by rearranging the constant:
1372 // shuffle (op V, C0), (op V, C1), M --> op V, C'
1373 // shuffle (op C0, V), (op C1, V), M --> op C', V
1374 V = X;
Sanjay Patel5bd36642018-07-09 13:21:46 +00001375 } else {
Sanjay Patelda667532018-06-29 13:44:06 +00001376 // If there are 2 different variable operands, we must create a new shuffle
1377 // (select) first, so check uses to ensure that we don't end up with more
1378 // instructions than we started with.
Sanjay Patel5bd36642018-07-09 13:21:46 +00001379 if (!B0->hasOneUse() && !B1->hasOneUse())
1380 return nullptr;
1381
Sanjay Patel06ea4202018-07-10 13:33:26 +00001382 // If we use the original shuffle mask and op1 is *variable*, we would be
1383 // putting an undef into operand 1 of div/rem/shift. This is either UB or
1384 // poison. We do not have to guard against UB when *constants* are op1
1385 // because safe constants guarantee that we do not overflow sdiv/srem (and
1386 // there's no danger for other opcodes).
1387 // TODO: To allow this case, create a new shuffle mask with no undefs.
1388 if (MightCreatePoisonOrUB && !ConstantsAreOp1)
Sanjay Patel5bd36642018-07-09 13:21:46 +00001389 return nullptr;
1390
Sanjay Patelda667532018-06-29 13:44:06 +00001391 // Note: In general, we do not create new shuffles in InstCombine because we
1392 // do not know if a target can lower an arbitrary shuffle optimally. In this
1393 // case, the shuffle uses the existing mask, so there is no additional risk.
Sanjay Patelda667532018-06-29 13:44:06 +00001394
1395 // Select the variable vectors first, then perform the binop:
1396 // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
1397 // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
Sanjay Patel5bd36642018-07-09 13:21:46 +00001398 V = Builder.CreateShuffleVector(X, Y, Mask);
Sanjay Patelda667532018-06-29 13:44:06 +00001399 }
1400
Sanjay Patelda667532018-06-29 13:44:06 +00001401 Instruction *NewBO = ConstantsAreOp1 ? BinaryOperator::Create(BOpc, V, NewC) :
1402 BinaryOperator::Create(BOpc, NewC, V);
Sanjay Patela76b7002018-06-21 20:15:09 +00001403
Sanjay Patel5bd36642018-07-09 13:21:46 +00001404 // Flags are intersected from the 2 source binops. But there are 2 exceptions:
1405 // 1. If we changed an opcode, poison conditions might have changed.
1406 // 2. If the shuffle had undef mask elements, the new binop might have undefs
Sanjay Patelc8d9d812018-07-10 16:09:49 +00001407 // where the original code did not. But if we already made a safe constant,
1408 // then there's no danger.
Sanjay Patela76b7002018-06-21 20:15:09 +00001409 NewBO->copyIRFlags(B0);
1410 NewBO->andIRFlags(B1);
Sanjay Patel57bda362018-06-28 17:48:04 +00001411 if (DropNSW)
1412 NewBO->setHasNoSignedWrap(false);
Sanjay Patelc8d9d812018-07-10 16:09:49 +00001413 if (Mask->containsUndefElement() && !MightCreatePoisonOrUB)
Sanjay Patel5bd36642018-07-09 13:21:46 +00001414 NewBO->dropPoisonGeneratingFlags();
Sanjay Patela76b7002018-06-21 20:15:09 +00001415 return NewBO;
1416}
1417
Sanjay Patelc1416b62018-09-07 21:03:34 +00001418/// Match a shuffle-select-shuffle pattern where the shuffles are widening and
1419/// narrowing (concatenating with undef and extracting back to the original
1420/// length). This allows replacing the wide select with a narrow select.
1421Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf,
1422 InstCombiner::BuilderTy &Builder) {
1423 // This must be a narrowing identity shuffle. It extracts the 1st N elements
1424 // of the 1st vector operand of a shuffle.
1425 if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract())
1426 return nullptr;
1427
1428 // The vector being shuffled must be a vector select that we can eliminate.
1429 // TODO: The one-use requirement could be eased if X and/or Y are constants.
1430 Value *Cond, *X, *Y;
1431 if (!match(Shuf.getOperand(0),
1432 m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))))
1433 return nullptr;
1434
1435 // We need a narrow condition value. It must be extended with undef elements
1436 // and have the same number of elements as this shuffle.
1437 unsigned NarrowNumElts = Shuf.getType()->getVectorNumElements();
1438 Value *NarrowCond;
1439 if (!match(Cond, m_OneUse(m_ShuffleVector(m_Value(NarrowCond), m_Undef(),
1440 m_Constant()))) ||
1441 NarrowCond->getType()->getVectorNumElements() != NarrowNumElts ||
1442 !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
1443 return nullptr;
1444
1445 // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) -->
1446 // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask)
1447 Value *Undef = UndefValue::get(X->getType());
1448 Value *NarrowX = Builder.CreateShuffleVector(X, Undef, Shuf.getMask());
1449 Value *NarrowY = Builder.CreateShuffleVector(Y, Undef, Shuf.getMask());
1450 return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
1451}
1452
Chris Lattnerec97a902010-01-05 05:36:20 +00001453Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
1454 Value *LHS = SVI.getOperand(0);
1455 Value *RHS = SVI.getOperand(1);
Craig Toppera4205622017-06-09 03:21:29 +00001456 if (auto *V = SimplifyShuffleVectorInst(
1457 LHS, RHS, SVI.getMask(), SVI.getType(), SQ.getWithInstruction(&SVI)))
Zvi Rackover82bf48d2017-04-04 04:47:57 +00001458 return replaceInstUsesWith(SVI, V);
1459
Sanjay Patelb999d742018-07-02 17:42:29 +00001460 if (Instruction *I = foldSelectShuffle(SVI, Builder, DL))
Sanjay Patela76b7002018-06-21 20:15:09 +00001461 return I;
1462
Sanjay Patelc1416b62018-09-07 21:03:34 +00001463 if (Instruction *I = narrowVectorSelect(SVI, Builder))
1464 return I;
1465
Craig Topper17b55682016-12-29 07:03:18 +00001466 unsigned VWidth = SVI.getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +00001467 APInt UndefElts(VWidth, 0);
1468 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +00001469 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
1470 if (V != &SVI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001471 return replaceInstUsesWith(SVI, V);
Sanjay Patele6b48a12017-08-31 15:57:17 +00001472 return &SVI;
Chris Lattnerec97a902010-01-05 05:36:20 +00001473 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001474
Sanjay Pateld4e19d22018-08-29 14:42:12 +00001475 SmallVector<int, 16> Mask = SVI.getShuffleMask();
1476 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
Craig Topper17b55682016-12-29 07:03:18 +00001477 unsigned LHSWidth = LHS->getType()->getVectorNumElements();
Sanjay Pateld4e19d22018-08-29 14:42:12 +00001478 bool MadeChange = false;
Eli Friedmance818272011-10-21 19:06:29 +00001479
Chris Lattnerec97a902010-01-05 05:36:20 +00001480 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
1481 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
1482 if (LHS == RHS || isa<UndefValue>(LHS)) {
Chris Lattnerec97a902010-01-05 05:36:20 +00001483 // Remap any references to RHS to use LHS.
Chris Lattner0256be92012-01-27 03:08:05 +00001484 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00001485 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00001486 if (Mask[i] < 0) {
JF Bastiend52c9902015-02-25 22:30:51 +00001487 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +00001488 continue;
1489 }
1490
1491 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
1492 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
1493 Mask[i] = -1; // Turn into undef.
JF Bastiend52c9902015-02-25 22:30:51 +00001494 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +00001495 } else {
1496 Mask[i] = Mask[i] % e; // Force to LHS.
JF Bastiend52c9902015-02-25 22:30:51 +00001497 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
Chris Lattnerec97a902010-01-05 05:36:20 +00001498 }
1499 }
1500 SVI.setOperand(0, SVI.getOperand(1));
1501 SVI.setOperand(1, UndefValue::get(RHS->getType()));
1502 SVI.setOperand(2, ConstantVector::get(Elts));
1503 LHS = SVI.getOperand(0);
1504 RHS = SVI.getOperand(1);
1505 MadeChange = true;
1506 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001507
Eli Friedmance818272011-10-21 19:06:29 +00001508 if (VWidth == LHSWidth) {
1509 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001510 bool isLHSID, isRHSID;
Sanjay Patel431e1142015-11-17 17:24:08 +00001511 recognizeIdentityMask(Mask, isLHSID, isRHSID);
Eli Friedmance818272011-10-21 19:06:29 +00001512
1513 // Eliminate identity shuffles.
Sanjay Patel4b198802016-02-01 22:23:39 +00001514 if (isLHSID) return replaceInstUsesWith(SVI, LHS);
1515 if (isRHSID) return replaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +00001516 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001517
Sanjay Patel26c119a2018-09-30 13:50:42 +00001518 if (isa<UndefValue>(RHS) && canEvaluateShuffled(LHS, Mask)) {
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001519 Value *V = evaluateInDifferentElementOrder(LHS, Mask);
Sanjay Patel4b198802016-02-01 22:23:39 +00001520 return replaceInstUsesWith(SVI, V);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001521 }
1522
JF Bastiend52c9902015-02-25 22:30:51 +00001523 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
1524 // a non-vector type. We can instead bitcast the original vector followed by
1525 // an extract of the desired element:
1526 //
1527 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
1528 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
1529 // %1 = bitcast <4 x i8> %sroa to i32
1530 // Becomes:
1531 // %bc = bitcast <16 x i8> %in to <4 x i32>
1532 // %ext = extractelement <4 x i32> %bc, i32 0
1533 //
1534 // If the shuffle is extracting a contiguous range of values from the input
1535 // vector then each use which is a bitcast of the extracted size can be
1536 // replaced. This will work if the vector types are compatible, and the begin
1537 // index is aligned to a value in the casted vector type. If the begin index
1538 // isn't aligned then we can shuffle the original vector (keeping the same
1539 // vector type) before extracting.
1540 //
1541 // This code will bail out if the target type is fundamentally incompatible
1542 // with vectors of the source type.
1543 //
1544 // Example of <16 x i8>, target type i32:
1545 // Index range [4,8): v-----------v Will work.
1546 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1547 // <16 x i8>: | | | | | | | | | | | | | | | | |
1548 // <4 x i32>: | | | | |
1549 // +-----------+-----------+-----------+-----------+
1550 // Index range [6,10): ^-----------^ Needs an extra shuffle.
1551 // Target type i40: ^--------------^ Won't work, bail.
1552 if (isShuffleExtractingFromLHS(SVI, Mask)) {
1553 Value *V = LHS;
1554 unsigned MaskElems = Mask.size();
JF Bastiend52c9902015-02-25 22:30:51 +00001555 VectorType *SrcTy = cast<VectorType>(V->getType());
1556 unsigned VecBitWidth = SrcTy->getBitWidth();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001557 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
JF Bastiend52c9902015-02-25 22:30:51 +00001558 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1559 unsigned SrcNumElems = SrcTy->getNumElements();
1560 SmallVector<BitCastInst *, 8> BCs;
1561 DenseMap<Type *, Value *> NewBCs;
1562 for (User *U : SVI.users())
1563 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1564 if (!BC->use_empty())
1565 // Only visit bitcasts that weren't previously handled.
1566 BCs.push_back(BC);
1567 for (BitCastInst *BC : BCs) {
Eugene Leviant958fcd72017-02-17 07:36:03 +00001568 unsigned BegIdx = Mask.front();
JF Bastiend52c9902015-02-25 22:30:51 +00001569 Type *TgtTy = BC->getDestTy();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001570 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
JF Bastiend52c9902015-02-25 22:30:51 +00001571 if (!TgtElemBitWidth)
1572 continue;
1573 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1574 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1575 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1576 if (!VecBitWidthsEqual)
1577 continue;
1578 if (!VectorType::isValidElementType(TgtTy))
1579 continue;
1580 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1581 if (!BegIsAligned) {
1582 // Shuffle the input so [0,NumElements) contains the output, and
1583 // [NumElems,SrcNumElems) is undef.
1584 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1585 UndefValue::get(Int32Ty));
1586 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1587 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
Craig Topperbb4069e2017-07-07 23:16:26 +00001588 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
1589 ConstantVector::get(ShuffleMask),
1590 SVI.getName() + ".extract");
JF Bastiend52c9902015-02-25 22:30:51 +00001591 BegIdx = 0;
1592 }
1593 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1594 assert(SrcElemsPerTgtElem);
1595 BegIdx /= SrcElemsPerTgtElem;
1596 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1597 auto *NewBC =
1598 BCAlreadyExists
1599 ? NewBCs[CastSrcTy]
Craig Topperbb4069e2017-07-07 23:16:26 +00001600 : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
JF Bastiend52c9902015-02-25 22:30:51 +00001601 if (!BCAlreadyExists)
1602 NewBCs[CastSrcTy] = NewBC;
Craig Topperbb4069e2017-07-07 23:16:26 +00001603 auto *Ext = Builder.CreateExtractElement(
JF Bastiend52c9902015-02-25 22:30:51 +00001604 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1605 // The shufflevector isn't being replaced: the bitcast that used it
1606 // is. InstCombine will visit the newly-created instructions.
Sanjay Patel4b198802016-02-01 22:23:39 +00001607 replaceInstUsesWith(*BC, Ext);
JF Bastiend52c9902015-02-25 22:30:51 +00001608 MadeChange = true;
1609 }
1610 }
1611
Eric Christopher51edc7b2010-08-17 22:55:27 +00001612 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +00001613 // one without producing an unusual shuffle.
1614 // Cases that might be simplified:
1615 // 1.
1616 // x1=shuffle(v1,v2,mask1)
1617 // x=shuffle(x1,undef,mask)
1618 // ==>
1619 // x=shuffle(v1,undef,newMask)
1620 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1621 // 2.
1622 // x1=shuffle(v1,undef,mask1)
1623 // x=shuffle(x1,x2,mask)
1624 // where v1.size() == mask1.size()
1625 // ==>
1626 // x=shuffle(v1,x2,newMask)
1627 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1628 // 3.
1629 // x2=shuffle(v2,undef,mask2)
1630 // x=shuffle(x1,x2,mask)
1631 // where v2.size() == mask2.size()
1632 // ==>
1633 // x=shuffle(x1,v2,newMask)
1634 // newMask[i] = (mask[i] < x1.size())
1635 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1636 // 4.
1637 // x1=shuffle(v1,undef,mask1)
1638 // x2=shuffle(v2,undef,mask2)
1639 // x=shuffle(x1,x2,mask)
1640 // where v1.size() == v2.size()
1641 // ==>
1642 // x=shuffle(v1,v2,newMask)
1643 // newMask[i] = (mask[i] < x1.size())
1644 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1645 //
1646 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +00001647 // we are absolutely afraid of producing a shuffle mask not in the input
1648 // program, because the code gen may not be smart enough to turn a merged
1649 // shuffle into two specific shuffles: it may produce worse code. As such,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001650 // we only merge two shuffles if the result is either a splat or one of the
1651 // input shuffle masks. In this case, merging the shuffles just removes
1652 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +00001653 // turning: (splat(splat)) -> splat, or
1654 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1655 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1656 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1657 if (LHSShuffle)
1658 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
Craig Topperf40110f2014-04-25 05:29:35 +00001659 LHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001660 if (RHSShuffle)
1661 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +00001662 RHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001663 if (!LHSShuffle && !RHSShuffle)
Craig Topperf40110f2014-04-25 05:29:35 +00001664 return MadeChange ? &SVI : nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001665
Craig Topperf40110f2014-04-25 05:29:35 +00001666 Value* LHSOp0 = nullptr;
1667 Value* LHSOp1 = nullptr;
1668 Value* RHSOp0 = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001669 unsigned LHSOp0Width = 0;
1670 unsigned RHSOp0Width = 0;
1671 if (LHSShuffle) {
1672 LHSOp0 = LHSShuffle->getOperand(0);
1673 LHSOp1 = LHSShuffle->getOperand(1);
Craig Topper17b55682016-12-29 07:03:18 +00001674 LHSOp0Width = LHSOp0->getType()->getVectorNumElements();
Eli Friedmance818272011-10-21 19:06:29 +00001675 }
1676 if (RHSShuffle) {
1677 RHSOp0 = RHSShuffle->getOperand(0);
Craig Topper17b55682016-12-29 07:03:18 +00001678 RHSOp0Width = RHSOp0->getType()->getVectorNumElements();
Eli Friedmance818272011-10-21 19:06:29 +00001679 }
1680 Value* newLHS = LHS;
1681 Value* newRHS = RHS;
1682 if (LHSShuffle) {
1683 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +00001684 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +00001685 newLHS = LHSOp0;
1686 newRHS = LHSOp1;
1687 }
1688 // case 2 or 4
1689 else if (LHSOp0Width == LHSWidth) {
1690 newLHS = LHSOp0;
1691 }
1692 }
1693 // case 3 or 4
1694 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1695 newRHS = RHSOp0;
1696 }
1697 // case 4
1698 if (LHSOp0 == RHSOp0) {
1699 newLHS = LHSOp0;
Craig Topperf40110f2014-04-25 05:29:35 +00001700 newRHS = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001701 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001702
Eli Friedmance818272011-10-21 19:06:29 +00001703 if (newLHS == LHS && newRHS == RHS)
Craig Topperf40110f2014-04-25 05:29:35 +00001704 return MadeChange ? &SVI : nullptr;
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001705
Eli Friedmance818272011-10-21 19:06:29 +00001706 SmallVector<int, 16> LHSMask;
1707 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +00001708 if (newLHS != LHS)
1709 LHSMask = LHSShuffle->getShuffleMask();
1710 if (RHSShuffle && newRHS != RHS)
1711 RHSMask = RHSShuffle->getShuffleMask();
1712
Eli Friedmance818272011-10-21 19:06:29 +00001713 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1714 SmallVector<int, 16> newMask;
1715 bool isSplat = true;
1716 int SplatElt = -1;
1717 // Create a new mask for the new ShuffleVectorInst so that the new
1718 // ShuffleVectorInst is equivalent to the original one.
1719 for (unsigned i = 0; i < VWidth; ++i) {
1720 int eltMask;
Craig Topper45d9f4b2013-01-18 05:30:07 +00001721 if (Mask[i] < 0) {
Eli Friedmance818272011-10-21 19:06:29 +00001722 // This element is an undef value.
1723 eltMask = -1;
1724 } else if (Mask[i] < (int)LHSWidth) {
1725 // This element is from left hand side vector operand.
Craig Topper2ea22b02013-01-18 05:09:16 +00001726 //
Eli Friedmance818272011-10-21 19:06:29 +00001727 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1728 // new mask value for the element.
1729 if (newLHS != LHS) {
1730 eltMask = LHSMask[Mask[i]];
1731 // If the value selected is an undef value, explicitly specify it
1732 // with a -1 mask value.
1733 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1734 eltMask = -1;
Craig Topper2ea22b02013-01-18 05:09:16 +00001735 } else
Eli Friedmance818272011-10-21 19:06:29 +00001736 eltMask = Mask[i];
1737 } else {
1738 // This element is from right hand side vector operand
1739 //
1740 // If the value selected is an undef value, explicitly specify it
1741 // with a -1 mask value. (case 1)
1742 if (isa<UndefValue>(RHS))
1743 eltMask = -1;
1744 // If RHS is going to be replaced (case 3 or 4), calculate the
1745 // new mask value for the element.
1746 else if (newRHS != RHS) {
1747 eltMask = RHSMask[Mask[i]-LHSWidth];
1748 // If the value selected is an undef value, explicitly specify it
1749 // with a -1 mask value.
1750 if (eltMask >= (int)RHSOp0Width) {
1751 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1752 && "should have been check above");
1753 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001754 }
Craig Topper2ea22b02013-01-18 05:09:16 +00001755 } else
Eli Friedmance818272011-10-21 19:06:29 +00001756 eltMask = Mask[i]-LHSWidth;
1757
1758 // If LHS's width is changed, shift the mask value accordingly.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001759 // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
Michael Gottesman02a11412012-10-16 21:29:38 +00001760 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1761 // If newRHS == newLHS, we want to remap any references from newRHS to
1762 // newLHS so that we can properly identify splats that may occur due to
Alp Tokercb402912014-01-24 17:20:08 +00001763 // obfuscation across the two vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001764 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001765 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001766 }
Eli Friedmance818272011-10-21 19:06:29 +00001767
1768 // Check if this could still be a splat.
1769 if (eltMask >= 0) {
1770 if (SplatElt >= 0 && SplatElt != eltMask)
1771 isSplat = false;
1772 SplatElt = eltMask;
1773 }
1774
1775 newMask.push_back(eltMask);
1776 }
1777
1778 // If the result mask is equal to one of the original shuffle masks,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001779 // or is a splat, do the replacement.
1780 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
Eli Friedmance818272011-10-21 19:06:29 +00001781 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00001782 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1783 if (newMask[i] < 0) {
1784 Elts.push_back(UndefValue::get(Int32Ty));
1785 } else {
1786 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1787 }
1788 }
Craig Topperf40110f2014-04-25 05:29:35 +00001789 if (!newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001790 newRHS = UndefValue::get(newLHS->getType());
1791 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001792 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001793
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001794 // If the result mask is an identity, replace uses of this instruction with
1795 // corresponding argument.
Serge Pavlovb575ee82014-05-13 06:07:21 +00001796 bool isLHSID, isRHSID;
Sanjay Patel431e1142015-11-17 17:24:08 +00001797 recognizeIdentityMask(newMask, isLHSID, isRHSID);
Sanjay Patel4b198802016-02-01 22:23:39 +00001798 if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS);
1799 if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001800
Craig Topperf40110f2014-04-25 05:29:35 +00001801 return MadeChange ? &SVI : nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +00001802}