Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1 | //===- InstCombineVectorOps.cpp -------------------------------------------===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file implements instcombine for ExtractElement, InsertElement and |
| 10 | // ShuffleVector. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
Chandler Carruth | a917458 | 2015-01-22 05:25:13 +0000 | [diff] [blame] | 14 | #include "InstCombineInternal.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/APInt.h" |
| 16 | #include "llvm/ADT/ArrayRef.h" |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/DenseMap.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/STLExtras.h" |
| 19 | #include "llvm/ADT/SmallVector.h" |
David Majnemer | 599ca44 | 2015-07-13 01:15:53 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/InstructionSimplify.h" |
| 21 | #include "llvm/Analysis/VectorUtils.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 22 | #include "llvm/IR/BasicBlock.h" |
| 23 | #include "llvm/IR/Constant.h" |
| 24 | #include "llvm/IR/Constants.h" |
| 25 | #include "llvm/IR/DerivedTypes.h" |
| 26 | #include "llvm/IR/InstrTypes.h" |
| 27 | #include "llvm/IR/Instruction.h" |
| 28 | #include "llvm/IR/Instructions.h" |
| 29 | #include "llvm/IR/Operator.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 30 | #include "llvm/IR/PatternMatch.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Type.h" |
| 32 | #include "llvm/IR/User.h" |
| 33 | #include "llvm/IR/Value.h" |
| 34 | #include "llvm/Support/Casting.h" |
| 35 | #include "llvm/Support/ErrorHandling.h" |
| 36 | #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" |
| 37 | #include <cassert> |
| 38 | #include <cstdint> |
| 39 | #include <iterator> |
| 40 | #include <utility> |
| 41 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 42 | using namespace llvm; |
Nadav Rotem | 7df8509 | 2013-01-15 23:43:14 +0000 | [diff] [blame] | 43 | using namespace PatternMatch; |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 44 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 45 | #define DEBUG_TYPE "instcombine" |
| 46 | |
Sanjay Patel | 6eccf48 | 2015-09-09 15:24:36 +0000 | [diff] [blame] | 47 | /// Return true if the value is cheaper to scalarize than it is to leave as a |
Sanjay Patel | e51d5bd | 2018-12-18 19:07:38 +0000 | [diff] [blame] | 48 | /// vector operation. IsConstantExtractIndex indicates whether we are extracting |
| 49 | /// one known element from a vector constant. |
| 50 | /// |
| 51 | /// FIXME: It's possible to create more instructions than previously existed. |
| 52 | static bool cheapToScalarize(Value *V, bool IsConstantExtractIndex) { |
| 53 | // If we can pick a scalar constant value out of a vector, that is free. |
| 54 | if (auto *C = dyn_cast<Constant>(V)) |
| 55 | return IsConstantExtractIndex || C->getSplatValue(); |
Chris Lattner | 8326bd8 | 2012-01-26 00:42:34 +0000 | [diff] [blame] | 56 | |
Sanjay Patel | e51d5bd | 2018-12-18 19:07:38 +0000 | [diff] [blame] | 57 | // An insertelement to the same constant index as our extract will simplify |
| 58 | // to the scalar inserted element. An insertelement to a different constant |
| 59 | // index is irrelevant to our extract. |
| 60 | if (match(V, m_InsertElement(m_Value(), m_Value(), m_ConstantInt()))) |
| 61 | return IsConstantExtractIndex; |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 62 | |
Sanjay Patel | e51d5bd | 2018-12-18 19:07:38 +0000 | [diff] [blame] | 63 | if (match(V, m_OneUse(m_Load(m_Value())))) |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 64 | return true; |
Sanjay Patel | e51d5bd | 2018-12-18 19:07:38 +0000 | [diff] [blame] | 65 | |
Simon Moll | d871ef4 | 2020-03-10 16:05:31 +0100 | [diff] [blame] | 66 | if (match(V, m_OneUse(m_UnOp()))) |
| 67 | return true; |
| 68 | |
Sanjay Patel | e51d5bd | 2018-12-18 19:07:38 +0000 | [diff] [blame] | 69 | Value *V0, *V1; |
| 70 | if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1))))) |
| 71 | if (cheapToScalarize(V0, IsConstantExtractIndex) || |
| 72 | cheapToScalarize(V1, IsConstantExtractIndex)) |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 73 | return true; |
Sanjay Patel | e51d5bd | 2018-12-18 19:07:38 +0000 | [diff] [blame] | 74 | |
| 75 | CmpInst::Predicate UnusedPred; |
| 76 | if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1))))) |
| 77 | if (cheapToScalarize(V0, IsConstantExtractIndex) || |
| 78 | cheapToScalarize(V1, IsConstantExtractIndex)) |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 79 | return true; |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 80 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 81 | return false; |
| 82 | } |
| 83 | |
Michael Kuperstein | a0c6ae0 | 2016-06-06 23:38:33 +0000 | [diff] [blame] | 84 | // If we have a PHI node with a vector type that is only used to feed |
Matt Arsenault | 3887473 | 2013-08-28 22:17:26 +0000 | [diff] [blame] | 85 | // itself and be an operand of extractelement at a constant location, |
| 86 | // try to replace the PHI of the vector type with a PHI of a scalar type. |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 87 | Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) { |
Michael Kuperstein | a0c6ae0 | 2016-06-06 23:38:33 +0000 | [diff] [blame] | 88 | SmallVector<Instruction *, 2> Extracts; |
| 89 | // The users we want the PHI to have are: |
| 90 | // 1) The EI ExtractElement (we already know this) |
| 91 | // 2) Possibly more ExtractElements with the same index. |
| 92 | // 3) Another operand, which will feed back into the PHI. |
| 93 | Instruction *PHIUser = nullptr; |
| 94 | for (auto U : PN->users()) { |
| 95 | if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) { |
| 96 | if (EI.getIndexOperand() == EU->getIndexOperand()) |
| 97 | Extracts.push_back(EU); |
| 98 | else |
| 99 | return nullptr; |
| 100 | } else if (!PHIUser) { |
| 101 | PHIUser = cast<Instruction>(U); |
| 102 | } else { |
| 103 | return nullptr; |
| 104 | } |
| 105 | } |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 106 | |
Michael Kuperstein | a0c6ae0 | 2016-06-06 23:38:33 +0000 | [diff] [blame] | 107 | if (!PHIUser) |
| 108 | return nullptr; |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 109 | |
| 110 | // Verify that this PHI user has one use, which is the PHI itself, |
| 111 | // and that it is a binary operation which is cheap to scalarize. |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 112 | // otherwise return nullptr. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 113 | if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) || |
Sanjay Patel | 431e114 | 2015-11-17 17:24:08 +0000 | [diff] [blame] | 114 | !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 115 | return nullptr; |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 116 | |
| 117 | // Create a scalar PHI node that will replace the vector PHI node |
| 118 | // just before the current PHI node. |
Joey Gouly | b34294d | 2013-05-24 12:33:28 +0000 | [diff] [blame] | 119 | PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith( |
| 120 | PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN)); |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 121 | // Scalarize each PHI operand. |
Joey Gouly | b34294d | 2013-05-24 12:33:28 +0000 | [diff] [blame] | 122 | for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 123 | Value *PHIInVal = PN->getIncomingValue(i); |
| 124 | BasicBlock *inBB = PN->getIncomingBlock(i); |
| 125 | Value *Elt = EI.getIndexOperand(); |
| 126 | // If the operand is the PHI induction variable: |
| 127 | if (PHIInVal == PHIUser) { |
| 128 | // Scalarize the binary operation. Its first operand is the |
Sanjay Patel | 70af1fd | 2014-07-07 22:13:58 +0000 | [diff] [blame] | 129 | // scalar PHI, and the second operand is extracted from the other |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 130 | // vector operand. |
| 131 | BinaryOperator *B0 = cast<BinaryOperator>(PHIUser); |
Joey Gouly | b34294d | 2013-05-24 12:33:28 +0000 | [diff] [blame] | 132 | unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0; |
Joey Gouly | 8369928 | 2013-05-24 12:29:54 +0000 | [diff] [blame] | 133 | Value *Op = InsertNewInstWith( |
| 134 | ExtractElementInst::Create(B0->getOperand(opId), Elt, |
| 135 | B0->getOperand(opId)->getName() + ".Elt"), |
| 136 | *B0); |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 137 | Value *newPHIUser = InsertNewInstWith( |
Owen Anderson | 7ea02fc | 2016-03-01 19:35:52 +0000 | [diff] [blame] | 138 | BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(), |
| 139 | scalarPHI, Op, B0), *B0); |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 140 | scalarPHI->addIncoming(newPHIUser, inBB); |
| 141 | } else { |
| 142 | // Scalarize PHI input: |
Joey Gouly | b34294d | 2013-05-24 12:33:28 +0000 | [diff] [blame] | 143 | Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, ""); |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 144 | // Insert the new instruction into the predecessor basic block. |
| 145 | Instruction *pos = dyn_cast<Instruction>(PHIInVal); |
| 146 | BasicBlock::iterator InsertPos; |
| 147 | if (pos && !isa<PHINode>(pos)) { |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 148 | InsertPos = ++pos->getIterator(); |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 149 | } else { |
| 150 | InsertPos = inBB->getFirstInsertionPt(); |
| 151 | } |
| 152 | |
| 153 | InsertNewInstWith(newEI, *InsertPos); |
| 154 | |
| 155 | scalarPHI->addIncoming(newEI, inBB); |
| 156 | } |
| 157 | } |
Michael Kuperstein | a0c6ae0 | 2016-06-06 23:38:33 +0000 | [diff] [blame] | 158 | |
| 159 | for (auto E : Extracts) |
| 160 | replaceInstUsesWith(*E, scalarPHI); |
| 161 | |
| 162 | return &EI; |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 163 | } |
| 164 | |
Sanjay Patel | 4674c77 | 2018-09-24 20:41:22 +0000 | [diff] [blame] | 165 | static Instruction *foldBitcastExtElt(ExtractElementInst &Ext, |
Sanjay Patel | 31b0719 | 2018-10-01 14:40:00 +0000 | [diff] [blame] | 166 | InstCombiner::BuilderTy &Builder, |
| 167 | bool IsBigEndian) { |
Sanjay Patel | 4674c77 | 2018-09-24 20:41:22 +0000 | [diff] [blame] | 168 | Value *X; |
| 169 | uint64_t ExtIndexC; |
| 170 | if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) || |
| 171 | !X->getType()->isVectorTy() || |
| 172 | !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC))) |
| 173 | return nullptr; |
| 174 | |
| 175 | // If this extractelement is using a bitcast from a vector of the same number |
| 176 | // of elements, see if we can find the source element from the source vector: |
| 177 | // extelt (bitcast VecX), IndexC --> bitcast X[IndexC] |
| 178 | Type *SrcTy = X->getType(); |
| 179 | Type *DestTy = Ext.getType(); |
| 180 | unsigned NumSrcElts = SrcTy->getVectorNumElements(); |
| 181 | unsigned NumElts = Ext.getVectorOperandType()->getNumElements(); |
| 182 | if (NumSrcElts == NumElts) |
| 183 | if (Value *Elt = findScalarElement(X, ExtIndexC)) |
| 184 | return new BitCastInst(Elt, DestTy); |
| 185 | |
Sanjay Patel | 31b0719 | 2018-10-01 14:40:00 +0000 | [diff] [blame] | 186 | // If the source elements are wider than the destination, try to shift and |
| 187 | // truncate a subset of scalar bits of an insert op. |
Sanjay Patel | 3746e11 | 2018-10-04 16:25:05 +0000 | [diff] [blame] | 188 | if (NumSrcElts < NumElts) { |
Sanjay Patel | 31b0719 | 2018-10-01 14:40:00 +0000 | [diff] [blame] | 189 | Value *Scalar; |
| 190 | uint64_t InsIndexC; |
| 191 | if (!match(X, m_InsertElement(m_Value(), m_Value(Scalar), |
| 192 | m_ConstantInt(InsIndexC)))) |
| 193 | return nullptr; |
| 194 | |
| 195 | // The extract must be from the subset of vector elements that we inserted |
| 196 | // into. Example: if we inserted element 1 of a <2 x i64> and we are |
| 197 | // extracting an i16 (narrowing ratio = 4), then this extract must be from 1 |
| 198 | // of elements 4-7 of the bitcasted vector. |
| 199 | unsigned NarrowingRatio = NumElts / NumSrcElts; |
| 200 | if (ExtIndexC / NarrowingRatio != InsIndexC) |
| 201 | return nullptr; |
| 202 | |
| 203 | // We are extracting part of the original scalar. How that scalar is |
| 204 | // inserted into the vector depends on the endian-ness. Example: |
| 205 | // Vector Byte Elt Index: 0 1 2 3 4 5 6 7 |
| 206 | // +--+--+--+--+--+--+--+--+ |
| 207 | // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3| |
| 208 | // extelt <4 x i16> V', 3: | |S2|S3| |
| 209 | // +--+--+--+--+--+--+--+--+ |
| 210 | // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value. |
| 211 | // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value. |
| 212 | // In this example, we must right-shift little-endian. Big-endian is just a |
| 213 | // truncate. |
| 214 | unsigned Chunk = ExtIndexC % NarrowingRatio; |
| 215 | if (IsBigEndian) |
| 216 | Chunk = NarrowingRatio - 1 - Chunk; |
Sanjay Patel | 3746e11 | 2018-10-04 16:25:05 +0000 | [diff] [blame] | 217 | |
| 218 | // Bail out if this is an FP vector to FP vector sequence. That would take |
| 219 | // more instructions than we started with unless there is no shift, and it |
| 220 | // may not be handled as well in the backend. |
| 221 | bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy(); |
| 222 | bool NeedDestBitcast = DestTy->isFloatingPointTy(); |
| 223 | if (NeedSrcBitcast && NeedDestBitcast) |
| 224 | return nullptr; |
| 225 | |
| 226 | unsigned SrcWidth = SrcTy->getScalarSizeInBits(); |
| 227 | unsigned DestWidth = DestTy->getPrimitiveSizeInBits(); |
| 228 | unsigned ShAmt = Chunk * DestWidth; |
| 229 | |
| 230 | // TODO: This limitation is more strict than necessary. We could sum the |
| 231 | // number of new instructions and subtract the number eliminated to know if |
| 232 | // we can proceed. |
| 233 | if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse()) |
| 234 | if (NeedSrcBitcast || NeedDestBitcast) |
| 235 | return nullptr; |
| 236 | |
| 237 | if (NeedSrcBitcast) { |
| 238 | Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth); |
| 239 | Scalar = Builder.CreateBitCast(Scalar, SrcIntTy); |
| 240 | } |
| 241 | |
Sanjay Patel | 31b0719 | 2018-10-01 14:40:00 +0000 | [diff] [blame] | 242 | if (ShAmt) { |
| 243 | // Bail out if we could end with more instructions than we started with. |
| 244 | if (!Ext.getVectorOperand()->hasOneUse()) |
| 245 | return nullptr; |
| 246 | Scalar = Builder.CreateLShr(Scalar, ShAmt); |
| 247 | } |
Sanjay Patel | 3746e11 | 2018-10-04 16:25:05 +0000 | [diff] [blame] | 248 | |
| 249 | if (NeedDestBitcast) { |
| 250 | Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth); |
| 251 | return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy); |
| 252 | } |
Sanjay Patel | 31b0719 | 2018-10-01 14:40:00 +0000 | [diff] [blame] | 253 | return new TruncInst(Scalar, DestTy); |
| 254 | } |
| 255 | |
Sanjay Patel | 4674c77 | 2018-09-24 20:41:22 +0000 | [diff] [blame] | 256 | return nullptr; |
| 257 | } |
| 258 | |
Piotr Sobczak | a861c9a | 2019-10-21 08:12:47 +0000 | [diff] [blame] | 259 | /// Find elements of V demanded by UserInstr. |
| 260 | static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) { |
| 261 | unsigned VWidth = V->getType()->getVectorNumElements(); |
| 262 | |
| 263 | // Conservatively assume that all elements are needed. |
| 264 | APInt UsedElts(APInt::getAllOnesValue(VWidth)); |
| 265 | |
| 266 | switch (UserInstr->getOpcode()) { |
| 267 | case Instruction::ExtractElement: { |
| 268 | ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr); |
| 269 | assert(EEI->getVectorOperand() == V); |
| 270 | ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand()); |
| 271 | if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) { |
| 272 | UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue()); |
| 273 | } |
| 274 | break; |
| 275 | } |
| 276 | case Instruction::ShuffleVector: { |
| 277 | ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr); |
| 278 | unsigned MaskNumElts = UserInstr->getType()->getVectorNumElements(); |
| 279 | |
| 280 | UsedElts = APInt(VWidth, 0); |
| 281 | for (unsigned i = 0; i < MaskNumElts; i++) { |
| 282 | unsigned MaskVal = Shuffle->getMaskValue(i); |
| 283 | if (MaskVal == -1u || MaskVal >= 2 * VWidth) |
| 284 | continue; |
| 285 | if (Shuffle->getOperand(0) == V && (MaskVal < VWidth)) |
| 286 | UsedElts.setBit(MaskVal); |
| 287 | if (Shuffle->getOperand(1) == V && |
| 288 | ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth))) |
| 289 | UsedElts.setBit(MaskVal - VWidth); |
| 290 | } |
| 291 | break; |
| 292 | } |
| 293 | default: |
| 294 | break; |
| 295 | } |
| 296 | return UsedElts; |
| 297 | } |
| 298 | |
| 299 | /// Find union of elements of V demanded by all its users. |
| 300 | /// If it is known by querying findDemandedEltsBySingleUser that |
| 301 | /// no user demands an element of V, then the corresponding bit |
| 302 | /// remains unset in the returned value. |
| 303 | static APInt findDemandedEltsByAllUsers(Value *V) { |
| 304 | unsigned VWidth = V->getType()->getVectorNumElements(); |
| 305 | |
| 306 | APInt UnionUsedElts(VWidth, 0); |
| 307 | for (const Use &U : V->uses()) { |
| 308 | if (Instruction *I = dyn_cast<Instruction>(U.getUser())) { |
| 309 | UnionUsedElts |= findDemandedEltsBySingleUser(V, I); |
| 310 | } else { |
| 311 | UnionUsedElts = APInt::getAllOnesValue(VWidth); |
| 312 | break; |
| 313 | } |
| 314 | |
| 315 | if (UnionUsedElts.isAllOnesValue()) |
| 316 | break; |
| 317 | } |
| 318 | |
| 319 | return UnionUsedElts; |
| 320 | } |
| 321 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 322 | Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) { |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 323 | Value *SrcVec = EI.getVectorOperand(); |
| 324 | Value *Index = EI.getIndexOperand(); |
| 325 | if (Value *V = SimplifyExtractElementInst(SrcVec, Index, |
Craig Topper | a420562 | 2017-06-09 03:21:29 +0000 | [diff] [blame] | 326 | SQ.getWithInstruction(&EI))) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 327 | return replaceInstUsesWith(EI, V); |
David Majnemer | 599ca44 | 2015-07-13 01:15:53 +0000 | [diff] [blame] | 328 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 329 | // If extracting a specified index from the vector, see if we can recursively |
| 330 | // find a previously computed scalar that was inserted into the vector. |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 331 | auto *IndexC = dyn_cast<ConstantInt>(Index); |
| 332 | if (IndexC) { |
Sanjay Patel | 7a52626 | 2018-09-24 16:39:03 +0000 | [diff] [blame] | 333 | unsigned NumElts = EI.getVectorOperandType()->getNumElements(); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 334 | |
Simon Pilgrim | e7d032f | 2017-12-27 12:00:18 +0000 | [diff] [blame] | 335 | // InstSimplify should handle cases where the index is invalid. |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 336 | if (!IndexC->getValue().ule(NumElts)) |
Simon Pilgrim | e7d032f | 2017-12-27 12:00:18 +0000 | [diff] [blame] | 337 | return nullptr; |
| 338 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 339 | // This instruction only demands the single element from the input vector. |
Piotr Sobczak | a861c9a | 2019-10-21 08:12:47 +0000 | [diff] [blame] | 340 | if (NumElts != 1) { |
| 341 | // If the input vector has a single use, simplify it based on this use |
| 342 | // property. |
| 343 | if (SrcVec->hasOneUse()) { |
| 344 | APInt UndefElts(NumElts, 0); |
| 345 | APInt DemandedElts(NumElts, 0); |
| 346 | DemandedElts.setBit(IndexC->getZExtValue()); |
| 347 | if (Value *V = |
Nikita Popov | 53d2090 | 2020-03-29 20:07:46 +0200 | [diff] [blame^] | 348 | SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts)) |
| 349 | return replaceOperand(EI, 0, V); |
Piotr Sobczak | a861c9a | 2019-10-21 08:12:47 +0000 | [diff] [blame] | 350 | } else { |
| 351 | // If the input vector has multiple uses, simplify it based on a union |
| 352 | // of all elements used. |
| 353 | APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec); |
| 354 | if (!DemandedElts.isAllOnesValue()) { |
| 355 | APInt UndefElts(NumElts, 0); |
| 356 | if (Value *V = SimplifyDemandedVectorElts( |
| 357 | SrcVec, DemandedElts, UndefElts, 0 /* Depth */, |
| 358 | true /* AllowMultipleUsers */)) { |
| 359 | if (V != SrcVec) { |
| 360 | SrcVec->replaceAllUsesWith(V); |
| 361 | return &EI; |
| 362 | } |
| 363 | } |
| 364 | } |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 365 | } |
| 366 | } |
Sanjay Patel | 31b0719 | 2018-10-01 14:40:00 +0000 | [diff] [blame] | 367 | if (Instruction *I = foldBitcastExtElt(EI, Builder, DL.isBigEndian())) |
Sanjay Patel | 4674c77 | 2018-09-24 20:41:22 +0000 | [diff] [blame] | 368 | return I; |
Anat Shemer | 0c95efa | 2013-04-18 19:35:39 +0000 | [diff] [blame] | 369 | |
| 370 | // If there's a vector PHI feeding a scalar use through this extractelement |
| 371 | // instruction, try to scalarize the PHI. |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 372 | if (auto *Phi = dyn_cast<PHINode>(SrcVec)) |
| 373 | if (Instruction *ScalarPHI = scalarizePHI(EI, Phi)) |
| 374 | return ScalarPHI; |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 375 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 376 | |
Simon Moll | d871ef4 | 2020-03-10 16:05:31 +0100 | [diff] [blame] | 377 | // TODO come up with a n-ary matcher that subsumes both unary and |
| 378 | // binary matchers. |
| 379 | UnaryOperator *UO; |
| 380 | if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, IndexC)) { |
| 381 | // extelt (unop X), Index --> unop (extelt X, Index) |
| 382 | Value *X = UO->getOperand(0); |
| 383 | Value *E = Builder.CreateExtractElement(X, Index); |
| 384 | return UnaryOperator::CreateWithCopiedFlags(UO->getOpcode(), E, UO); |
| 385 | } |
| 386 | |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 387 | BinaryOperator *BO; |
| 388 | if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, IndexC)) { |
| 389 | // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index) |
| 390 | Value *X = BO->getOperand(0), *Y = BO->getOperand(1); |
| 391 | Value *E0 = Builder.CreateExtractElement(X, Index); |
| 392 | Value *E1 = Builder.CreateExtractElement(Y, Index); |
| 393 | return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO); |
| 394 | } |
| 395 | |
Matt Arsenault | 9ccde61 | 2018-12-10 21:50:54 +0000 | [diff] [blame] | 396 | Value *X, *Y; |
| 397 | CmpInst::Predicate Pred; |
| 398 | if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) && |
| 399 | cheapToScalarize(SrcVec, IndexC)) { |
| 400 | // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index) |
| 401 | Value *E0 = Builder.CreateExtractElement(X, Index); |
| 402 | Value *E1 = Builder.CreateExtractElement(Y, Index); |
| 403 | return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1); |
| 404 | } |
| 405 | |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 406 | if (auto *I = dyn_cast<Instruction>(SrcVec)) { |
| 407 | if (auto *IE = dyn_cast<InsertElementInst>(I)) { |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 408 | // Extracting the inserted element? |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 409 | if (IE->getOperand(2) == Index) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 410 | return replaceInstUsesWith(EI, IE->getOperand(1)); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 411 | // If the inserted and extracted elements are constants, they must not |
| 412 | // be the same value, extract from the pre-inserted value instead. |
Nikita Popov | 878cb38 | 2020-01-31 22:23:33 +0100 | [diff] [blame] | 413 | if (isa<Constant>(IE->getOperand(2)) && IndexC) |
| 414 | return replaceOperand(EI, 0, IE->getOperand(0)); |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 415 | } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) { |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 416 | // If this is extracting an element from a shufflevector, figure out where |
| 417 | // it came from and extract from the appropriate input element instead. |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 418 | if (auto *Elt = dyn_cast<ConstantInt>(Index)) { |
Eli Friedman | 303c81c | 2011-10-21 19:11:34 +0000 | [diff] [blame] | 419 | int SrcIdx = SVI->getMaskValue(Elt->getZExtValue()); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 420 | Value *Src; |
| 421 | unsigned LHSWidth = |
Chris Lattner | 8326bd8 | 2012-01-26 00:42:34 +0000 | [diff] [blame] | 422 | SVI->getOperand(0)->getType()->getVectorNumElements(); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 423 | |
Bob Wilson | 11ee456 | 2010-10-29 22:03:05 +0000 | [diff] [blame] | 424 | if (SrcIdx < 0) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 425 | return replaceInstUsesWith(EI, UndefValue::get(EI.getType())); |
Bob Wilson | 11ee456 | 2010-10-29 22:03:05 +0000 | [diff] [blame] | 426 | if (SrcIdx < (int)LHSWidth) |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 427 | Src = SVI->getOperand(0); |
Bob Wilson | 11ee456 | 2010-10-29 22:03:05 +0000 | [diff] [blame] | 428 | else { |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 429 | SrcIdx -= LHSWidth; |
| 430 | Src = SVI->getOperand(1); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 431 | } |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 432 | Type *Int32Ty = Type::getInt32Ty(EI.getContext()); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 433 | return ExtractElementInst::Create(Src, |
Bob Wilson | 9d07f39 | 2010-10-29 22:03:07 +0000 | [diff] [blame] | 434 | ConstantInt::get(Int32Ty, |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 435 | SrcIdx, false)); |
| 436 | } |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 437 | } else if (auto *CI = dyn_cast<CastInst>(I)) { |
Sanjay Patel | b67076c | 2015-11-29 22:09:34 +0000 | [diff] [blame] | 438 | // Canonicalize extractelement(cast) -> cast(extractelement). |
| 439 | // Bitcasts can change the number of vector elements, and they cost |
| 440 | // nothing. |
Anat Shemer | 5570318 | 2013-04-18 19:56:44 +0000 | [diff] [blame] | 441 | if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) { |
Sanjay Patel | 47b3b4b | 2018-12-05 21:57:51 +0000 | [diff] [blame] | 442 | Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index); |
Nadav Rotem | d74b72b | 2011-03-31 22:57:29 +0000 | [diff] [blame] | 443 | return CastInst::Create(CI->getOpcode(), EE, EI.getType()); |
| 444 | } |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 445 | } |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 446 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 447 | return nullptr; |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 448 | } |
| 449 | |
Sanjay Patel | 6eccf48 | 2015-09-09 15:24:36 +0000 | [diff] [blame] | 450 | /// If V is a shuffle of values that ONLY returns elements from either LHS or |
| 451 | /// RHS, return the shuffle mask and true. Otherwise, return false. |
Sanjay Patel | 431e114 | 2015-11-17 17:24:08 +0000 | [diff] [blame] | 452 | static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, |
Chris Lattner | 0256be9 | 2012-01-27 03:08:05 +0000 | [diff] [blame] | 453 | SmallVectorImpl<Constant*> &Mask) { |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 454 | assert(LHS->getType() == RHS->getType() && |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 455 | "Invalid CollectSingleShuffleElements"); |
Matt Arsenault | 8227b9f | 2013-09-06 00:37:24 +0000 | [diff] [blame] | 456 | unsigned NumElts = V->getType()->getVectorNumElements(); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 457 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 458 | if (isa<UndefValue>(V)) { |
| 459 | Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); |
| 460 | return true; |
| 461 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 462 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 463 | if (V == LHS) { |
| 464 | for (unsigned i = 0; i != NumElts; ++i) |
| 465 | Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); |
| 466 | return true; |
| 467 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 468 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 469 | if (V == RHS) { |
| 470 | for (unsigned i = 0; i != NumElts; ++i) |
| 471 | Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), |
| 472 | i+NumElts)); |
| 473 | return true; |
| 474 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 475 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 476 | if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { |
| 477 | // If this is an insert of an extract from some other vector, include it. |
| 478 | Value *VecOp = IEI->getOperand(0); |
| 479 | Value *ScalarOp = IEI->getOperand(1); |
| 480 | Value *IdxOp = IEI->getOperand(2); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 481 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 482 | if (!isa<ConstantInt>(IdxOp)) |
| 483 | return false; |
| 484 | unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 485 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 486 | if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. |
Sanjay Patel | 70af1fd | 2014-07-07 22:13:58 +0000 | [diff] [blame] | 487 | // We can handle this if the vector we are inserting into is |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 488 | // transitively ok. |
Sanjay Patel | 431e114 | 2015-11-17 17:24:08 +0000 | [diff] [blame] | 489 | if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 490 | // If so, update the mask to reflect the inserted undef. |
| 491 | Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext())); |
| 492 | return true; |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 493 | } |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 494 | } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 495 | if (isa<ConstantInt>(EI->getOperand(1))) { |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 496 | unsigned ExtractedIdx = |
| 497 | cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 498 | unsigned NumLHSElts = LHS->getType()->getVectorNumElements(); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 499 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 500 | // This must be extracting from either LHS or RHS. |
| 501 | if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { |
Sanjay Patel | 70af1fd | 2014-07-07 22:13:58 +0000 | [diff] [blame] | 502 | // We can handle this if the vector we are inserting into is |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 503 | // transitively ok. |
Sanjay Patel | 431e114 | 2015-11-17 17:24:08 +0000 | [diff] [blame] | 504 | if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 505 | // If so, update the mask to reflect the inserted value. |
| 506 | if (EI->getOperand(0) == LHS) { |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 507 | Mask[InsertedIdx % NumElts] = |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 508 | ConstantInt::get(Type::getInt32Ty(V->getContext()), |
| 509 | ExtractedIdx); |
| 510 | } else { |
| 511 | assert(EI->getOperand(0) == RHS); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 512 | Mask[InsertedIdx % NumElts] = |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 513 | ConstantInt::get(Type::getInt32Ty(V->getContext()), |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 514 | ExtractedIdx + NumLHSElts); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 515 | } |
| 516 | return true; |
| 517 | } |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 522 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 523 | return false; |
| 524 | } |
| 525 | |
Sanjay Patel | ae945e7 | 2015-12-24 21:17:56 +0000 | [diff] [blame] | 526 | /// If we have insertion into a vector that is wider than the vector that we |
| 527 | /// are extracting from, try to widen the source vector to allow a single |
| 528 | /// shufflevector to replace one or more insert/extract pairs. |
| 529 | static void replaceExtractElements(InsertElementInst *InsElt, |
| 530 | ExtractElementInst *ExtElt, |
| 531 | InstCombiner &IC) { |
| 532 | VectorType *InsVecType = InsElt->getType(); |
| 533 | VectorType *ExtVecType = ExtElt->getVectorOperandType(); |
| 534 | unsigned NumInsElts = InsVecType->getVectorNumElements(); |
| 535 | unsigned NumExtElts = ExtVecType->getVectorNumElements(); |
| 536 | |
| 537 | // The inserted-to vector must be wider than the extracted-from vector. |
| 538 | if (InsVecType->getElementType() != ExtVecType->getElementType() || |
| 539 | NumExtElts >= NumInsElts) |
| 540 | return; |
| 541 | |
| 542 | // Create a shuffle mask to widen the extended-from vector using undefined |
| 543 | // values. The mask selects all of the values of the original vector followed |
| 544 | // by as many undefined values as needed to create a vector of the same length |
| 545 | // as the inserted-to vector. |
| 546 | SmallVector<Constant *, 16> ExtendMask; |
| 547 | IntegerType *IntType = Type::getInt32Ty(InsElt->getContext()); |
| 548 | for (unsigned i = 0; i < NumExtElts; ++i) |
| 549 | ExtendMask.push_back(ConstantInt::get(IntType, i)); |
| 550 | for (unsigned i = NumExtElts; i < NumInsElts; ++i) |
| 551 | ExtendMask.push_back(UndefValue::get(IntType)); |
| 552 | |
| 553 | Value *ExtVecOp = ExtElt->getVectorOperand(); |
Sanjay Patel | 66fff73 | 2016-01-29 20:21:02 +0000 | [diff] [blame] | 554 | auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp); |
| 555 | BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) |
| 556 | ? ExtVecOpInst->getParent() |
| 557 | : ExtElt->getParent(); |
| 558 | |
| 559 | // TODO: This restriction matches the basic block check below when creating |
| 560 | // new extractelement instructions. If that limitation is removed, this one |
| 561 | // could also be removed. But for now, we just bail out to ensure that we |
| 562 | // will replace the extractelement instruction that is feeding our |
| 563 | // insertelement instruction. This allows the insertelement to then be |
| 564 | // replaced by a shufflevector. If the insertelement is not replaced, we can |
| 565 | // induce infinite looping because there's an optimization for extractelement |
| 566 | // that will delete our widening shuffle. This would trigger another attempt |
| 567 | // here to create that shuffle, and we spin forever. |
| 568 | if (InsertionBlock != InsElt->getParent()) |
| 569 | return; |
| 570 | |
Sanjay Patel | 4e1b5a5 | 2016-11-10 00:15:14 +0000 | [diff] [blame] | 571 | // TODO: This restriction matches the check in visitInsertElementInst() and |
| 572 | // prevents an infinite loop caused by not turning the extract/insert pair |
| 573 | // into a shuffle. We really should not need either check, but we're lacking |
| 574 | // folds for shufflevectors because we're afraid to generate shuffle masks |
| 575 | // that the backend can't handle. |
| 576 | if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back())) |
| 577 | return; |
| 578 | |
Sanjay Patel | ae945e7 | 2015-12-24 21:17:56 +0000 | [diff] [blame] | 579 | auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType), |
| 580 | ConstantVector::get(ExtendMask)); |
| 581 | |
Sanjay Patel | a1c5347 | 2016-01-05 19:09:47 +0000 | [diff] [blame] | 582 | // Insert the new shuffle after the vector operand of the extract is defined |
Sanjay Patel | d72a458 | 2016-01-08 01:39:16 +0000 | [diff] [blame] | 583 | // (as long as it's not a PHI) or at the start of the basic block of the |
| 584 | // extract, so any subsequent extracts in the same basic block can use it. |
| 585 | // TODO: Insert before the earliest ExtractElementInst that is replaced. |
Sanjay Patel | d72a458 | 2016-01-08 01:39:16 +0000 | [diff] [blame] | 586 | if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) |
Sanjay Patel | a1c5347 | 2016-01-05 19:09:47 +0000 | [diff] [blame] | 587 | WideVec->insertAfter(ExtVecOpInst); |
Sanjay Patel | d72a458 | 2016-01-08 01:39:16 +0000 | [diff] [blame] | 588 | else |
Sanjay Patel | a1c5347 | 2016-01-05 19:09:47 +0000 | [diff] [blame] | 589 | IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt()); |
Sanjay Patel | a1c5347 | 2016-01-05 19:09:47 +0000 | [diff] [blame] | 590 | |
| 591 | // Replace extracts from the original narrow vector with extracts from the new |
| 592 | // wide vector. |
Sanjay Patel | ae945e7 | 2015-12-24 21:17:56 +0000 | [diff] [blame] | 593 | for (User *U : ExtVecOp->users()) { |
Sanjay Patel | a1c5347 | 2016-01-05 19:09:47 +0000 | [diff] [blame] | 594 | ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U); |
Sanjay Patel | d72a458 | 2016-01-08 01:39:16 +0000 | [diff] [blame] | 595 | if (!OldExt || OldExt->getParent() != WideVec->getParent()) |
Sanjay Patel | a1c5347 | 2016-01-05 19:09:47 +0000 | [diff] [blame] | 596 | continue; |
| 597 | auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1)); |
Sven van Haastregt | 78819e0 | 2017-06-05 09:18:10 +0000 | [diff] [blame] | 598 | NewExt->insertAfter(OldExt); |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 599 | IC.replaceInstUsesWith(*OldExt, NewExt); |
Sanjay Patel | ae945e7 | 2015-12-24 21:17:56 +0000 | [diff] [blame] | 600 | } |
| 601 | } |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 602 | |
| 603 | /// We are building a shuffle to create V, which is a sequence of insertelement, |
| 604 | /// extractelement pairs. If PermittedRHS is set, then we must either use it or |
Sanjay Patel | 70af1fd | 2014-07-07 22:13:58 +0000 | [diff] [blame] | 605 | /// not rely on the second vector source. Return a std::pair containing the |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 606 | /// left and right vectors of the proposed shuffle (or 0), and set the Mask |
| 607 | /// parameter as required. |
| 608 | /// |
| 609 | /// Note: we intentionally don't try to fold earlier shuffles since they have |
| 610 | /// often been chosen carefully to be efficiently implementable on the target. |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 611 | using ShuffleOps = std::pair<Value *, Value *>; |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 612 | |
Sanjay Patel | 431e114 | 2015-11-17 17:24:08 +0000 | [diff] [blame] | 613 | static ShuffleOps collectShuffleElements(Value *V, |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 614 | SmallVectorImpl<Constant *> &Mask, |
Sanjay Patel | ae945e7 | 2015-12-24 21:17:56 +0000 | [diff] [blame] | 615 | Value *PermittedRHS, |
| 616 | InstCombiner &IC) { |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 617 | assert(V->getType()->isVectorTy() && "Invalid shuffle!"); |
Craig Topper | 17b5568 | 2016-12-29 07:03:18 +0000 | [diff] [blame] | 618 | unsigned NumElts = V->getType()->getVectorNumElements(); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 619 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 620 | if (isa<UndefValue>(V)) { |
| 621 | Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 622 | return std::make_pair( |
| 623 | PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr); |
Chris Lattner | a0d01ff | 2012-01-24 14:31:22 +0000 | [diff] [blame] | 624 | } |
Craig Topper | 2ea22b0 | 2013-01-18 05:09:16 +0000 | [diff] [blame] | 625 | |
Chris Lattner | a0d01ff | 2012-01-24 14:31:22 +0000 | [diff] [blame] | 626 | if (isa<ConstantAggregateZero>(V)) { |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 627 | Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0)); |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 628 | return std::make_pair(V, nullptr); |
Chris Lattner | a0d01ff | 2012-01-24 14:31:22 +0000 | [diff] [blame] | 629 | } |
Craig Topper | 2ea22b0 | 2013-01-18 05:09:16 +0000 | [diff] [blame] | 630 | |
Chris Lattner | a0d01ff | 2012-01-24 14:31:22 +0000 | [diff] [blame] | 631 | if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 632 | // If this is an insert of an extract from some other vector, include it. |
| 633 | Value *VecOp = IEI->getOperand(0); |
| 634 | Value *ScalarOp = IEI->getOperand(1); |
| 635 | Value *IdxOp = IEI->getOperand(2); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 636 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 637 | if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 638 | if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 639 | unsigned ExtractedIdx = |
Bob Wilson | 67a6f32 | 2010-10-29 22:20:45 +0000 | [diff] [blame] | 640 | cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 641 | unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 642 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 643 | // Either the extracted from or inserted into vector must be RHSVec, |
| 644 | // otherwise we'd end up with a shuffle of three inputs. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 645 | if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) { |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 646 | Value *RHS = EI->getOperand(0); |
Sanjay Patel | ae945e7 | 2015-12-24 21:17:56 +0000 | [diff] [blame] | 647 | ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC); |
Craig Topper | e73658d | 2014-04-28 04:05:08 +0000 | [diff] [blame] | 648 | assert(LR.second == nullptr || LR.second == RHS); |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 649 | |
| 650 | if (LR.first->getType() != RHS->getType()) { |
Sanjay Patel | ae945e7 | 2015-12-24 21:17:56 +0000 | [diff] [blame] | 651 | // Although we are giving up for now, see if we can create extracts |
| 652 | // that match the inserts for another round of combining. |
| 653 | replaceExtractElements(IEI, EI, IC); |
| 654 | |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 655 | // We tried our best, but we can't find anything compatible with RHS |
| 656 | // further up the chain. Return a trivial shuffle. |
| 657 | for (unsigned i = 0; i < NumElts; ++i) |
| 658 | Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i); |
| 659 | return std::make_pair(V, nullptr); |
| 660 | } |
| 661 | |
| 662 | unsigned NumLHSElts = RHS->getType()->getVectorNumElements(); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 663 | Mask[InsertedIdx % NumElts] = |
Bob Wilson | 67a6f32 | 2010-10-29 22:20:45 +0000 | [diff] [blame] | 664 | ConstantInt::get(Type::getInt32Ty(V->getContext()), |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 665 | NumLHSElts+ExtractedIdx); |
| 666 | return std::make_pair(LR.first, RHS); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 667 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 668 | |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 669 | if (VecOp == PermittedRHS) { |
| 670 | // We've gone as far as we can: anything on the other side of the |
| 671 | // extractelement will already have been converted into a shuffle. |
| 672 | unsigned NumLHSElts = |
| 673 | EI->getOperand(0)->getType()->getVectorNumElements(); |
| 674 | for (unsigned i = 0; i != NumElts; ++i) |
| 675 | Mask.push_back(ConstantInt::get( |
| 676 | Type::getInt32Ty(V->getContext()), |
| 677 | i == InsertedIdx ? ExtractedIdx : NumLHSElts + i)); |
| 678 | return std::make_pair(EI->getOperand(0), PermittedRHS); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 679 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 680 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 681 | // If this insertelement is a chain that comes from exactly these two |
| 682 | // vectors, return the vector and the effective shuffle. |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 683 | if (EI->getOperand(0)->getType() == PermittedRHS->getType() && |
Sanjay Patel | 431e114 | 2015-11-17 17:24:08 +0000 | [diff] [blame] | 684 | collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS, |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 685 | Mask)) |
| 686 | return std::make_pair(EI->getOperand(0), PermittedRHS); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 687 | } |
| 688 | } |
| 689 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 690 | |
Sanjay Patel | b67076c | 2015-11-29 22:09:34 +0000 | [diff] [blame] | 691 | // Otherwise, we can't do anything fancy. Return an identity vector. |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 692 | for (unsigned i = 0; i != NumElts; ++i) |
| 693 | Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); |
Tim Northover | fad2761 | 2014-03-07 10:24:44 +0000 | [diff] [blame] | 694 | return std::make_pair(V, nullptr); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 695 | } |
| 696 | |
Michael Zolotukhin | 7d6293a | 2014-05-07 14:30:18 +0000 | [diff] [blame] | 697 | /// Try to find redundant insertvalue instructions, like the following ones: |
| 698 | /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0 |
| 699 | /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0 |
| 700 | /// Here the second instruction inserts values at the same indices, as the |
| 701 | /// first one, making the first one redundant. |
| 702 | /// It should be transformed to: |
| 703 | /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0 |
| 704 | Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) { |
| 705 | bool IsRedundant = false; |
| 706 | ArrayRef<unsigned int> FirstIndices = I.getIndices(); |
| 707 | |
| 708 | // If there is a chain of insertvalue instructions (each of them except the |
| 709 | // last one has only one use and it's another insertvalue insn from this |
| 710 | // chain), check if any of the 'children' uses the same indices as the first |
| 711 | // instruction. In this case, the first one is redundant. |
| 712 | Value *V = &I; |
Michael Zolotukhin | 292d3ca | 2014-05-08 19:50:24 +0000 | [diff] [blame] | 713 | unsigned Depth = 0; |
Michael Zolotukhin | 7d6293a | 2014-05-07 14:30:18 +0000 | [diff] [blame] | 714 | while (V->hasOneUse() && Depth < 10) { |
| 715 | User *U = V->user_back(); |
Michael Zolotukhin | 292d3ca | 2014-05-08 19:50:24 +0000 | [diff] [blame] | 716 | auto UserInsInst = dyn_cast<InsertValueInst>(U); |
| 717 | if (!UserInsInst || U->getOperand(0) != V) |
Michael Zolotukhin | 7d6293a | 2014-05-07 14:30:18 +0000 | [diff] [blame] | 718 | break; |
Michael Zolotukhin | 7d6293a | 2014-05-07 14:30:18 +0000 | [diff] [blame] | 719 | if (UserInsInst->getIndices() == FirstIndices) { |
| 720 | IsRedundant = true; |
| 721 | break; |
| 722 | } |
| 723 | V = UserInsInst; |
| 724 | Depth++; |
| 725 | } |
| 726 | |
| 727 | if (IsRedundant) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 728 | return replaceInstUsesWith(I, I.getOperand(0)); |
Michael Zolotukhin | 7d6293a | 2014-05-07 14:30:18 +0000 | [diff] [blame] | 729 | return nullptr; |
| 730 | } |
| 731 | |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 732 | static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) { |
| 733 | int MaskSize = Shuf.getMask()->getType()->getVectorNumElements(); |
| 734 | int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements(); |
| 735 | |
| 736 | // A vector select does not change the size of the operands. |
| 737 | if (MaskSize != VecSize) |
| 738 | return false; |
| 739 | |
| 740 | // Each mask element must be undefined or choose a vector element from one of |
| 741 | // the source operands without crossing vector lanes. |
| 742 | for (int i = 0; i != MaskSize; ++i) { |
| 743 | int Elt = Shuf.getMaskValue(i); |
| 744 | if (Elt != -1 && Elt != i && Elt != i + VecSize) |
| 745 | return false; |
| 746 | } |
| 747 | |
| 748 | return true; |
| 749 | } |
| 750 | |
Sanjay Patel | 71ad227 | 2019-06-26 15:52:59 +0000 | [diff] [blame] | 751 | /// Turn a chain of inserts that splats a value into an insert + shuffle: |
| 752 | /// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... -> |
| 753 | /// shufflevector(insertelt(X, %k, 0), undef, zero) |
| 754 | static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) { |
| 755 | // We are interested in the last insert in a chain. So if this insert has a |
| 756 | // single user and that user is an insert, bail. |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 757 | if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back())) |
| 758 | return nullptr; |
| 759 | |
Sanjay Patel | 71ad227 | 2019-06-26 15:52:59 +0000 | [diff] [blame] | 760 | auto *VecTy = cast<VectorType>(InsElt.getType()); |
| 761 | unsigned NumElements = VecTy->getNumElements(); |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 762 | |
| 763 | // Do not try to do this for a one-element vector, since that's a nop, |
| 764 | // and will cause an inf-loop. |
| 765 | if (NumElements == 1) |
| 766 | return nullptr; |
| 767 | |
| 768 | Value *SplatVal = InsElt.getOperand(1); |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 769 | InsertElementInst *CurrIE = &InsElt; |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 770 | SmallVector<bool, 16> ElementPresent(NumElements, false); |
Florian Hahn | b992fee | 2017-08-30 10:54:21 +0000 | [diff] [blame] | 771 | InsertElementInst *FirstIE = nullptr; |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 772 | |
| 773 | // Walk the chain backwards, keeping track of which indices we inserted into, |
| 774 | // until we hit something that isn't an insert of the splatted value. |
| 775 | while (CurrIE) { |
Sanjay Patel | 863d494 | 2017-11-27 18:19:32 +0000 | [diff] [blame] | 776 | auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2)); |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 777 | if (!Idx || CurrIE->getOperand(1) != SplatVal) |
| 778 | return nullptr; |
| 779 | |
Sanjay Patel | 863d494 | 2017-11-27 18:19:32 +0000 | [diff] [blame] | 780 | auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0)); |
Florian Hahn | b992fee | 2017-08-30 10:54:21 +0000 | [diff] [blame] | 781 | // Check none of the intermediate steps have any additional uses, except |
| 782 | // for the root insertelement instruction, which can be re-used, if it |
| 783 | // inserts at position 0. |
| 784 | if (CurrIE != &InsElt && |
| 785 | (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero()))) |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 786 | return nullptr; |
| 787 | |
| 788 | ElementPresent[Idx->getZExtValue()] = true; |
Florian Hahn | b992fee | 2017-08-30 10:54:21 +0000 | [diff] [blame] | 789 | FirstIE = CurrIE; |
| 790 | CurrIE = NextIE; |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 791 | } |
| 792 | |
Sanjay Patel | 75b5edf | 2019-07-04 16:45:34 +0000 | [diff] [blame] | 793 | // If this is just a single insertelement (not a sequence), we are done. |
| 794 | if (FirstIE == &InsElt) |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 795 | return nullptr; |
| 796 | |
Sanjay Patel | 75b5edf | 2019-07-04 16:45:34 +0000 | [diff] [blame] | 797 | // If we are not inserting into an undef vector, make sure we've seen an |
| 798 | // insert into every element. |
| 799 | // TODO: If the base vector is not undef, it might be better to create a splat |
| 800 | // and then a select-shuffle (blend) with the base vector. |
| 801 | if (!isa<UndefValue>(FirstIE->getOperand(0))) |
| 802 | if (any_of(ElementPresent, [](bool Present) { return !Present; })) |
| 803 | return nullptr; |
| 804 | |
Sanjay Patel | 71ad227 | 2019-06-26 15:52:59 +0000 | [diff] [blame] | 805 | // Create the insert + shuffle. |
| 806 | Type *Int32Ty = Type::getInt32Ty(InsElt.getContext()); |
| 807 | UndefValue *UndefVec = UndefValue::get(VecTy); |
| 808 | Constant *Zero = ConstantInt::get(Int32Ty, 0); |
| 809 | if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero()) |
| 810 | FirstIE = InsertElementInst::Create(UndefVec, SplatVal, Zero, "", &InsElt); |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 811 | |
Sanjay Patel | 75b5edf | 2019-07-04 16:45:34 +0000 | [diff] [blame] | 812 | // Splat from element 0, but replace absent elements with undef in the mask. |
| 813 | SmallVector<Constant *, 16> Mask(NumElements, Zero); |
| 814 | for (unsigned i = 0; i != NumElements; ++i) |
| 815 | if (!ElementPresent[i]) |
| 816 | Mask[i] = UndefValue::get(Int32Ty); |
| 817 | |
| 818 | return new ShuffleVectorInst(FirstIE, UndefVec, ConstantVector::get(Mask)); |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 819 | } |
| 820 | |
Sanjay Patel | 3dee113 | 2019-07-08 19:48:52 +0000 | [diff] [blame] | 821 | /// Try to fold an insert element into an existing splat shuffle by changing |
| 822 | /// the shuffle's mask to include the index of this insert element. |
| 823 | static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) { |
| 824 | // Check if the vector operand of this insert is a canonical splat shuffle. |
| 825 | auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0)); |
| 826 | if (!Shuf || !Shuf->isZeroEltSplat()) |
| 827 | return nullptr; |
| 828 | |
| 829 | // Check for a constant insertion index. |
| 830 | uint64_t IdxC; |
| 831 | if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC))) |
| 832 | return nullptr; |
| 833 | |
| 834 | // Check if the splat shuffle's input is the same as this insert's scalar op. |
| 835 | Value *X = InsElt.getOperand(1); |
| 836 | Value *Op0 = Shuf->getOperand(0); |
| 837 | if (!match(Op0, m_InsertElement(m_Undef(), m_Specific(X), m_ZeroInt()))) |
| 838 | return nullptr; |
| 839 | |
| 840 | // Replace the shuffle mask element at the index of this insert with a zero. |
| 841 | // For example: |
| 842 | // inselt (shuf (inselt undef, X, 0), undef, <0,undef,0,undef>), X, 1 |
| 843 | // --> shuf (inselt undef, X, 0), undef, <0,0,0,undef> |
| 844 | unsigned NumMaskElts = Shuf->getType()->getVectorNumElements(); |
| 845 | SmallVector<Constant *, 16> NewMaskVec(NumMaskElts); |
| 846 | Type *I32Ty = IntegerType::getInt32Ty(Shuf->getContext()); |
| 847 | Constant *Zero = ConstantInt::getNullValue(I32Ty); |
| 848 | for (unsigned i = 0; i != NumMaskElts; ++i) |
| 849 | NewMaskVec[i] = i == IdxC ? Zero : Shuf->getMask()->getAggregateElement(i); |
| 850 | |
| 851 | Constant *NewMask = ConstantVector::get(NewMaskVec); |
| 852 | return new ShuffleVectorInst(Op0, UndefValue::get(Op0->getType()), NewMask); |
| 853 | } |
| 854 | |
Sanjay Patel | aff5bee | 2019-09-08 19:03:01 +0000 | [diff] [blame] | 855 | /// Try to fold an extract+insert element into an existing identity shuffle by |
| 856 | /// changing the shuffle's mask to include the index of this insert element. |
| 857 | static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) { |
| 858 | // Check if the vector operand of this insert is an identity shuffle. |
| 859 | auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0)); |
| 860 | if (!Shuf || !isa<UndefValue>(Shuf->getOperand(1)) || |
| 861 | !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding())) |
| 862 | return nullptr; |
| 863 | |
| 864 | // Check for a constant insertion index. |
| 865 | uint64_t IdxC; |
| 866 | if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC))) |
| 867 | return nullptr; |
| 868 | |
| 869 | // Check if this insert's scalar op is extracted from the identity shuffle's |
| 870 | // input vector. |
| 871 | Value *Scalar = InsElt.getOperand(1); |
| 872 | Value *X = Shuf->getOperand(0); |
| 873 | if (!match(Scalar, m_ExtractElement(m_Specific(X), m_SpecificInt(IdxC)))) |
| 874 | return nullptr; |
| 875 | |
| 876 | // Replace the shuffle mask element at the index of this extract+insert with |
| 877 | // that same index value. |
| 878 | // For example: |
| 879 | // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask' |
| 880 | unsigned NumMaskElts = Shuf->getType()->getVectorNumElements(); |
| 881 | SmallVector<Constant *, 16> NewMaskVec(NumMaskElts); |
| 882 | Type *I32Ty = IntegerType::getInt32Ty(Shuf->getContext()); |
| 883 | Constant *NewMaskEltC = ConstantInt::get(I32Ty, IdxC); |
| 884 | Constant *OldMask = Shuf->getMask(); |
| 885 | for (unsigned i = 0; i != NumMaskElts; ++i) { |
| 886 | if (i != IdxC) { |
| 887 | // All mask elements besides the inserted element remain the same. |
| 888 | NewMaskVec[i] = OldMask->getAggregateElement(i); |
| 889 | } else if (OldMask->getAggregateElement(i) == NewMaskEltC) { |
| 890 | // If the mask element was already set, there's nothing to do |
| 891 | // (demanded elements analysis may unset it later). |
| 892 | return nullptr; |
| 893 | } else { |
| 894 | assert(isa<UndefValue>(OldMask->getAggregateElement(i)) && |
| 895 | "Unexpected shuffle mask element for identity shuffle"); |
| 896 | NewMaskVec[i] = NewMaskEltC; |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | Constant *NewMask = ConstantVector::get(NewMaskVec); |
| 901 | return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask); |
| 902 | } |
| 903 | |
Sanjay Patel | 2f602ce | 2017-03-22 17:10:44 +0000 | [diff] [blame] | 904 | /// If we have an insertelement instruction feeding into another insertelement |
| 905 | /// and the 2nd is inserting a constant into the vector, canonicalize that |
| 906 | /// constant insertion before the insertion of a variable: |
| 907 | /// |
| 908 | /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 --> |
| 909 | /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1 |
| 910 | /// |
| 911 | /// This has the potential of eliminating the 2nd insertelement instruction |
| 912 | /// via constant folding of the scalar constant into a vector constant. |
| 913 | static Instruction *hoistInsEltConst(InsertElementInst &InsElt2, |
| 914 | InstCombiner::BuilderTy &Builder) { |
| 915 | auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0)); |
| 916 | if (!InsElt1 || !InsElt1->hasOneUse()) |
| 917 | return nullptr; |
| 918 | |
| 919 | Value *X, *Y; |
| 920 | Constant *ScalarC; |
| 921 | ConstantInt *IdxC1, *IdxC2; |
| 922 | if (match(InsElt1->getOperand(0), m_Value(X)) && |
| 923 | match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) && |
| 924 | match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) && |
| 925 | match(InsElt2.getOperand(1), m_Constant(ScalarC)) && |
| 926 | match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) { |
| 927 | Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2); |
| 928 | return InsertElementInst::Create(NewInsElt1, Y, IdxC1); |
| 929 | } |
| 930 | |
| 931 | return nullptr; |
| 932 | } |
| 933 | |
Alexey Bataev | fee9078 | 2016-09-23 09:14:08 +0000 | [diff] [blame] | 934 | /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex |
| 935 | /// --> shufflevector X, CVec', Mask' |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 936 | static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) { |
Alexey Bataev | fee9078 | 2016-09-23 09:14:08 +0000 | [diff] [blame] | 937 | auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0)); |
| 938 | // Bail out if the parent has more than one use. In that case, we'd be |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 939 | // replacing the insertelt with a shuffle, and that's not a clear win. |
Alexey Bataev | fee9078 | 2016-09-23 09:14:08 +0000 | [diff] [blame] | 940 | if (!Inst || !Inst->hasOneUse()) |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 941 | return nullptr; |
Alexey Bataev | fee9078 | 2016-09-23 09:14:08 +0000 | [diff] [blame] | 942 | if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) { |
| 943 | // The shuffle must have a constant vector operand. The insertelt must have |
| 944 | // a constant scalar being inserted at a constant position in the vector. |
| 945 | Constant *ShufConstVec, *InsEltScalar; |
| 946 | uint64_t InsEltIndex; |
| 947 | if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) || |
| 948 | !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) || |
| 949 | !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex))) |
| 950 | return nullptr; |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 951 | |
Alexey Bataev | fee9078 | 2016-09-23 09:14:08 +0000 | [diff] [blame] | 952 | // Adding an element to an arbitrary shuffle could be expensive, but a |
| 953 | // shuffle that selects elements from vectors without crossing lanes is |
| 954 | // assumed cheap. |
| 955 | // If we're just adding a constant into that shuffle, it will still be |
| 956 | // cheap. |
| 957 | if (!isShuffleEquivalentToSelect(*Shuf)) |
| 958 | return nullptr; |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 959 | |
Alexey Bataev | fee9078 | 2016-09-23 09:14:08 +0000 | [diff] [blame] | 960 | // From the above 'select' check, we know that the mask has the same number |
| 961 | // of elements as the vector input operands. We also know that each constant |
| 962 | // input element is used in its lane and can not be used more than once by |
| 963 | // the shuffle. Therefore, replace the constant in the shuffle's constant |
| 964 | // vector with the insertelt constant. Replace the constant in the shuffle's |
| 965 | // mask vector with the insertelt index plus the length of the vector |
| 966 | // (because the constant vector operand of a shuffle is always the 2nd |
| 967 | // operand). |
| 968 | Constant *Mask = Shuf->getMask(); |
| 969 | unsigned NumElts = Mask->getType()->getVectorNumElements(); |
| 970 | SmallVector<Constant *, 16> NewShufElts(NumElts); |
| 971 | SmallVector<Constant *, 16> NewMaskElts(NumElts); |
| 972 | for (unsigned I = 0; I != NumElts; ++I) { |
| 973 | if (I == InsEltIndex) { |
| 974 | NewShufElts[I] = InsEltScalar; |
| 975 | Type *Int32Ty = Type::getInt32Ty(Shuf->getContext()); |
| 976 | NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts); |
| 977 | } else { |
| 978 | // Copy over the existing values. |
| 979 | NewShufElts[I] = ShufConstVec->getAggregateElement(I); |
| 980 | NewMaskElts[I] = Mask->getAggregateElement(I); |
| 981 | } |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 982 | } |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 983 | |
Alexey Bataev | fee9078 | 2016-09-23 09:14:08 +0000 | [diff] [blame] | 984 | // Create new operands for a shuffle that includes the constant of the |
| 985 | // original insertelt. The old shuffle will be dead now. |
| 986 | return new ShuffleVectorInst(Shuf->getOperand(0), |
| 987 | ConstantVector::get(NewShufElts), |
| 988 | ConstantVector::get(NewMaskElts)); |
| 989 | } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) { |
| 990 | // Transform sequences of insertelements ops with constant data/indexes into |
| 991 | // a single shuffle op. |
| 992 | unsigned NumElts = InsElt.getType()->getNumElements(); |
| 993 | |
| 994 | uint64_t InsertIdx[2]; |
| 995 | Constant *Val[2]; |
| 996 | if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) || |
| 997 | !match(InsElt.getOperand(1), m_Constant(Val[0])) || |
| 998 | !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) || |
| 999 | !match(IEI->getOperand(1), m_Constant(Val[1]))) |
| 1000 | return nullptr; |
| 1001 | SmallVector<Constant *, 16> Values(NumElts); |
| 1002 | SmallVector<Constant *, 16> Mask(NumElts); |
| 1003 | auto ValI = std::begin(Val); |
| 1004 | // Generate new constant vector and mask. |
| 1005 | // We have 2 values/masks from the insertelements instructions. Insert them |
| 1006 | // into new value/mask vectors. |
| 1007 | for (uint64_t I : InsertIdx) { |
| 1008 | if (!Values[I]) { |
| 1009 | assert(!Mask[I]); |
| 1010 | Values[I] = *ValI; |
| 1011 | Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), |
| 1012 | NumElts + I); |
| 1013 | } |
| 1014 | ++ValI; |
| 1015 | } |
| 1016 | // Remaining values are filled with 'undef' values. |
| 1017 | for (unsigned I = 0; I < NumElts; ++I) { |
| 1018 | if (!Values[I]) { |
| 1019 | assert(!Mask[I]); |
| 1020 | Values[I] = UndefValue::get(InsElt.getType()->getElementType()); |
| 1021 | Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I); |
| 1022 | } |
| 1023 | } |
| 1024 | // Create new operands for a shuffle that includes the constant of the |
| 1025 | // original insertelt. |
| 1026 | return new ShuffleVectorInst(IEI->getOperand(0), |
| 1027 | ConstantVector::get(Values), |
| 1028 | ConstantVector::get(Mask)); |
| 1029 | } |
| 1030 | return nullptr; |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 1031 | } |
| 1032 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1033 | Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) { |
| 1034 | Value *VecOp = IE.getOperand(0); |
| 1035 | Value *ScalarOp = IE.getOperand(1); |
| 1036 | Value *IdxOp = IE.getOperand(2); |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 1037 | |
Igor Laevsky | e0edb66 | 2017-12-13 11:21:18 +0000 | [diff] [blame] | 1038 | if (auto *V = SimplifyInsertElementInst( |
| 1039 | VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE))) |
| 1040 | return replaceInstUsesWith(IE, V); |
| 1041 | |
Sanjay Patel | 926e477 | 2019-05-17 18:06:12 +0000 | [diff] [blame] | 1042 | // If the vector and scalar are both bitcast from the same element type, do |
| 1043 | // the insert in that source type followed by bitcast. |
| 1044 | Value *VecSrc, *ScalarSrc; |
| 1045 | if (match(VecOp, m_BitCast(m_Value(VecSrc))) && |
| 1046 | match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) && |
| 1047 | (VecOp->hasOneUse() || ScalarOp->hasOneUse()) && |
| 1048 | VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() && |
| 1049 | VecSrc->getType()->getVectorElementType() == ScalarSrc->getType()) { |
| 1050 | // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp --> |
| 1051 | // bitcast (inselt VecSrc, ScalarSrc, IdxOp) |
| 1052 | Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp); |
| 1053 | return new BitCastInst(NewInsElt, IE.getType()); |
| 1054 | } |
| 1055 | |
Sanjay Patel | 0522b0d | 2018-10-20 17:15:57 +0000 | [diff] [blame] | 1056 | // If the inserted element was extracted from some other vector and both |
Sanjay Patel | 9317963 | 2019-05-26 14:03:50 +0000 | [diff] [blame] | 1057 | // indexes are valid constants, try to turn this into a shuffle. |
Sanjay Patel | 0522b0d | 2018-10-20 17:15:57 +0000 | [diff] [blame] | 1058 | uint64_t InsertedIdx, ExtractedIdx; |
| 1059 | Value *ExtVecOp; |
| 1060 | if (match(IdxOp, m_ConstantInt(InsertedIdx)) && |
| 1061 | match(ScalarOp, m_ExtractElement(m_Value(ExtVecOp), |
Sanjay Patel | 9317963 | 2019-05-26 14:03:50 +0000 | [diff] [blame] | 1062 | m_ConstantInt(ExtractedIdx))) && |
| 1063 | ExtractedIdx < ExtVecOp->getType()->getVectorNumElements()) { |
Sanjay Patel | 0522b0d | 2018-10-20 17:15:57 +0000 | [diff] [blame] | 1064 | // TODO: Looking at the user(s) to determine if this insert is a |
| 1065 | // fold-to-shuffle opportunity does not match the usual instcombine |
| 1066 | // constraints. We should decide if the transform is worthy based only |
| 1067 | // on this instruction and its operands, but that may not work currently. |
| 1068 | // |
| 1069 | // Here, we are trying to avoid creating shuffles before reaching |
| 1070 | // the end of a chain of extract-insert pairs. This is complicated because |
| 1071 | // we do not generally form arbitrary shuffle masks in instcombine |
| 1072 | // (because those may codegen poorly), but collectShuffleElements() does |
| 1073 | // exactly that. |
| 1074 | // |
| 1075 | // The rules for determining what is an acceptable target-independent |
| 1076 | // shuffle mask are fuzzy because they evolve based on the backend's |
| 1077 | // capabilities and real-world impact. |
| 1078 | auto isShuffleRootCandidate = [](InsertElementInst &Insert) { |
| 1079 | if (!Insert.hasOneUse()) |
| 1080 | return true; |
| 1081 | auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back()); |
| 1082 | if (!InsertUser) |
| 1083 | return true; |
| 1084 | return false; |
| 1085 | }; |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 1086 | |
Sanjay Patel | 0522b0d | 2018-10-20 17:15:57 +0000 | [diff] [blame] | 1087 | // Try to form a shuffle from a chain of extract-insert ops. |
| 1088 | if (isShuffleRootCandidate(IE)) { |
| 1089 | SmallVector<Constant*, 16> Mask; |
| 1090 | ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this); |
Sanjay Patel | 729c436 | 2018-10-20 16:25:55 +0000 | [diff] [blame] | 1091 | |
Sanjay Patel | 0522b0d | 2018-10-20 17:15:57 +0000 | [diff] [blame] | 1092 | // The proposed shuffle may be trivial, in which case we shouldn't |
| 1093 | // perform the combine. |
| 1094 | if (LR.first != &IE && LR.second != &IE) { |
| 1095 | // We now have a shuffle of LHS, RHS, Mask. |
| 1096 | if (LR.second == nullptr) |
| 1097 | LR.second = UndefValue::get(LR.first->getType()); |
| 1098 | return new ShuffleVectorInst(LR.first, LR.second, |
| 1099 | ConstantVector::get(Mask)); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1100 | } |
| 1101 | } |
| 1102 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 1103 | |
Craig Topper | 17b5568 | 2016-12-29 07:03:18 +0000 | [diff] [blame] | 1104 | unsigned VWidth = VecOp->getType()->getVectorNumElements(); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1105 | APInt UndefElts(VWidth, 0); |
| 1106 | APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); |
Eli Friedman | ef200db | 2011-02-19 22:42:40 +0000 | [diff] [blame] | 1107 | if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) { |
| 1108 | if (V != &IE) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 1109 | return replaceInstUsesWith(IE, V); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1110 | return &IE; |
Eli Friedman | ef200db | 2011-02-19 22:42:40 +0000 | [diff] [blame] | 1111 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 1112 | |
Sanjay Patel | 521f19f | 2016-09-02 17:05:43 +0000 | [diff] [blame] | 1113 | if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE)) |
| 1114 | return Shuf; |
| 1115 | |
Craig Topper | bb4069e | 2017-07-07 23:16:26 +0000 | [diff] [blame] | 1116 | if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder)) |
Sanjay Patel | 2f602ce | 2017-03-22 17:10:44 +0000 | [diff] [blame] | 1117 | return NewInsElt; |
| 1118 | |
Sanjay Patel | 71ad227 | 2019-06-26 15:52:59 +0000 | [diff] [blame] | 1119 | if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE)) |
Michael Kuperstein | cd7ad71 | 2016-12-28 00:18:08 +0000 | [diff] [blame] | 1120 | return Broadcast; |
| 1121 | |
Sanjay Patel | 3dee113 | 2019-07-08 19:48:52 +0000 | [diff] [blame] | 1122 | if (Instruction *Splat = foldInsEltIntoSplat(IE)) |
| 1123 | return Splat; |
| 1124 | |
Sanjay Patel | aff5bee | 2019-09-08 19:03:01 +0000 | [diff] [blame] | 1125 | if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE)) |
| 1126 | return IdentityShuf; |
| 1127 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1128 | return nullptr; |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1129 | } |
| 1130 | |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1131 | /// Return true if we can evaluate the specified expression tree if the vector |
| 1132 | /// elements were shuffled in a different order. |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1133 | static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask, |
Nick Lewycky | 3f715e2 | 2013-06-01 20:51:31 +0000 | [diff] [blame] | 1134 | unsigned Depth = 5) { |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1135 | // We can always reorder the elements of a constant. |
| 1136 | if (isa<Constant>(V)) |
| 1137 | return true; |
| 1138 | |
| 1139 | // We won't reorder vector arguments. No IPO here. |
| 1140 | Instruction *I = dyn_cast<Instruction>(V); |
| 1141 | if (!I) return false; |
| 1142 | |
| 1143 | // Two users may expect different orders of the elements. Don't try it. |
| 1144 | if (!I->hasOneUse()) |
| 1145 | return false; |
| 1146 | |
| 1147 | if (Depth == 0) return false; |
| 1148 | |
| 1149 | switch (I->getOpcode()) { |
Bjorn Pettersson | 6456252 | 2019-10-18 07:42:02 +0000 | [diff] [blame] | 1150 | case Instruction::UDiv: |
| 1151 | case Instruction::SDiv: |
| 1152 | case Instruction::URem: |
| 1153 | case Instruction::SRem: |
| 1154 | // Propagating an undefined shuffle mask element to integer div/rem is not |
| 1155 | // allowed because those opcodes can create immediate undefined behavior |
| 1156 | // from an undefined element in an operand. |
| 1157 | if (llvm::any_of(Mask, [](int M){ return M == -1; })) |
| 1158 | return false; |
| 1159 | LLVM_FALLTHROUGH; |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1160 | case Instruction::Add: |
| 1161 | case Instruction::FAdd: |
| 1162 | case Instruction::Sub: |
| 1163 | case Instruction::FSub: |
| 1164 | case Instruction::Mul: |
| 1165 | case Instruction::FMul: |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1166 | case Instruction::FDiv: |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1167 | case Instruction::FRem: |
| 1168 | case Instruction::Shl: |
| 1169 | case Instruction::LShr: |
| 1170 | case Instruction::AShr: |
| 1171 | case Instruction::And: |
| 1172 | case Instruction::Or: |
| 1173 | case Instruction::Xor: |
| 1174 | case Instruction::ICmp: |
| 1175 | case Instruction::FCmp: |
| 1176 | case Instruction::Trunc: |
| 1177 | case Instruction::ZExt: |
| 1178 | case Instruction::SExt: |
| 1179 | case Instruction::FPToUI: |
| 1180 | case Instruction::FPToSI: |
| 1181 | case Instruction::UIToFP: |
| 1182 | case Instruction::SIToFP: |
| 1183 | case Instruction::FPTrunc: |
| 1184 | case Instruction::FPExt: |
| 1185 | case Instruction::GetElementPtr: { |
Sanjay Patel | 26c119a | 2018-09-30 13:50:42 +0000 | [diff] [blame] | 1186 | // Bail out if we would create longer vector ops. We could allow creating |
Bjorn Pettersson | 6456252 | 2019-10-18 07:42:02 +0000 | [diff] [blame] | 1187 | // longer vector ops, but that may result in more expensive codegen. |
Sanjay Patel | 26c119a | 2018-09-30 13:50:42 +0000 | [diff] [blame] | 1188 | Type *ITy = I->getType(); |
| 1189 | if (ITy->isVectorTy() && Mask.size() > ITy->getVectorNumElements()) |
| 1190 | return false; |
Sanjay Patel | 4e2875314 | 2015-11-16 22:16:52 +0000 | [diff] [blame] | 1191 | for (Value *Operand : I->operands()) { |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1192 | if (!canEvaluateShuffled(Operand, Mask, Depth - 1)) |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1193 | return false; |
| 1194 | } |
| 1195 | return true; |
| 1196 | } |
| 1197 | case Instruction::InsertElement: { |
| 1198 | ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); |
| 1199 | if (!CI) return false; |
| 1200 | int ElementNumber = CI->getLimitedValue(); |
| 1201 | |
| 1202 | // Verify that 'CI' does not occur twice in Mask. A single 'insertelement' |
| 1203 | // can't put an element into multiple indices. |
| 1204 | bool SeenOnce = false; |
| 1205 | for (int i = 0, e = Mask.size(); i != e; ++i) { |
| 1206 | if (Mask[i] == ElementNumber) { |
| 1207 | if (SeenOnce) |
| 1208 | return false; |
| 1209 | SeenOnce = true; |
| 1210 | } |
| 1211 | } |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1212 | return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1213 | } |
| 1214 | } |
| 1215 | return false; |
| 1216 | } |
| 1217 | |
| 1218 | /// Rebuild a new instruction just like 'I' but with the new operands given. |
| 1219 | /// In the event of type mismatch, the type of the operands is correct. |
Sanjay Patel | 431e114 | 2015-11-17 17:24:08 +0000 | [diff] [blame] | 1220 | static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) { |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1221 | // We don't want to use the IRBuilder here because we want the replacement |
| 1222 | // instructions to appear next to 'I', not the builder's insertion point. |
| 1223 | switch (I->getOpcode()) { |
| 1224 | case Instruction::Add: |
| 1225 | case Instruction::FAdd: |
| 1226 | case Instruction::Sub: |
| 1227 | case Instruction::FSub: |
| 1228 | case Instruction::Mul: |
| 1229 | case Instruction::FMul: |
| 1230 | case Instruction::UDiv: |
| 1231 | case Instruction::SDiv: |
| 1232 | case Instruction::FDiv: |
| 1233 | case Instruction::URem: |
| 1234 | case Instruction::SRem: |
| 1235 | case Instruction::FRem: |
| 1236 | case Instruction::Shl: |
| 1237 | case Instruction::LShr: |
| 1238 | case Instruction::AShr: |
| 1239 | case Instruction::And: |
| 1240 | case Instruction::Or: |
| 1241 | case Instruction::Xor: { |
| 1242 | BinaryOperator *BO = cast<BinaryOperator>(I); |
| 1243 | assert(NewOps.size() == 2 && "binary operator with #ops != 2"); |
| 1244 | BinaryOperator *New = |
| 1245 | BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(), |
| 1246 | NewOps[0], NewOps[1], "", BO); |
| 1247 | if (isa<OverflowingBinaryOperator>(BO)) { |
| 1248 | New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap()); |
| 1249 | New->setHasNoSignedWrap(BO->hasNoSignedWrap()); |
| 1250 | } |
| 1251 | if (isa<PossiblyExactOperator>(BO)) { |
| 1252 | New->setIsExact(BO->isExact()); |
| 1253 | } |
Owen Anderson | 48b842e | 2014-01-18 00:48:14 +0000 | [diff] [blame] | 1254 | if (isa<FPMathOperator>(BO)) |
| 1255 | New->copyFastMathFlags(I); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1256 | return New; |
| 1257 | } |
| 1258 | case Instruction::ICmp: |
| 1259 | assert(NewOps.size() == 2 && "icmp with #ops != 2"); |
| 1260 | return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(), |
| 1261 | NewOps[0], NewOps[1]); |
| 1262 | case Instruction::FCmp: |
| 1263 | assert(NewOps.size() == 2 && "fcmp with #ops != 2"); |
| 1264 | return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(), |
| 1265 | NewOps[0], NewOps[1]); |
| 1266 | case Instruction::Trunc: |
| 1267 | case Instruction::ZExt: |
| 1268 | case Instruction::SExt: |
| 1269 | case Instruction::FPToUI: |
| 1270 | case Instruction::FPToSI: |
| 1271 | case Instruction::UIToFP: |
| 1272 | case Instruction::SIToFP: |
| 1273 | case Instruction::FPTrunc: |
| 1274 | case Instruction::FPExt: { |
| 1275 | // It's possible that the mask has a different number of elements from |
| 1276 | // the original cast. We recompute the destination type to match the mask. |
| 1277 | Type *DestTy = |
| 1278 | VectorType::get(I->getType()->getScalarType(), |
| 1279 | NewOps[0]->getType()->getVectorNumElements()); |
| 1280 | assert(NewOps.size() == 1 && "cast with #ops != 1"); |
| 1281 | return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy, |
| 1282 | "", I); |
| 1283 | } |
| 1284 | case Instruction::GetElementPtr: { |
| 1285 | Value *Ptr = NewOps[0]; |
| 1286 | ArrayRef<Value*> Idx = NewOps.slice(1); |
David Blaikie | 22319eb | 2015-03-14 19:24:04 +0000 | [diff] [blame] | 1287 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
| 1288 | cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1289 | GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds()); |
| 1290 | return GEP; |
| 1291 | } |
| 1292 | } |
| 1293 | llvm_unreachable("failed to rebuild vector instructions"); |
| 1294 | } |
| 1295 | |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1296 | static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) { |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1297 | // Mask.size() does not need to be equal to the number of vector elements. |
| 1298 | |
| 1299 | assert(V->getType()->isVectorTy() && "can't reorder non-vector elements"); |
Sanjay Patel | ce36b03 | 2017-10-09 17:54:46 +0000 | [diff] [blame] | 1300 | Type *EltTy = V->getType()->getScalarType(); |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1301 | Type *I32Ty = IntegerType::getInt32Ty(V->getContext()); |
Sanjay Patel | ce36b03 | 2017-10-09 17:54:46 +0000 | [diff] [blame] | 1302 | if (isa<UndefValue>(V)) |
| 1303 | return UndefValue::get(VectorType::get(EltTy, Mask.size())); |
| 1304 | |
| 1305 | if (isa<ConstantAggregateZero>(V)) |
| 1306 | return ConstantAggregateZero::get(VectorType::get(EltTy, Mask.size())); |
| 1307 | |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1308 | if (Constant *C = dyn_cast<Constant>(V)) { |
| 1309 | SmallVector<Constant *, 16> MaskValues; |
| 1310 | for (int i = 0, e = Mask.size(); i != e; ++i) { |
| 1311 | if (Mask[i] == -1) |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1312 | MaskValues.push_back(UndefValue::get(I32Ty)); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1313 | else |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1314 | MaskValues.push_back(ConstantInt::get(I32Ty, Mask[i])); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1315 | } |
| 1316 | return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()), |
| 1317 | ConstantVector::get(MaskValues)); |
| 1318 | } |
| 1319 | |
| 1320 | Instruction *I = cast<Instruction>(V); |
| 1321 | switch (I->getOpcode()) { |
| 1322 | case Instruction::Add: |
| 1323 | case Instruction::FAdd: |
| 1324 | case Instruction::Sub: |
| 1325 | case Instruction::FSub: |
| 1326 | case Instruction::Mul: |
| 1327 | case Instruction::FMul: |
| 1328 | case Instruction::UDiv: |
| 1329 | case Instruction::SDiv: |
| 1330 | case Instruction::FDiv: |
| 1331 | case Instruction::URem: |
| 1332 | case Instruction::SRem: |
| 1333 | case Instruction::FRem: |
| 1334 | case Instruction::Shl: |
| 1335 | case Instruction::LShr: |
| 1336 | case Instruction::AShr: |
| 1337 | case Instruction::And: |
| 1338 | case Instruction::Or: |
| 1339 | case Instruction::Xor: |
| 1340 | case Instruction::ICmp: |
| 1341 | case Instruction::FCmp: |
| 1342 | case Instruction::Trunc: |
| 1343 | case Instruction::ZExt: |
| 1344 | case Instruction::SExt: |
| 1345 | case Instruction::FPToUI: |
| 1346 | case Instruction::FPToSI: |
| 1347 | case Instruction::UIToFP: |
| 1348 | case Instruction::SIToFP: |
| 1349 | case Instruction::FPTrunc: |
| 1350 | case Instruction::FPExt: |
| 1351 | case Instruction::Select: |
| 1352 | case Instruction::GetElementPtr: { |
| 1353 | SmallVector<Value*, 8> NewOps; |
| 1354 | bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements()); |
| 1355 | for (int i = 0, e = I->getNumOperands(); i != e; ++i) { |
Mikael Holmen | 150a7ec | 2019-04-01 14:10:10 +0000 | [diff] [blame] | 1356 | Value *V; |
| 1357 | // Recursively call evaluateInDifferentElementOrder on vector arguments |
| 1358 | // as well. E.g. GetElementPtr may have scalar operands even if the |
| 1359 | // return value is a vector, so we need to examine the operand type. |
| 1360 | if (I->getOperand(i)->getType()->isVectorTy()) |
| 1361 | V = evaluateInDifferentElementOrder(I->getOperand(i), Mask); |
| 1362 | else |
| 1363 | V = I->getOperand(i); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1364 | NewOps.push_back(V); |
| 1365 | NeedsRebuild |= (V != I->getOperand(i)); |
| 1366 | } |
| 1367 | if (NeedsRebuild) { |
Sanjay Patel | 431e114 | 2015-11-17 17:24:08 +0000 | [diff] [blame] | 1368 | return buildNew(I, NewOps); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1369 | } |
| 1370 | return I; |
| 1371 | } |
| 1372 | case Instruction::InsertElement: { |
| 1373 | int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue(); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1374 | |
| 1375 | // The insertelement was inserting at Element. Figure out which element |
| 1376 | // that becomes after shuffling. The answer is guaranteed to be unique |
| 1377 | // by CanEvaluateShuffled. |
Nick Lewycky | 3f715e2 | 2013-06-01 20:51:31 +0000 | [diff] [blame] | 1378 | bool Found = false; |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1379 | int Index = 0; |
Nick Lewycky | 3f715e2 | 2013-06-01 20:51:31 +0000 | [diff] [blame] | 1380 | for (int e = Mask.size(); Index != e; ++Index) { |
| 1381 | if (Mask[Index] == Element) { |
| 1382 | Found = true; |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1383 | break; |
Nick Lewycky | 3f715e2 | 2013-06-01 20:51:31 +0000 | [diff] [blame] | 1384 | } |
| 1385 | } |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1386 | |
Hao Liu | 26abebb | 2014-01-08 03:06:15 +0000 | [diff] [blame] | 1387 | // If element is not in Mask, no need to handle the operand 1 (element to |
| 1388 | // be inserted). Just evaluate values in operand 0 according to Mask. |
Nick Lewycky | 3f715e2 | 2013-06-01 20:51:31 +0000 | [diff] [blame] | 1389 | if (!Found) |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1390 | return evaluateInDifferentElementOrder(I->getOperand(0), Mask); |
Joey Gouly | a3250f2 | 2013-07-12 23:08:06 +0000 | [diff] [blame] | 1391 | |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1392 | Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1393 | return InsertElementInst::Create(V, I->getOperand(1), |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1394 | ConstantInt::get(I32Ty, Index), "", I); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1395 | } |
| 1396 | } |
| 1397 | llvm_unreachable("failed to reorder elements of vector instruction!"); |
| 1398 | } |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1399 | |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 1400 | // Returns true if the shuffle is extracting a contiguous range of values from |
| 1401 | // LHS, for example: |
| 1402 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |
| 1403 | // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP| |
| 1404 | // Shuffles to: |EE|FF|GG|HH| |
| 1405 | // +--+--+--+--+ |
| 1406 | static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, |
| 1407 | SmallVector<int, 16> &Mask) { |
Craig Topper | 17b5568 | 2016-12-29 07:03:18 +0000 | [diff] [blame] | 1408 | unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements(); |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 1409 | unsigned MaskElems = Mask.size(); |
| 1410 | unsigned BegIdx = Mask.front(); |
| 1411 | unsigned EndIdx = Mask.back(); |
| 1412 | if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1) |
| 1413 | return false; |
| 1414 | for (unsigned I = 0; I != MaskElems; ++I) |
| 1415 | if (static_cast<unsigned>(Mask[I]) != BegIdx + I) |
| 1416 | return false; |
| 1417 | return true; |
| 1418 | } |
| 1419 | |
Sanjay Patel | b999d74 | 2018-07-02 17:42:29 +0000 | [diff] [blame] | 1420 | /// These are the ingredients in an alternate form binary operator as described |
| 1421 | /// below. |
| 1422 | struct BinopElts { |
| 1423 | BinaryOperator::BinaryOps Opcode; |
| 1424 | Value *Op0; |
| 1425 | Value *Op1; |
| 1426 | BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0, |
| 1427 | Value *V0 = nullptr, Value *V1 = nullptr) : |
| 1428 | Opcode(Opc), Op0(V0), Op1(V1) {} |
| 1429 | operator bool() const { return Opcode != 0; } |
| 1430 | }; |
| 1431 | |
| 1432 | /// Binops may be transformed into binops with different opcodes and operands. |
| 1433 | /// Reverse the usual canonicalization to enable folds with the non-canonical |
| 1434 | /// form of the binop. If a transform is possible, return the elements of the |
| 1435 | /// new binop. If not, return invalid elements. |
| 1436 | static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) { |
| 1437 | Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1); |
| 1438 | Type *Ty = BO->getType(); |
| 1439 | switch (BO->getOpcode()) { |
| 1440 | case Instruction::Shl: { |
| 1441 | // shl X, C --> mul X, (1 << C) |
| 1442 | Constant *C; |
| 1443 | if (match(BO1, m_Constant(C))) { |
| 1444 | Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C); |
| 1445 | return { Instruction::Mul, BO0, ShlOne }; |
| 1446 | } |
| 1447 | break; |
| 1448 | } |
| 1449 | case Instruction::Or: { |
| 1450 | // or X, C --> add X, C (when X and C have no common bits set) |
| 1451 | const APInt *C; |
| 1452 | if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL)) |
| 1453 | return { Instruction::Add, BO0, BO1 }; |
| 1454 | break; |
| 1455 | } |
| 1456 | default: |
| 1457 | break; |
| 1458 | } |
| 1459 | return {}; |
| 1460 | } |
| 1461 | |
Sanjay Patel | 3074b9e | 2018-07-03 13:44:22 +0000 | [diff] [blame] | 1462 | static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) { |
| 1463 | assert(Shuf.isSelect() && "Must have select-equivalent shuffle"); |
| 1464 | |
| 1465 | // Are we shuffling together some value and that same value after it has been |
| 1466 | // modified by a binop with a constant? |
| 1467 | Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1); |
| 1468 | Constant *C; |
| 1469 | bool Op0IsBinop; |
| 1470 | if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C)))) |
| 1471 | Op0IsBinop = true; |
| 1472 | else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C)))) |
| 1473 | Op0IsBinop = false; |
| 1474 | else |
| 1475 | return nullptr; |
| 1476 | |
Sanjay Patel | 3074b9e | 2018-07-03 13:44:22 +0000 | [diff] [blame] | 1477 | // The identity constant for a binop leaves a variable operand unchanged. For |
| 1478 | // a vector, this is a splat of something like 0, -1, or 1. |
| 1479 | // If there's no identity constant for this binop, we're done. |
Sanjay Patel | 509a1e7 | 2018-07-10 15:12:31 +0000 | [diff] [blame] | 1480 | auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1); |
Sanjay Patel | 3074b9e | 2018-07-03 13:44:22 +0000 | [diff] [blame] | 1481 | BinaryOperator::BinaryOps BOpcode = BO->getOpcode(); |
Sanjay Patel | 509a1e7 | 2018-07-10 15:12:31 +0000 | [diff] [blame] | 1482 | Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true); |
Sanjay Patel | 3074b9e | 2018-07-03 13:44:22 +0000 | [diff] [blame] | 1483 | if (!IdC) |
| 1484 | return nullptr; |
| 1485 | |
| 1486 | // Shuffle identity constants into the lanes that return the original value. |
| 1487 | // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4} |
| 1488 | // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4} |
| 1489 | // The existing binop constant vector remains in the same operand position. |
| 1490 | Constant *Mask = Shuf.getMask(); |
| 1491 | Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) : |
| 1492 | ConstantExpr::getShuffleVector(IdC, C, Mask); |
| 1493 | |
Sanjay Patel | 509a1e7 | 2018-07-10 15:12:31 +0000 | [diff] [blame] | 1494 | bool MightCreatePoisonOrUB = |
| 1495 | Mask->containsUndefElement() && |
| 1496 | (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode)); |
| 1497 | if (MightCreatePoisonOrUB) |
| 1498 | NewC = getSafeVectorConstantForBinop(BOpcode, NewC, true); |
| 1499 | |
Sanjay Patel | 3074b9e | 2018-07-03 13:44:22 +0000 | [diff] [blame] | 1500 | // shuf (bop X, C), X, M --> bop X, C' |
| 1501 | // shuf X, (bop X, C), M --> bop X, C' |
Sanjay Patel | 509a1e7 | 2018-07-10 15:12:31 +0000 | [diff] [blame] | 1502 | Value *X = Op0IsBinop ? Op1 : Op0; |
Sanjay Patel | 3074b9e | 2018-07-03 13:44:22 +0000 | [diff] [blame] | 1503 | Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC); |
| 1504 | NewBO->copyIRFlags(BO); |
Sanjay Patel | 3333106 | 2018-07-10 14:27:55 +0000 | [diff] [blame] | 1505 | |
| 1506 | // An undef shuffle mask element may propagate as an undef constant element in |
| 1507 | // the new binop. That would produce poison where the original code might not. |
Sanjay Patel | 509a1e7 | 2018-07-10 15:12:31 +0000 | [diff] [blame] | 1508 | // If we already made a safe constant, then there's no danger. |
| 1509 | if (Mask->containsUndefElement() && !MightCreatePoisonOrUB) |
Sanjay Patel | 3333106 | 2018-07-10 14:27:55 +0000 | [diff] [blame] | 1510 | NewBO->dropPoisonGeneratingFlags(); |
Sanjay Patel | 3074b9e | 2018-07-03 13:44:22 +0000 | [diff] [blame] | 1511 | return NewBO; |
| 1512 | } |
| 1513 | |
Sanjay Patel | 0b59103 | 2019-07-08 16:26:48 +0000 | [diff] [blame] | 1514 | /// If we have an insert of a scalar to a non-zero element of an undefined |
| 1515 | /// vector and then shuffle that value, that's the same as inserting to the zero |
| 1516 | /// element and shuffling. Splatting from the zero element is recognized as the |
| 1517 | /// canonical form of splat. |
| 1518 | static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf, |
| 1519 | InstCombiner::BuilderTy &Builder) { |
| 1520 | Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1); |
| 1521 | Constant *Mask = Shuf.getMask(); |
| 1522 | Value *X; |
| 1523 | uint64_t IndexC; |
| 1524 | |
| 1525 | // Match a shuffle that is a splat to a non-zero element. |
| 1526 | if (!match(Op0, m_OneUse(m_InsertElement(m_Undef(), m_Value(X), |
| 1527 | m_ConstantInt(IndexC)))) || |
| 1528 | !match(Op1, m_Undef()) || match(Mask, m_ZeroInt()) || IndexC == 0) |
| 1529 | return nullptr; |
| 1530 | |
| 1531 | // Insert into element 0 of an undef vector. |
| 1532 | UndefValue *UndefVec = UndefValue::get(Shuf.getType()); |
| 1533 | Constant *Zero = Builder.getInt32(0); |
| 1534 | Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero); |
| 1535 | |
| 1536 | // Splat from element 0. Any mask element that is undefined remains undefined. |
| 1537 | // For example: |
| 1538 | // shuf (inselt undef, X, 2), undef, <2,2,undef> |
| 1539 | // --> shuf (inselt undef, X, 0), undef, <0,0,undef> |
| 1540 | unsigned NumMaskElts = Shuf.getType()->getVectorNumElements(); |
| 1541 | SmallVector<Constant *, 16> NewMask(NumMaskElts, Zero); |
| 1542 | for (unsigned i = 0; i != NumMaskElts; ++i) |
| 1543 | if (isa<UndefValue>(Mask->getAggregateElement(i))) |
| 1544 | NewMask[i] = Mask->getAggregateElement(i); |
| 1545 | |
| 1546 | return new ShuffleVectorInst(NewIns, UndefVec, ConstantVector::get(NewMask)); |
| 1547 | } |
| 1548 | |
Sanjay Patel | b999d74 | 2018-07-02 17:42:29 +0000 | [diff] [blame] | 1549 | /// Try to fold shuffles that are the equivalent of a vector select. |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1550 | static Instruction *foldSelectShuffle(ShuffleVectorInst &Shuf, |
Sanjay Patel | b999d74 | 2018-07-02 17:42:29 +0000 | [diff] [blame] | 1551 | InstCombiner::BuilderTy &Builder, |
| 1552 | const DataLayout &DL) { |
Sanjay Patel | a76b700 | 2018-06-21 20:15:09 +0000 | [diff] [blame] | 1553 | if (!Shuf.isSelect()) |
| 1554 | return nullptr; |
| 1555 | |
Sanjay Patel | e85d2e4 | 2019-11-25 11:55:57 -0500 | [diff] [blame] | 1556 | // Canonicalize to choose from operand 0 first unless operand 1 is undefined. |
| 1557 | // Commuting undef to operand 0 conflicts with another canonicalization. |
Sanjay Patel | b276dd1 | 2019-03-31 15:01:30 +0000 | [diff] [blame] | 1558 | unsigned NumElts = Shuf.getType()->getVectorNumElements(); |
Sanjay Patel | e85d2e4 | 2019-11-25 11:55:57 -0500 | [diff] [blame] | 1559 | if (!isa<UndefValue>(Shuf.getOperand(1)) && |
| 1560 | Shuf.getMaskValue(0) >= (int)NumElts) { |
Sanjay Patel | b33938d | 2019-04-08 13:28:29 +0000 | [diff] [blame] | 1561 | // TODO: Can we assert that both operands of a shuffle-select are not undef |
| 1562 | // (otherwise, it would have been folded by instsimplify? |
Sanjay Patel | b276dd1 | 2019-03-31 15:01:30 +0000 | [diff] [blame] | 1563 | Shuf.commute(); |
| 1564 | return &Shuf; |
| 1565 | } |
| 1566 | |
Sanjay Patel | 3074b9e | 2018-07-03 13:44:22 +0000 | [diff] [blame] | 1567 | if (Instruction *I = foldSelectShuffleWith1Binop(Shuf)) |
| 1568 | return I; |
| 1569 | |
Sanjay Patel | a76b700 | 2018-06-21 20:15:09 +0000 | [diff] [blame] | 1570 | BinaryOperator *B0, *B1; |
| 1571 | if (!match(Shuf.getOperand(0), m_BinOp(B0)) || |
| 1572 | !match(Shuf.getOperand(1), m_BinOp(B1))) |
| 1573 | return nullptr; |
| 1574 | |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1575 | Value *X, *Y; |
Sanjay Patel | a76b700 | 2018-06-21 20:15:09 +0000 | [diff] [blame] | 1576 | Constant *C0, *C1; |
Sanjay Patel | a52963b | 2018-06-22 12:46:16 +0000 | [diff] [blame] | 1577 | bool ConstantsAreOp1; |
| 1578 | if (match(B0, m_BinOp(m_Value(X), m_Constant(C0))) && |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1579 | match(B1, m_BinOp(m_Value(Y), m_Constant(C1)))) |
Sanjay Patel | a52963b | 2018-06-22 12:46:16 +0000 | [diff] [blame] | 1580 | ConstantsAreOp1 = true; |
| 1581 | else if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) && |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1582 | match(B1, m_BinOp(m_Constant(C1), m_Value(Y)))) |
Sanjay Patel | a52963b | 2018-06-22 12:46:16 +0000 | [diff] [blame] | 1583 | ConstantsAreOp1 = false; |
| 1584 | else |
Sanjay Patel | a76b700 | 2018-06-21 20:15:09 +0000 | [diff] [blame] | 1585 | return nullptr; |
| 1586 | |
Sanjay Patel | 57bda36 | 2018-06-28 17:48:04 +0000 | [diff] [blame] | 1587 | // We need matching binops to fold the lanes together. |
| 1588 | BinaryOperator::BinaryOps Opc0 = B0->getOpcode(); |
| 1589 | BinaryOperator::BinaryOps Opc1 = B1->getOpcode(); |
| 1590 | bool DropNSW = false; |
| 1591 | if (ConstantsAreOp1 && Opc0 != Opc1) { |
Sanjay Patel | 57bda36 | 2018-06-28 17:48:04 +0000 | [diff] [blame] | 1592 | // TODO: We drop "nsw" if shift is converted into multiply because it may |
| 1593 | // not be correct when the shift amount is BitWidth - 1. We could examine |
| 1594 | // each vector element to determine if it is safe to keep that flag. |
Sanjay Patel | b999d74 | 2018-07-02 17:42:29 +0000 | [diff] [blame] | 1595 | if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl) |
Sanjay Patel | 57bda36 | 2018-06-28 17:48:04 +0000 | [diff] [blame] | 1596 | DropNSW = true; |
Sanjay Patel | b999d74 | 2018-07-02 17:42:29 +0000 | [diff] [blame] | 1597 | if (BinopElts AltB0 = getAlternateBinop(B0, DL)) { |
| 1598 | assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop"); |
| 1599 | Opc0 = AltB0.Opcode; |
| 1600 | C0 = cast<Constant>(AltB0.Op1); |
| 1601 | } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) { |
| 1602 | assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop"); |
| 1603 | Opc1 = AltB1.Opcode; |
| 1604 | C1 = cast<Constant>(AltB1.Op1); |
Sanjay Patel | 57bda36 | 2018-06-28 17:48:04 +0000 | [diff] [blame] | 1605 | } |
| 1606 | } |
| 1607 | |
| 1608 | if (Opc0 != Opc1) |
Sanjay Patel | 4784e15 | 2018-06-21 23:56:59 +0000 | [diff] [blame] | 1609 | return nullptr; |
| 1610 | |
Sanjay Patel | 57bda36 | 2018-06-28 17:48:04 +0000 | [diff] [blame] | 1611 | // The opcodes must be the same. Use a new name to make that clear. |
| 1612 | BinaryOperator::BinaryOps BOpc = Opc0; |
| 1613 | |
Sanjay Patel | 06ea420 | 2018-07-10 13:33:26 +0000 | [diff] [blame] | 1614 | // Select the constant elements needed for the single binop. |
| 1615 | Constant *Mask = Shuf.getMask(); |
| 1616 | Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask); |
| 1617 | |
Sanjay Patel | 5bd3664 | 2018-07-09 13:21:46 +0000 | [diff] [blame] | 1618 | // We are moving a binop after a shuffle. When a shuffle has an undefined |
| 1619 | // mask element, the result is undefined, but it is not poison or undefined |
| 1620 | // behavior. That is not necessarily true for div/rem/shift. |
Sanjay Patel | 5bd3664 | 2018-07-09 13:21:46 +0000 | [diff] [blame] | 1621 | bool MightCreatePoisonOrUB = |
| 1622 | Mask->containsUndefElement() && |
| 1623 | (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc)); |
Sanjay Patel | 06ea420 | 2018-07-10 13:33:26 +0000 | [diff] [blame] | 1624 | if (MightCreatePoisonOrUB) |
| 1625 | NewC = getSafeVectorConstantForBinop(BOpc, NewC, ConstantsAreOp1); |
Sanjay Patel | 5bd3664 | 2018-07-09 13:21:46 +0000 | [diff] [blame] | 1626 | |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1627 | Value *V; |
| 1628 | if (X == Y) { |
| 1629 | // Remove a binop and the shuffle by rearranging the constant: |
| 1630 | // shuffle (op V, C0), (op V, C1), M --> op V, C' |
| 1631 | // shuffle (op C0, V), (op C1, V), M --> op C', V |
| 1632 | V = X; |
Sanjay Patel | 5bd3664 | 2018-07-09 13:21:46 +0000 | [diff] [blame] | 1633 | } else { |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1634 | // If there are 2 different variable operands, we must create a new shuffle |
| 1635 | // (select) first, so check uses to ensure that we don't end up with more |
| 1636 | // instructions than we started with. |
Sanjay Patel | 5bd3664 | 2018-07-09 13:21:46 +0000 | [diff] [blame] | 1637 | if (!B0->hasOneUse() && !B1->hasOneUse()) |
| 1638 | return nullptr; |
| 1639 | |
Sanjay Patel | 06ea420 | 2018-07-10 13:33:26 +0000 | [diff] [blame] | 1640 | // If we use the original shuffle mask and op1 is *variable*, we would be |
| 1641 | // putting an undef into operand 1 of div/rem/shift. This is either UB or |
| 1642 | // poison. We do not have to guard against UB when *constants* are op1 |
| 1643 | // because safe constants guarantee that we do not overflow sdiv/srem (and |
| 1644 | // there's no danger for other opcodes). |
| 1645 | // TODO: To allow this case, create a new shuffle mask with no undefs. |
| 1646 | if (MightCreatePoisonOrUB && !ConstantsAreOp1) |
Sanjay Patel | 5bd3664 | 2018-07-09 13:21:46 +0000 | [diff] [blame] | 1647 | return nullptr; |
| 1648 | |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1649 | // Note: In general, we do not create new shuffles in InstCombine because we |
| 1650 | // do not know if a target can lower an arbitrary shuffle optimally. In this |
| 1651 | // case, the shuffle uses the existing mask, so there is no additional risk. |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1652 | |
| 1653 | // Select the variable vectors first, then perform the binop: |
| 1654 | // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C' |
| 1655 | // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M) |
Sanjay Patel | 5bd3664 | 2018-07-09 13:21:46 +0000 | [diff] [blame] | 1656 | V = Builder.CreateShuffleVector(X, Y, Mask); |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1657 | } |
| 1658 | |
Sanjay Patel | da66753 | 2018-06-29 13:44:06 +0000 | [diff] [blame] | 1659 | Instruction *NewBO = ConstantsAreOp1 ? BinaryOperator::Create(BOpc, V, NewC) : |
| 1660 | BinaryOperator::Create(BOpc, NewC, V); |
Sanjay Patel | a76b700 | 2018-06-21 20:15:09 +0000 | [diff] [blame] | 1661 | |
Sanjay Patel | 5bd3664 | 2018-07-09 13:21:46 +0000 | [diff] [blame] | 1662 | // Flags are intersected from the 2 source binops. But there are 2 exceptions: |
| 1663 | // 1. If we changed an opcode, poison conditions might have changed. |
| 1664 | // 2. If the shuffle had undef mask elements, the new binop might have undefs |
Sanjay Patel | c8d9d81 | 2018-07-10 16:09:49 +0000 | [diff] [blame] | 1665 | // where the original code did not. But if we already made a safe constant, |
| 1666 | // then there's no danger. |
Sanjay Patel | a76b700 | 2018-06-21 20:15:09 +0000 | [diff] [blame] | 1667 | NewBO->copyIRFlags(B0); |
| 1668 | NewBO->andIRFlags(B1); |
Sanjay Patel | 57bda36 | 2018-06-28 17:48:04 +0000 | [diff] [blame] | 1669 | if (DropNSW) |
| 1670 | NewBO->setHasNoSignedWrap(false); |
Sanjay Patel | c8d9d81 | 2018-07-10 16:09:49 +0000 | [diff] [blame] | 1671 | if (Mask->containsUndefElement() && !MightCreatePoisonOrUB) |
Sanjay Patel | 5bd3664 | 2018-07-09 13:21:46 +0000 | [diff] [blame] | 1672 | NewBO->dropPoisonGeneratingFlags(); |
Sanjay Patel | a76b700 | 2018-06-21 20:15:09 +0000 | [diff] [blame] | 1673 | return NewBO; |
| 1674 | } |
| 1675 | |
Sanjay Patel | c1416b6 | 2018-09-07 21:03:34 +0000 | [diff] [blame] | 1676 | /// Match a shuffle-select-shuffle pattern where the shuffles are widening and |
| 1677 | /// narrowing (concatenating with undef and extracting back to the original |
| 1678 | /// length). This allows replacing the wide select with a narrow select. |
Sanjay Patel | 88194df | 2018-10-09 15:29:26 +0000 | [diff] [blame] | 1679 | static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf, |
| 1680 | InstCombiner::BuilderTy &Builder) { |
Sanjay Patel | c1416b6 | 2018-09-07 21:03:34 +0000 | [diff] [blame] | 1681 | // This must be a narrowing identity shuffle. It extracts the 1st N elements |
| 1682 | // of the 1st vector operand of a shuffle. |
| 1683 | if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract()) |
| 1684 | return nullptr; |
| 1685 | |
| 1686 | // The vector being shuffled must be a vector select that we can eliminate. |
| 1687 | // TODO: The one-use requirement could be eased if X and/or Y are constants. |
| 1688 | Value *Cond, *X, *Y; |
| 1689 | if (!match(Shuf.getOperand(0), |
| 1690 | m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y))))) |
| 1691 | return nullptr; |
| 1692 | |
| 1693 | // We need a narrow condition value. It must be extended with undef elements |
| 1694 | // and have the same number of elements as this shuffle. |
| 1695 | unsigned NarrowNumElts = Shuf.getType()->getVectorNumElements(); |
| 1696 | Value *NarrowCond; |
| 1697 | if (!match(Cond, m_OneUse(m_ShuffleVector(m_Value(NarrowCond), m_Undef(), |
| 1698 | m_Constant()))) || |
| 1699 | NarrowCond->getType()->getVectorNumElements() != NarrowNumElts || |
| 1700 | !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding()) |
| 1701 | return nullptr; |
| 1702 | |
| 1703 | // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) --> |
| 1704 | // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask) |
| 1705 | Value *Undef = UndefValue::get(X->getType()); |
| 1706 | Value *NarrowX = Builder.CreateShuffleVector(X, Undef, Shuf.getMask()); |
| 1707 | Value *NarrowY = Builder.CreateShuffleVector(Y, Undef, Shuf.getMask()); |
| 1708 | return SelectInst::Create(NarrowCond, NarrowX, NarrowY); |
| 1709 | } |
| 1710 | |
Sanjay Patel | 7181146 | 2018-10-14 15:25:06 +0000 | [diff] [blame] | 1711 | /// Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask. |
| 1712 | static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) { |
| 1713 | Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1); |
| 1714 | if (!Shuf.isIdentityWithExtract() || !isa<UndefValue>(Op1)) |
| 1715 | return nullptr; |
| 1716 | |
| 1717 | Value *X, *Y; |
| 1718 | Constant *Mask; |
| 1719 | if (!match(Op0, m_ShuffleVector(m_Value(X), m_Value(Y), m_Constant(Mask)))) |
| 1720 | return nullptr; |
| 1721 | |
Sanjay Patel | cddb1e5 | 2019-02-05 22:58:45 +0000 | [diff] [blame] | 1722 | // Be conservative with shuffle transforms. If we can't kill the 1st shuffle, |
| 1723 | // then combining may result in worse codegen. |
| 1724 | if (!Op0->hasOneUse()) |
| 1725 | return nullptr; |
| 1726 | |
Sanjay Patel | 7181146 | 2018-10-14 15:25:06 +0000 | [diff] [blame] | 1727 | // We are extracting a subvector from a shuffle. Remove excess elements from |
| 1728 | // the 1st shuffle mask to eliminate the extract. |
| 1729 | // |
| 1730 | // This transform is conservatively limited to identity extracts because we do |
| 1731 | // not allow arbitrary shuffle mask creation as a target-independent transform |
| 1732 | // (because we can't guarantee that will lower efficiently). |
| 1733 | // |
| 1734 | // If the extracting shuffle has an undef mask element, it transfers to the |
| 1735 | // new shuffle mask. Otherwise, copy the original mask element. Example: |
| 1736 | // shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> --> |
| 1737 | // shuf X, Y, <C0, undef, C2, undef> |
| 1738 | unsigned NumElts = Shuf.getType()->getVectorNumElements(); |
| 1739 | SmallVector<Constant *, 16> NewMask(NumElts); |
| 1740 | assert(NumElts < Mask->getType()->getVectorNumElements() && |
| 1741 | "Identity with extract must have less elements than its inputs"); |
| 1742 | |
| 1743 | for (unsigned i = 0; i != NumElts; ++i) { |
| 1744 | Constant *ExtractMaskElt = Shuf.getMask()->getAggregateElement(i); |
| 1745 | Constant *MaskElt = Mask->getAggregateElement(i); |
| 1746 | NewMask[i] = isa<UndefValue>(ExtractMaskElt) ? ExtractMaskElt : MaskElt; |
| 1747 | } |
| 1748 | return new ShuffleVectorInst(X, Y, ConstantVector::get(NewMask)); |
| 1749 | } |
| 1750 | |
Sanjay Patel | 396d18a | 2019-12-10 10:10:05 -0500 | [diff] [blame] | 1751 | /// Try to replace a shuffle with an insertelement or try to replace a shuffle |
| 1752 | /// operand with the operand of an insertelement. |
Nikita Popov | 5a8819b | 2020-02-03 21:17:36 +0100 | [diff] [blame] | 1753 | static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf, |
| 1754 | InstCombiner &IC) { |
Sanjay Patel | b12e410 | 2018-10-30 15:26:39 +0000 | [diff] [blame] | 1755 | Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1); |
| 1756 | SmallVector<int, 16> Mask = Shuf.getShuffleMask(); |
| 1757 | |
| 1758 | // The shuffle must not change vector sizes. |
| 1759 | // TODO: This restriction could be removed if the insert has only one use |
| 1760 | // (because the transform would require a new length-changing shuffle). |
| 1761 | int NumElts = Mask.size(); |
| 1762 | if (NumElts != (int)(V0->getType()->getVectorNumElements())) |
| 1763 | return nullptr; |
| 1764 | |
Sanjay Patel | 396d18a | 2019-12-10 10:10:05 -0500 | [diff] [blame] | 1765 | // This is a specialization of a fold in SimplifyDemandedVectorElts. We may |
| 1766 | // not be able to handle it there if the insertelement has >1 use. |
| 1767 | // If the shuffle has an insertelement operand but does not choose the |
| 1768 | // inserted scalar element from that value, then we can replace that shuffle |
| 1769 | // operand with the source vector of the insertelement. |
| 1770 | Value *X; |
| 1771 | uint64_t IdxC; |
| 1772 | if (match(V0, m_InsertElement(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) { |
| 1773 | // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask |
Nikita Popov | 5a8819b | 2020-02-03 21:17:36 +0100 | [diff] [blame] | 1774 | if (none_of(Mask, [IdxC](int MaskElt) { return MaskElt == (int)IdxC; })) |
| 1775 | return IC.replaceOperand(Shuf, 0, X); |
Sanjay Patel | 396d18a | 2019-12-10 10:10:05 -0500 | [diff] [blame] | 1776 | } |
| 1777 | if (match(V1, m_InsertElement(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) { |
| 1778 | // Offset the index constant by the vector width because we are checking for |
| 1779 | // accesses to the 2nd vector input of the shuffle. |
| 1780 | IdxC += NumElts; |
| 1781 | // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask |
Nikita Popov | 5a8819b | 2020-02-03 21:17:36 +0100 | [diff] [blame] | 1782 | if (none_of(Mask, [IdxC](int MaskElt) { return MaskElt == (int)IdxC; })) |
| 1783 | return IC.replaceOperand(Shuf, 1, X); |
Sanjay Patel | 396d18a | 2019-12-10 10:10:05 -0500 | [diff] [blame] | 1784 | } |
| 1785 | |
Sanjay Patel | b12e410 | 2018-10-30 15:26:39 +0000 | [diff] [blame] | 1786 | // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC' |
| 1787 | auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) { |
| 1788 | // We need an insertelement with a constant index. |
| 1789 | if (!match(V0, m_InsertElement(m_Value(), m_Value(Scalar), |
| 1790 | m_ConstantInt(IndexC)))) |
| 1791 | return false; |
| 1792 | |
| 1793 | // Test the shuffle mask to see if it splices the inserted scalar into the |
| 1794 | // operand 1 vector of the shuffle. |
| 1795 | int NewInsIndex = -1; |
| 1796 | for (int i = 0; i != NumElts; ++i) { |
| 1797 | // Ignore undef mask elements. |
| 1798 | if (Mask[i] == -1) |
| 1799 | continue; |
| 1800 | |
| 1801 | // The shuffle takes elements of operand 1 without lane changes. |
| 1802 | if (Mask[i] == NumElts + i) |
| 1803 | continue; |
| 1804 | |
| 1805 | // The shuffle must choose the inserted scalar exactly once. |
| 1806 | if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue()) |
| 1807 | return false; |
| 1808 | |
| 1809 | // The shuffle is placing the inserted scalar into element i. |
| 1810 | NewInsIndex = i; |
| 1811 | } |
| 1812 | |
| 1813 | assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?"); |
| 1814 | |
| 1815 | // Index is updated to the potentially translated insertion lane. |
| 1816 | IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex); |
| 1817 | return true; |
| 1818 | }; |
| 1819 | |
| 1820 | // If the shuffle is unnecessary, insert the scalar operand directly into |
| 1821 | // operand 1 of the shuffle. Example: |
| 1822 | // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0 |
| 1823 | Value *Scalar; |
| 1824 | ConstantInt *IndexC; |
| 1825 | if (isShufflingScalarIntoOp1(Scalar, IndexC)) |
| 1826 | return InsertElementInst::Create(V1, Scalar, IndexC); |
| 1827 | |
| 1828 | // Try again after commuting shuffle. Example: |
| 1829 | // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> --> |
| 1830 | // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3 |
| 1831 | std::swap(V0, V1); |
| 1832 | ShuffleVectorInst::commuteShuffleMask(Mask, NumElts); |
| 1833 | if (isShufflingScalarIntoOp1(Scalar, IndexC)) |
| 1834 | return InsertElementInst::Create(V1, Scalar, IndexC); |
| 1835 | |
| 1836 | return nullptr; |
| 1837 | } |
| 1838 | |
Sanjay Patel | 6a55418 | 2019-05-22 00:32:25 +0000 | [diff] [blame] | 1839 | static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) { |
| 1840 | // Match the operands as identity with padding (also known as concatenation |
| 1841 | // with undef) shuffles of the same source type. The backend is expected to |
| 1842 | // recreate these concatenations from a shuffle of narrow operands. |
| 1843 | auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0)); |
| 1844 | auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1)); |
| 1845 | if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() || |
| 1846 | !Shuffle1 || !Shuffle1->isIdentityWithPadding()) |
| 1847 | return nullptr; |
| 1848 | |
| 1849 | // We limit this transform to power-of-2 types because we expect that the |
| 1850 | // backend can convert the simplified IR patterns to identical nodes as the |
| 1851 | // original IR. |
Sanjay Patel | 3249be1 | 2019-05-23 18:46:03 +0000 | [diff] [blame] | 1852 | // TODO: If we can verify the same behavior for arbitrary types, the |
| 1853 | // power-of-2 checks can be removed. |
Sanjay Patel | 6a55418 | 2019-05-22 00:32:25 +0000 | [diff] [blame] | 1854 | Value *X = Shuffle0->getOperand(0); |
| 1855 | Value *Y = Shuffle1->getOperand(0); |
| 1856 | if (X->getType() != Y->getType() || |
| 1857 | !isPowerOf2_32(Shuf.getType()->getVectorNumElements()) || |
| 1858 | !isPowerOf2_32(Shuffle0->getType()->getVectorNumElements()) || |
| 1859 | !isPowerOf2_32(X->getType()->getVectorNumElements()) || |
| 1860 | isa<UndefValue>(X) || isa<UndefValue>(Y)) |
| 1861 | return nullptr; |
| 1862 | assert(isa<UndefValue>(Shuffle0->getOperand(1)) && |
| 1863 | isa<UndefValue>(Shuffle1->getOperand(1)) && |
| 1864 | "Unexpected operand for identity shuffle"); |
| 1865 | |
| 1866 | // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source |
| 1867 | // operands directly by adjusting the shuffle mask to account for the narrower |
| 1868 | // types: |
| 1869 | // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask' |
| 1870 | int NarrowElts = X->getType()->getVectorNumElements(); |
| 1871 | int WideElts = Shuffle0->getType()->getVectorNumElements(); |
| 1872 | assert(WideElts > NarrowElts && "Unexpected types for identity with padding"); |
| 1873 | |
| 1874 | Type *I32Ty = IntegerType::getInt32Ty(Shuf.getContext()); |
| 1875 | SmallVector<int, 16> Mask = Shuf.getShuffleMask(); |
| 1876 | SmallVector<Constant *, 16> NewMask(Mask.size(), UndefValue::get(I32Ty)); |
| 1877 | for (int i = 0, e = Mask.size(); i != e; ++i) { |
| 1878 | if (Mask[i] == -1) |
| 1879 | continue; |
Sanjay Patel | 3249be1 | 2019-05-23 18:46:03 +0000 | [diff] [blame] | 1880 | |
| 1881 | // If this shuffle is choosing an undef element from 1 of the sources, that |
| 1882 | // element is undef. |
| 1883 | if (Mask[i] < WideElts) { |
| 1884 | if (Shuffle0->getMaskValue(Mask[i]) == -1) |
| 1885 | continue; |
| 1886 | } else { |
| 1887 | if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1) |
| 1888 | continue; |
| 1889 | } |
| 1890 | |
| 1891 | // If this shuffle is choosing from the 1st narrow op, the mask element is |
| 1892 | // the same. If this shuffle is choosing from the 2nd narrow op, the mask |
| 1893 | // element is offset down to adjust for the narrow vector widths. |
| 1894 | if (Mask[i] < WideElts) { |
| 1895 | assert(Mask[i] < NarrowElts && "Unexpected shuffle mask"); |
Sanjay Patel | 6a55418 | 2019-05-22 00:32:25 +0000 | [diff] [blame] | 1896 | NewMask[i] = ConstantInt::get(I32Ty, Mask[i]); |
Sanjay Patel | 3249be1 | 2019-05-23 18:46:03 +0000 | [diff] [blame] | 1897 | } else { |
| 1898 | assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask"); |
Sanjay Patel | 6a55418 | 2019-05-22 00:32:25 +0000 | [diff] [blame] | 1899 | NewMask[i] = ConstantInt::get(I32Ty, Mask[i] - (WideElts - NarrowElts)); |
Sanjay Patel | 3249be1 | 2019-05-23 18:46:03 +0000 | [diff] [blame] | 1900 | } |
Sanjay Patel | 6a55418 | 2019-05-22 00:32:25 +0000 | [diff] [blame] | 1901 | } |
| 1902 | return new ShuffleVectorInst(X, Y, ConstantVector::get(NewMask)); |
| 1903 | } |
| 1904 | |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1905 | Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) { |
| 1906 | Value *LHS = SVI.getOperand(0); |
| 1907 | Value *RHS = SVI.getOperand(1); |
Craig Topper | a420562 | 2017-06-09 03:21:29 +0000 | [diff] [blame] | 1908 | if (auto *V = SimplifyShuffleVectorInst( |
| 1909 | LHS, RHS, SVI.getMask(), SVI.getType(), SQ.getWithInstruction(&SVI))) |
Zvi Rackover | 82bf48d | 2017-04-04 04:47:57 +0000 | [diff] [blame] | 1910 | return replaceInstUsesWith(SVI, V); |
| 1911 | |
Sanjay Patel | 3582716 | 2019-11-25 13:30:45 -0500 | [diff] [blame] | 1912 | // shuffle x, x, mask --> shuffle x, undef, mask' |
Sanjay Patel | 3f4d1b4 | 2019-03-29 16:49:38 +0000 | [diff] [blame] | 1913 | unsigned VWidth = SVI.getType()->getVectorNumElements(); |
| 1914 | unsigned LHSWidth = LHS->getType()->getVectorNumElements(); |
| 1915 | SmallVector<int, 16> Mask = SVI.getShuffleMask(); |
| 1916 | Type *Int32Ty = Type::getInt32Ty(SVI.getContext()); |
Sanjay Patel | 3582716 | 2019-11-25 13:30:45 -0500 | [diff] [blame] | 1917 | if (LHS == RHS) { |
Sanjay Patel | 847aabf | 2019-11-25 10:54:18 -0500 | [diff] [blame] | 1918 | assert(!isa<UndefValue>(RHS) && "Shuffle with 2 undef ops not simplified?"); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1919 | // Remap any references to RHS to use LHS. |
Chris Lattner | 0256be9 | 2012-01-27 03:08:05 +0000 | [diff] [blame] | 1920 | SmallVector<Constant*, 16> Elts; |
Sanjay Patel | 2068409 | 2019-11-25 10:40:21 -0500 | [diff] [blame] | 1921 | for (unsigned i = 0; i != VWidth; ++i) { |
Sanjay Patel | 3582716 | 2019-11-25 13:30:45 -0500 | [diff] [blame] | 1922 | // Propagate undef elements or force mask to LHS. |
| 1923 | if (Mask[i] < 0) |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 1924 | Elts.push_back(UndefValue::get(Int32Ty)); |
Sanjay Patel | fc31b58 | 2019-11-25 11:11:12 -0500 | [diff] [blame] | 1925 | else |
| 1926 | Elts.push_back(ConstantInt::get(Int32Ty, Mask[i] % LHSWidth)); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1927 | } |
Nikita Popov | d4627b9 | 2020-02-08 17:02:10 +0100 | [diff] [blame] | 1928 | return new ShuffleVectorInst(LHS, UndefValue::get(RHS->getType()), |
| 1929 | ConstantVector::get(Elts)); |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 1930 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 1931 | |
Sanjay Patel | 3582716 | 2019-11-25 13:30:45 -0500 | [diff] [blame] | 1932 | // shuffle undef, x, mask --> shuffle x, undef, mask' |
| 1933 | if (isa<UndefValue>(LHS)) { |
| 1934 | SVI.commute(); |
| 1935 | return &SVI; |
| 1936 | } |
| 1937 | |
Sanjay Patel | 0b59103 | 2019-07-08 16:26:48 +0000 | [diff] [blame] | 1938 | if (Instruction *I = canonicalizeInsertSplat(SVI, Builder)) |
| 1939 | return I; |
| 1940 | |
Sanjay Patel | 3f4d1b4 | 2019-03-29 16:49:38 +0000 | [diff] [blame] | 1941 | if (Instruction *I = foldSelectShuffle(SVI, Builder, DL)) |
| 1942 | return I; |
| 1943 | |
| 1944 | if (Instruction *I = narrowVectorSelect(SVI, Builder)) |
| 1945 | return I; |
| 1946 | |
| 1947 | APInt UndefElts(VWidth, 0); |
| 1948 | APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); |
| 1949 | if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { |
| 1950 | if (V != &SVI) |
| 1951 | return replaceInstUsesWith(SVI, V); |
| 1952 | return &SVI; |
| 1953 | } |
| 1954 | |
| 1955 | if (Instruction *I = foldIdentityExtractShuffle(SVI)) |
| 1956 | return I; |
| 1957 | |
Sanjay Patel | 6a55418 | 2019-05-22 00:32:25 +0000 | [diff] [blame] | 1958 | // These transforms have the potential to lose undef knowledge, so they are |
Sanjay Patel | 3f4d1b4 | 2019-03-29 16:49:38 +0000 | [diff] [blame] | 1959 | // intentionally placed after SimplifyDemandedVectorElts(). |
Nikita Popov | 5a8819b | 2020-02-03 21:17:36 +0100 | [diff] [blame] | 1960 | if (Instruction *I = foldShuffleWithInsert(SVI, *this)) |
Sanjay Patel | 3f4d1b4 | 2019-03-29 16:49:38 +0000 | [diff] [blame] | 1961 | return I; |
Sanjay Patel | 6a55418 | 2019-05-22 00:32:25 +0000 | [diff] [blame] | 1962 | if (Instruction *I = foldIdentityPaddedShuffles(SVI)) |
| 1963 | return I; |
Sanjay Patel | 3f4d1b4 | 2019-03-29 16:49:38 +0000 | [diff] [blame] | 1964 | |
Sanjay Patel | 26c119a | 2018-09-30 13:50:42 +0000 | [diff] [blame] | 1965 | if (isa<UndefValue>(RHS) && canEvaluateShuffled(LHS, Mask)) { |
Sanjay Patel | 54d31ef | 2018-09-29 15:05:24 +0000 | [diff] [blame] | 1966 | Value *V = evaluateInDifferentElementOrder(LHS, Mask); |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 1967 | return replaceInstUsesWith(SVI, V); |
Nick Lewycky | a2b7720 | 2013-05-31 00:59:42 +0000 | [diff] [blame] | 1968 | } |
| 1969 | |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 1970 | // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to |
| 1971 | // a non-vector type. We can instead bitcast the original vector followed by |
| 1972 | // an extract of the desired element: |
| 1973 | // |
| 1974 | // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef, |
| 1975 | // <4 x i32> <i32 0, i32 1, i32 2, i32 3> |
| 1976 | // %1 = bitcast <4 x i8> %sroa to i32 |
| 1977 | // Becomes: |
| 1978 | // %bc = bitcast <16 x i8> %in to <4 x i32> |
| 1979 | // %ext = extractelement <4 x i32> %bc, i32 0 |
| 1980 | // |
| 1981 | // If the shuffle is extracting a contiguous range of values from the input |
| 1982 | // vector then each use which is a bitcast of the extracted size can be |
| 1983 | // replaced. This will work if the vector types are compatible, and the begin |
| 1984 | // index is aligned to a value in the casted vector type. If the begin index |
| 1985 | // isn't aligned then we can shuffle the original vector (keeping the same |
| 1986 | // vector type) before extracting. |
| 1987 | // |
| 1988 | // This code will bail out if the target type is fundamentally incompatible |
| 1989 | // with vectors of the source type. |
| 1990 | // |
| 1991 | // Example of <16 x i8>, target type i32: |
| 1992 | // Index range [4,8): v-----------v Will work. |
| 1993 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |
| 1994 | // <16 x i8>: | | | | | | | | | | | | | | | | | |
| 1995 | // <4 x i32>: | | | | | |
| 1996 | // +-----------+-----------+-----------+-----------+ |
| 1997 | // Index range [6,10): ^-----------^ Needs an extra shuffle. |
| 1998 | // Target type i40: ^--------------^ Won't work, bail. |
Sanjay Patel | 3f4d1b4 | 2019-03-29 16:49:38 +0000 | [diff] [blame] | 1999 | bool MadeChange = false; |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 2000 | if (isShuffleExtractingFromLHS(SVI, Mask)) { |
| 2001 | Value *V = LHS; |
| 2002 | unsigned MaskElems = Mask.size(); |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 2003 | VectorType *SrcTy = cast<VectorType>(V->getType()); |
| 2004 | unsigned VecBitWidth = SrcTy->getBitWidth(); |
David Majnemer | 98cfe2b | 2015-04-03 20:18:40 +0000 | [diff] [blame] | 2005 | unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType()); |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 2006 | assert(SrcElemBitWidth && "vector elements must have a bitwidth"); |
| 2007 | unsigned SrcNumElems = SrcTy->getNumElements(); |
| 2008 | SmallVector<BitCastInst *, 8> BCs; |
| 2009 | DenseMap<Type *, Value *> NewBCs; |
| 2010 | for (User *U : SVI.users()) |
| 2011 | if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) |
| 2012 | if (!BC->use_empty()) |
| 2013 | // Only visit bitcasts that weren't previously handled. |
| 2014 | BCs.push_back(BC); |
| 2015 | for (BitCastInst *BC : BCs) { |
Eugene Leviant | 958fcd7 | 2017-02-17 07:36:03 +0000 | [diff] [blame] | 2016 | unsigned BegIdx = Mask.front(); |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 2017 | Type *TgtTy = BC->getDestTy(); |
David Majnemer | 98cfe2b | 2015-04-03 20:18:40 +0000 | [diff] [blame] | 2018 | unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy); |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 2019 | if (!TgtElemBitWidth) |
| 2020 | continue; |
| 2021 | unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth; |
| 2022 | bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth; |
| 2023 | bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth); |
| 2024 | if (!VecBitWidthsEqual) |
| 2025 | continue; |
| 2026 | if (!VectorType::isValidElementType(TgtTy)) |
| 2027 | continue; |
| 2028 | VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems); |
| 2029 | if (!BegIsAligned) { |
| 2030 | // Shuffle the input so [0,NumElements) contains the output, and |
| 2031 | // [NumElems,SrcNumElems) is undef. |
| 2032 | SmallVector<Constant *, 16> ShuffleMask(SrcNumElems, |
| 2033 | UndefValue::get(Int32Ty)); |
| 2034 | for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I) |
| 2035 | ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx); |
Craig Topper | bb4069e | 2017-07-07 23:16:26 +0000 | [diff] [blame] | 2036 | V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()), |
| 2037 | ConstantVector::get(ShuffleMask), |
| 2038 | SVI.getName() + ".extract"); |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 2039 | BegIdx = 0; |
| 2040 | } |
| 2041 | unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth; |
| 2042 | assert(SrcElemsPerTgtElem); |
| 2043 | BegIdx /= SrcElemsPerTgtElem; |
| 2044 | bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end(); |
| 2045 | auto *NewBC = |
| 2046 | BCAlreadyExists |
| 2047 | ? NewBCs[CastSrcTy] |
Craig Topper | bb4069e | 2017-07-07 23:16:26 +0000 | [diff] [blame] | 2048 | : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc"); |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 2049 | if (!BCAlreadyExists) |
| 2050 | NewBCs[CastSrcTy] = NewBC; |
Craig Topper | bb4069e | 2017-07-07 23:16:26 +0000 | [diff] [blame] | 2051 | auto *Ext = Builder.CreateExtractElement( |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 2052 | NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract"); |
| 2053 | // The shufflevector isn't being replaced: the bitcast that used it |
| 2054 | // is. InstCombine will visit the newly-created instructions. |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 2055 | replaceInstUsesWith(*BC, Ext); |
JF Bastien | d52c990 | 2015-02-25 22:30:51 +0000 | [diff] [blame] | 2056 | MadeChange = true; |
| 2057 | } |
| 2058 | } |
| 2059 | |
Eric Christopher | 51edc7b | 2010-08-17 22:55:27 +0000 | [diff] [blame] | 2060 | // If the LHS is a shufflevector itself, see if we can combine it with this |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2061 | // one without producing an unusual shuffle. |
| 2062 | // Cases that might be simplified: |
| 2063 | // 1. |
| 2064 | // x1=shuffle(v1,v2,mask1) |
| 2065 | // x=shuffle(x1,undef,mask) |
| 2066 | // ==> |
| 2067 | // x=shuffle(v1,undef,newMask) |
| 2068 | // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1 |
| 2069 | // 2. |
| 2070 | // x1=shuffle(v1,undef,mask1) |
| 2071 | // x=shuffle(x1,x2,mask) |
| 2072 | // where v1.size() == mask1.size() |
| 2073 | // ==> |
| 2074 | // x=shuffle(v1,x2,newMask) |
| 2075 | // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i] |
| 2076 | // 3. |
| 2077 | // x2=shuffle(v2,undef,mask2) |
| 2078 | // x=shuffle(x1,x2,mask) |
| 2079 | // where v2.size() == mask2.size() |
| 2080 | // ==> |
| 2081 | // x=shuffle(x1,v2,newMask) |
| 2082 | // newMask[i] = (mask[i] < x1.size()) |
| 2083 | // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size() |
| 2084 | // 4. |
| 2085 | // x1=shuffle(v1,undef,mask1) |
| 2086 | // x2=shuffle(v2,undef,mask2) |
| 2087 | // x=shuffle(x1,x2,mask) |
| 2088 | // where v1.size() == v2.size() |
| 2089 | // ==> |
| 2090 | // x=shuffle(v1,v2,newMask) |
| 2091 | // newMask[i] = (mask[i] < x1.size()) |
| 2092 | // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size() |
| 2093 | // |
| 2094 | // Here we are really conservative: |
Eric Christopher | 51edc7b | 2010-08-17 22:55:27 +0000 | [diff] [blame] | 2095 | // we are absolutely afraid of producing a shuffle mask not in the input |
| 2096 | // program, because the code gen may not be smart enough to turn a merged |
| 2097 | // shuffle into two specific shuffles: it may produce worse code. As such, |
Jim Grosbach | d11584a | 2013-05-01 00:25:27 +0000 | [diff] [blame] | 2098 | // we only merge two shuffles if the result is either a splat or one of the |
| 2099 | // input shuffle masks. In this case, merging the shuffles just removes |
| 2100 | // one instruction, which we know is safe. This is good for things like |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2101 | // turning: (splat(splat)) -> splat, or |
| 2102 | // merge(V[0..n], V[n+1..2n]) -> V[0..2n] |
| 2103 | ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS); |
| 2104 | ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS); |
| 2105 | if (LHSShuffle) |
| 2106 | if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2107 | LHSShuffle = nullptr; |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2108 | if (RHSShuffle) |
| 2109 | if (!isa<UndefValue>(RHSShuffle->getOperand(1))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2110 | RHSShuffle = nullptr; |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2111 | if (!LHSShuffle && !RHSShuffle) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2112 | return MadeChange ? &SVI : nullptr; |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2113 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2114 | Value* LHSOp0 = nullptr; |
| 2115 | Value* LHSOp1 = nullptr; |
| 2116 | Value* RHSOp0 = nullptr; |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2117 | unsigned LHSOp0Width = 0; |
| 2118 | unsigned RHSOp0Width = 0; |
| 2119 | if (LHSShuffle) { |
| 2120 | LHSOp0 = LHSShuffle->getOperand(0); |
| 2121 | LHSOp1 = LHSShuffle->getOperand(1); |
Craig Topper | 17b5568 | 2016-12-29 07:03:18 +0000 | [diff] [blame] | 2122 | LHSOp0Width = LHSOp0->getType()->getVectorNumElements(); |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2123 | } |
| 2124 | if (RHSShuffle) { |
| 2125 | RHSOp0 = RHSShuffle->getOperand(0); |
Craig Topper | 17b5568 | 2016-12-29 07:03:18 +0000 | [diff] [blame] | 2126 | RHSOp0Width = RHSOp0->getType()->getVectorNumElements(); |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2127 | } |
| 2128 | Value* newLHS = LHS; |
| 2129 | Value* newRHS = RHS; |
| 2130 | if (LHSShuffle) { |
| 2131 | // case 1 |
Eric Christopher | 51edc7b | 2010-08-17 22:55:27 +0000 | [diff] [blame] | 2132 | if (isa<UndefValue>(RHS)) { |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2133 | newLHS = LHSOp0; |
| 2134 | newRHS = LHSOp1; |
| 2135 | } |
| 2136 | // case 2 or 4 |
| 2137 | else if (LHSOp0Width == LHSWidth) { |
| 2138 | newLHS = LHSOp0; |
| 2139 | } |
| 2140 | } |
| 2141 | // case 3 or 4 |
| 2142 | if (RHSShuffle && RHSOp0Width == LHSWidth) { |
| 2143 | newRHS = RHSOp0; |
| 2144 | } |
| 2145 | // case 4 |
| 2146 | if (LHSOp0 == RHSOp0) { |
| 2147 | newLHS = LHSOp0; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2148 | newRHS = nullptr; |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2149 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 2150 | |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2151 | if (newLHS == LHS && newRHS == RHS) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2152 | return MadeChange ? &SVI : nullptr; |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 2153 | |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2154 | SmallVector<int, 16> LHSMask; |
| 2155 | SmallVector<int, 16> RHSMask; |
Chris Lattner | 8326bd8 | 2012-01-26 00:42:34 +0000 | [diff] [blame] | 2156 | if (newLHS != LHS) |
| 2157 | LHSMask = LHSShuffle->getShuffleMask(); |
| 2158 | if (RHSShuffle && newRHS != RHS) |
| 2159 | RHSMask = RHSShuffle->getShuffleMask(); |
| 2160 | |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2161 | unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth; |
| 2162 | SmallVector<int, 16> newMask; |
| 2163 | bool isSplat = true; |
| 2164 | int SplatElt = -1; |
| 2165 | // Create a new mask for the new ShuffleVectorInst so that the new |
| 2166 | // ShuffleVectorInst is equivalent to the original one. |
| 2167 | for (unsigned i = 0; i < VWidth; ++i) { |
| 2168 | int eltMask; |
Craig Topper | 45d9f4b | 2013-01-18 05:30:07 +0000 | [diff] [blame] | 2169 | if (Mask[i] < 0) { |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2170 | // This element is an undef value. |
| 2171 | eltMask = -1; |
| 2172 | } else if (Mask[i] < (int)LHSWidth) { |
| 2173 | // This element is from left hand side vector operand. |
Craig Topper | 2ea22b0 | 2013-01-18 05:09:16 +0000 | [diff] [blame] | 2174 | // |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2175 | // If LHS is going to be replaced (case 1, 2, or 4), calculate the |
| 2176 | // new mask value for the element. |
| 2177 | if (newLHS != LHS) { |
| 2178 | eltMask = LHSMask[Mask[i]]; |
| 2179 | // If the value selected is an undef value, explicitly specify it |
| 2180 | // with a -1 mask value. |
| 2181 | if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1)) |
| 2182 | eltMask = -1; |
Craig Topper | 2ea22b0 | 2013-01-18 05:09:16 +0000 | [diff] [blame] | 2183 | } else |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2184 | eltMask = Mask[i]; |
| 2185 | } else { |
| 2186 | // This element is from right hand side vector operand |
| 2187 | // |
| 2188 | // If the value selected is an undef value, explicitly specify it |
| 2189 | // with a -1 mask value. (case 1) |
| 2190 | if (isa<UndefValue>(RHS)) |
| 2191 | eltMask = -1; |
| 2192 | // If RHS is going to be replaced (case 3 or 4), calculate the |
| 2193 | // new mask value for the element. |
| 2194 | else if (newRHS != RHS) { |
| 2195 | eltMask = RHSMask[Mask[i]-LHSWidth]; |
| 2196 | // If the value selected is an undef value, explicitly specify it |
| 2197 | // with a -1 mask value. |
| 2198 | if (eltMask >= (int)RHSOp0Width) { |
| 2199 | assert(isa<UndefValue>(RHSShuffle->getOperand(1)) |
| 2200 | && "should have been check above"); |
| 2201 | eltMask = -1; |
Nate Begeman | 2a0ca3e9 | 2010-08-13 00:17:53 +0000 | [diff] [blame] | 2202 | } |
Craig Topper | 2ea22b0 | 2013-01-18 05:09:16 +0000 | [diff] [blame] | 2203 | } else |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2204 | eltMask = Mask[i]-LHSWidth; |
| 2205 | |
| 2206 | // If LHS's width is changed, shift the mask value accordingly. |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 2207 | // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any |
Michael Gottesman | 02a1141 | 2012-10-16 21:29:38 +0000 | [diff] [blame] | 2208 | // references from RHSOp0 to LHSOp0, so we don't need to shift the mask. |
| 2209 | // If newRHS == newLHS, we want to remap any references from newRHS to |
| 2210 | // newLHS so that we can properly identify splats that may occur due to |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 2211 | // obfuscation across the two vectors. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2212 | if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS) |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2213 | eltMask += newLHSWidth; |
Nate Begeman | 2a0ca3e9 | 2010-08-13 00:17:53 +0000 | [diff] [blame] | 2214 | } |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2215 | |
| 2216 | // Check if this could still be a splat. |
| 2217 | if (eltMask >= 0) { |
| 2218 | if (SplatElt >= 0 && SplatElt != eltMask) |
| 2219 | isSplat = false; |
| 2220 | SplatElt = eltMask; |
| 2221 | } |
| 2222 | |
| 2223 | newMask.push_back(eltMask); |
| 2224 | } |
| 2225 | |
| 2226 | // If the result mask is equal to one of the original shuffle masks, |
Jim Grosbach | d11584a | 2013-05-01 00:25:27 +0000 | [diff] [blame] | 2227 | // or is a splat, do the replacement. |
| 2228 | if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) { |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2229 | SmallVector<Constant*, 16> Elts; |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2230 | for (unsigned i = 0, e = newMask.size(); i != e; ++i) { |
| 2231 | if (newMask[i] < 0) { |
| 2232 | Elts.push_back(UndefValue::get(Int32Ty)); |
| 2233 | } else { |
| 2234 | Elts.push_back(ConstantInt::get(Int32Ty, newMask[i])); |
| 2235 | } |
| 2236 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2237 | if (!newRHS) |
Eli Friedman | ce81827 | 2011-10-21 19:06:29 +0000 | [diff] [blame] | 2238 | newRHS = UndefValue::get(newLHS->getType()); |
| 2239 | return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts)); |
Nate Begeman | 2a0ca3e9 | 2010-08-13 00:17:53 +0000 | [diff] [blame] | 2240 | } |
Bob Wilson | 8ecf98b | 2010-10-29 22:20:43 +0000 | [diff] [blame] | 2241 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2242 | return MadeChange ? &SVI : nullptr; |
Chris Lattner | ec97a90 | 2010-01-05 05:36:20 +0000 | [diff] [blame] | 2243 | } |