LLVM 24.0.0git
InstCombineVectorOps.cpp
Go to the documentation of this file.
1//===- InstCombineVectorOps.cpp -------------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements instcombine for ExtractElement, InsertElement and
10// ShuffleVector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/Statistic.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/Constant.h"
26#include "llvm/IR/Constants.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
31#include "llvm/IR/Operator.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/User.h"
35#include "llvm/IR/Value.h"
39#include <cassert>
40#include <cstdint>
41#include <iterator>
42#include <utility>
43
44#define DEBUG_TYPE "instcombine"
45
46using namespace llvm;
47using namespace PatternMatch;
48
49STATISTIC(NumAggregateReconstructionsSimplified,
50 "Number of aggregate reconstructions turned into reuse of the "
51 "original aggregate");
52
53/// Return true if the value is cheaper to scalarize than it is to leave as a
54/// vector operation. If the extract index \p EI is a constant integer then
55/// some operations may be cheap to scalarize.
56///
57/// FIXME: It's possible to create more instructions than previously existed.
58static bool cheapToScalarize(Value *V, Value *EI) {
60
61 // If we can pick a scalar constant value out of a vector, that is free.
62 if (auto *C = dyn_cast<Constant>(V))
63 return CEI || C->getSplatValue();
64
66 ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
67 // Index needs to be lower than the minimum size of the vector, because
68 // for scalable vector, the vector size is known at run time.
69 return CEI->getValue().ult(EC.getKnownMinValue());
70 }
71
72 // An insertelement to the same constant index as our extract will simplify
73 // to the scalar inserted element. An insertelement to a different constant
74 // index is irrelevant to our extract.
76 return CEI;
77
78 if (match(V, m_OneUse(m_Load(m_Value()))))
79 return true;
80
81 if (match(V, m_OneUse(m_UnOp())))
82 return true;
83
84 Value *V0, *V1;
85 if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
86 if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
87 return true;
88
89 CmpPredicate UnusedPred;
90 if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
91 if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
92 return true;
93
94 return false;
95}
96
97// If we have a PHI node with a vector type that is only used to feed
98// itself and be an operand of extractelement at a constant location,
99// try to replace the PHI of the vector type with a PHI of a scalar type.
100Instruction *InstCombinerImpl::scalarizePHI(ExtractElementInst &EI,
101 PHINode *PN) {
102 SmallVector<Instruction *, 2> Extracts;
103 // The users we want the PHI to have are:
104 // 1) The EI ExtractElement (we already know this)
105 // 2) Possibly more ExtractElements with the same index.
106 // 3) Another operand, which will feed back into the PHI.
107 Instruction *PHIUser = nullptr;
108 for (Instruction *U : PN->users()) {
109 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
110 if (EI.getIndexOperand() == EU->getIndexOperand())
111 Extracts.push_back(EU);
112 else
113 return nullptr;
114 } else if (!PHIUser) {
115 PHIUser = U;
116 } else {
117 return nullptr;
118 }
119 }
120
121 if (!PHIUser)
122 return nullptr;
123
124 // Verify that this PHI user has one use, which is the PHI itself,
125 // and that it is a binary operation which is cheap to scalarize.
126 // otherwise return nullptr.
127 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
128 !(isa<BinaryOperator>(PHIUser)) ||
129 !cheapToScalarize(PHIUser, EI.getIndexOperand()))
130 return nullptr;
131
132 // An incoming value defined by the terminator (invoke, callbr) of its
133 // incoming block is not available anywhere in that block, so there is no
134 // place to extract from it.
135 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I)
137 return nullptr;
138
139 // Create a scalar PHI node that will replace the vector PHI node
140 // just before the current PHI node.
141 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
143 // Scalarize each PHI operand. A switch may produce multiple edges from the
144 // same predecessor; reuse the scalar instruction for duplicate edges.
145 SmallDenseMap<BasicBlock *, Value *, 4> ScalarizedValues;
146 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
147 Value *PHIInVal = PN->getIncomingValue(i);
148 BasicBlock *inBB = PN->getIncomingBlock(i);
149 Value *Elt = EI.getIndexOperand();
150
151 // Reuse scalar value for duplicate edges from the same predecessor.
152 if (Value *Existing = ScalarizedValues.lookup(inBB)) {
153 scalarPHI->addIncoming(Existing, inBB);
154 continue;
155 }
156
157 Value *ScalarVal;
158 // If the operand is the PHI induction variable:
159 if (PHIInVal == PHIUser) {
160 // Scalarize the binary operation. One operand is the
161 // scalar PHI, and the other is extracted from the other
162 // vector operand.
163 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
164 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
166 ExtractElementInst::Create(B0->getOperand(opId), Elt,
167 B0->getOperand(opId)->getName() + ".Elt"),
168 B0->getIterator());
169 // Preserve operand order for binary operation to preserve semantics of
170 // non-commutative operations.
171 Value *FirstOp = (B0->getOperand(0) == PN) ? scalarPHI : Op;
172 Value *SecondOp = (B0->getOperand(0) == PN) ? Op : scalarPHI;
174 B0->getOpcode(), FirstOp, SecondOp, B0),
175 B0->getIterator());
176 } else {
177 // Scalarize PHI input:
178 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
179 // Insert the new instruction into the predecessor basic block.
180 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
181 BasicBlock::iterator InsertPos;
182 if (pos && !isa<PHINode>(pos) && !pos->isTerminator()) {
183 InsertPos = ++pos->getIterator();
184 } else {
185 InsertPos = inBB->getFirstInsertionPt();
186 }
187
188 ScalarVal = InsertNewInstWith(newEI, InsertPos);
189 }
190
191 ScalarizedValues[inBB] = ScalarVal;
192 scalarPHI->addIncoming(ScalarVal, inBB);
193 }
194
195 for (auto *E : Extracts) {
196 replaceInstUsesWith(*E, scalarPHI);
197 // Add old extract to worklist for DCE.
199 }
200
201 return &EI;
202}
203
204Instruction *InstCombinerImpl::foldBitcastExtElt(ExtractElementInst &Ext) {
205 Value *X;
206 uint64_t ExtIndexC;
207 if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
208 !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
209 return nullptr;
210
211 ElementCount NumElts =
212 cast<VectorType>(Ext.getVectorOperandType())->getElementCount();
213 Type *DestTy = Ext.getType();
214 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
215 bool IsBigEndian = DL.isBigEndian();
216
217 // If we are casting an integer to vector and extracting a portion, that is
218 // a shift-right and truncate.
219 if (X->getType()->isIntegerTy()) {
221 "Expected fixed vector type for bitcast from scalar integer");
222
223 // Big endian requires adjusting the extract index since MSB is at index 0.
224 // LittleEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 X to i8
225 // BigEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 (X >> 24) to i8
226 if (IsBigEndian)
227 ExtIndexC = NumElts.getKnownMinValue() - 1 - ExtIndexC;
228 unsigned ShiftAmountC = ExtIndexC * DestWidth;
229 if ((!ShiftAmountC ||
230 isDesirableIntType(X->getType()->getPrimitiveSizeInBits())) &&
231 Ext.getVectorOperand()->hasOneUse()) {
232 if (ShiftAmountC)
233 X = Builder.CreateLShr(X, ShiftAmountC, "extelt.offset");
234 if (DestTy->isFloatingPointTy()) {
235 Type *DstIntTy = IntegerType::getIntNTy(X->getContext(), DestWidth);
236 Value *Trunc = Builder.CreateTrunc(X, DstIntTy);
237 return new BitCastInst(Trunc, DestTy);
238 }
239 return new TruncInst(X, DestTy);
240 }
241 }
242
243 if (!X->getType()->isVectorTy())
244 return nullptr;
245
246 // If this extractelement is using a bitcast from a vector of the same number
247 // of elements, see if we can find the source element from the source vector:
248 // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
249 auto *SrcTy = cast<VectorType>(X->getType());
250 ElementCount NumSrcElts = SrcTy->getElementCount();
251 if (NumSrcElts == NumElts)
252 if (Value *Elt = findScalarElement(X, ExtIndexC))
253 return new BitCastInst(Elt, DestTy);
254
255 assert(NumSrcElts.isScalable() == NumElts.isScalable() &&
256 "Src and Dst must be the same sort of vector type");
257
258 // If the source elements are wider than the destination, try to shift and
259 // truncate a subset of scalar bits of an insert op.
260 if (NumSrcElts.getKnownMinValue() < NumElts.getKnownMinValue()) {
261 Value *Scalar;
262 Value *Vec;
263 uint64_t InsIndexC;
264 if (!match(X, m_InsertElt(m_Value(Vec), m_Value(Scalar),
265 m_ConstantInt(InsIndexC))))
266 return nullptr;
267
268 // The extract must be from the subset of vector elements that we inserted
269 // into. Example: if we inserted element 1 of a <2 x i64> and we are
270 // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
271 // of elements 4-7 of the bitcasted vector.
272 unsigned NarrowingRatio =
273 NumElts.getKnownMinValue() / NumSrcElts.getKnownMinValue();
274
275 if (ExtIndexC / NarrowingRatio != InsIndexC) {
276 // Remove insertelement, if we don't use the inserted element.
277 // extractelement (bitcast (insertelement (Vec, b)), a) ->
278 // extractelement (bitcast (Vec), a)
279 // FIXME: this should be removed to SimplifyDemandedVectorElts,
280 // once scale vectors are supported.
281 if (X->hasOneUse() && Ext.getVectorOperand()->hasOneUse()) {
282 Value *NewBC = Builder.CreateBitCast(Vec, Ext.getVectorOperandType());
283 return ExtractElementInst::Create(NewBC, Ext.getIndexOperand());
284 }
285 return nullptr;
286 }
287
288 // We are extracting part of the original scalar. How that scalar is
289 // inserted into the vector depends on the endian-ness. Example:
290 // Vector Byte Elt Index: 0 1 2 3 4 5 6 7
291 // +--+--+--+--+--+--+--+--+
292 // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3|
293 // extelt <4 x i16> V', 3: | |S2|S3|
294 // +--+--+--+--+--+--+--+--+
295 // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
296 // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
297 // In this example, we must right-shift little-endian. Big-endian is just a
298 // truncate.
299 unsigned Chunk = ExtIndexC % NarrowingRatio;
300 if (IsBigEndian)
301 Chunk = NarrowingRatio - 1 - Chunk;
302
303 // Bail out if this is an FP vector to FP vector sequence. That would take
304 // more instructions than we started with unless there is no shift, and it
305 // may not be handled as well in the backend.
306 bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
307 bool NeedDestBitcast = DestTy->isFloatingPointTy();
308 if (NeedSrcBitcast && NeedDestBitcast)
309 return nullptr;
310
311 unsigned SrcWidth = SrcTy->getScalarSizeInBits();
312 unsigned ShAmt = Chunk * DestWidth;
313
314 // TODO: This limitation is more strict than necessary. We could sum the
315 // number of new instructions and subtract the number eliminated to know if
316 // we can proceed.
317 if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
318 if (NeedSrcBitcast || NeedDestBitcast)
319 return nullptr;
320
321 if (NeedSrcBitcast) {
322 Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
323 Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
324 }
325
326 if (ShAmt) {
327 // Bail out if we could end with more instructions than we started with.
328 if (!Ext.getVectorOperand()->hasOneUse())
329 return nullptr;
330 Scalar = Builder.CreateLShr(Scalar, ShAmt);
331 }
332
333 if (NeedDestBitcast) {
334 Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
335 return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
336 }
337 return new TruncInst(Scalar, DestTy);
338 }
339
340 return nullptr;
341}
342
343/// Find elements of V demanded by UserInstr. If returns false, we were not able
344/// to determine all elements.
346 APInt &UnionUsedElts) {
347 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
348
349 switch (UserInstr->getOpcode()) {
350 case Instruction::ExtractElement: {
352 assert(EEI->getVectorOperand() == V);
354 if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
355 UnionUsedElts.setBit(EEIIndexC->getZExtValue());
356 return true;
357 }
358 break;
359 }
360 case Instruction::ShuffleVector: {
361 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr);
362 unsigned MaskNumElts =
363 cast<FixedVectorType>(UserInstr->getType())->getNumElements();
364
365 for (auto I : llvm::seq(MaskNumElts)) {
366 unsigned MaskVal = Shuffle->getMaskValue(I);
367 if (MaskVal == -1u || MaskVal >= 2 * VWidth)
368 continue;
369 if (Shuffle->getOperand(0) == V && (MaskVal < VWidth))
370 UnionUsedElts.setBit(MaskVal);
371 if (Shuffle->getOperand(1) == V &&
372 ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
373 UnionUsedElts.setBit(MaskVal - VWidth);
374 }
375 return true;
376 }
377 default:
378 break;
379 }
380
381 return false;
382}
383
384/// Find union of elements of V demanded by all its users.
385/// If it is known by querying findDemandedEltsBySingleUser that
386/// no user demands an element of V, then the corresponding bit
387/// remains unset in the returned value.
389 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
390
391 APInt UnionUsedElts(VWidth, 0);
392 for (const Use &U : V->uses()) {
393 if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
394 if (!findDemandedEltsBySingleUser(V, I, UnionUsedElts))
395 return APInt::getAllOnes(VWidth);
396 } else {
397 UnionUsedElts = APInt::getAllOnes(VWidth);
398 break;
399 }
400
401 if (UnionUsedElts.isAllOnes())
402 break;
403 }
404
405 return UnionUsedElts;
406}
407
408/// Given a constant index for a extractelement or insertelement instruction,
409/// return it with the canonical type if it isn't already canonical. We
410/// arbitrarily pick 64 bit as our canonical type. The actual bitwidth doesn't
411/// matter, we just want a consistent type to simplify CSE.
413 const unsigned IndexBW = IndexC->getBitWidth();
414 if (IndexBW == 64 || IndexC->getValue().getActiveBits() > 64)
415 return nullptr;
416 return ConstantInt::get(IndexC->getContext(),
417 IndexC->getValue().zextOrTrunc(64));
418}
419
420/// Fold a variable extract from a vector of pointers that all point into the
421/// same object at a constant stride
422static Value *
425 const DataLayout &DL) {
427 if (!VecTy || !VecTy->getElementType()->isPointerTy())
428 return nullptr;
429
430 unsigned NumElts = VecTy->getNumElements();
431 if (NumElts < 2)
432 return nullptr;
433
434 // Every lane must resolve to the same base pointer plus a constant byte
435 // offset. findScalarElement returns poison for a lane the vector never
436 // defines; that poison is its own base, so a vector mixing defined and
437 // undefined lanes fails the base comparison below.
438 unsigned IdxWidth = DL.getIndexTypeSizeInBits(VecTy->getElementType());
439 Value *Base = nullptr;
440 SmallVector<APInt> Offsets;
441 for (unsigned I = 0; I != NumElts; ++I) {
443 if (!Elt)
444 return nullptr;
445 Value *EltBase;
446 const APInt *C;
447 APInt Offset(IdxWidth, 0);
448 // m_Value may bind even when the offset is not constant, so reset it.
449 if (match(Elt, m_PtrAdd(DL, m_Value(EltBase), m_APInt(C))))
450 Offset = *C;
451 else
452 EltBase = Elt;
453 if (I == 0)
454 Base = EltBase;
455 else if (Base != EltBase)
456 return nullptr;
457 Offsets.push_back(Offset);
458 }
459
460 // The offsets must form an arithmetic sequence.
461 APInt Stride = Offsets[1] - Offsets[0];
462 for (unsigned I = 1; I != NumElts; ++I)
463 if (Offsets[I] - Offsets[0] != Stride * I)
464 return nullptr;
465
466 // Index off the common base, not off element 0: an element may be poison in
467 // a lane the extract never selects. The base is an operand of every element
468 // and the new GEPs have no flags, so the result is never more poisonous.
469 Type *IdxTy = DL.getIndexType(VecTy->getElementType());
470 Value *Idx = Builder.CreateZExtOrTrunc(EI.getIndexOperand(), IdxTy);
471 Value *Ptr = Builder.CreatePtrAdd(
472 Base, Builder.CreateMul(Idx, ConstantInt::get(IdxTy, Stride)));
473 return Builder.CreatePtrAdd(Ptr, ConstantInt::get(IdxTy, Offsets[0]));
474}
475
477 Value *SrcVec = EI.getVectorOperand();
478 Value *Index = EI.getIndexOperand();
479 if (Value *V = simplifyExtractElementInst(SrcVec, Index,
480 SQ.getWithInstruction(&EI)))
481 return replaceInstUsesWith(EI, V);
482
483 // extractelt (select %x, %vec1, %vec2), %const ->
484 // select %x, %vec1[%const], %vec2[%const]
485 // TODO: Support constant folding of multiple select operands:
486 // extractelt (select %x, %vec1, %vec2), (select %x, %c1, %c2)
487 // If the extractelement will for instance try to do out of bounds accesses
488 // because of the values of %c1 and/or %c2, the sequence could be optimized
489 // early. This is currently not possible because constant folding will reach
490 // an unreachable assertion if it doesn't find a constant operand.
492 if (SI->getCondition()->getType()->isIntegerTy() &&
494 if (Instruction *R = FoldOpIntoSelect(EI, SI))
495 return R;
496
497 // Fold a variable index into a table of pointers into one object into
498 // address arithmetic
499 if (!isa<ConstantInt>(Index))
501 return replaceInstUsesWith(EI, V);
502
503 // If extracting a specified index from the vector, see if we can recursively
504 // find a previously computed scalar that was inserted into the vector.
505 auto *IndexC = dyn_cast<ConstantInt>(Index);
506 bool HasKnownValidIndex = false;
507 if (IndexC) {
508 // Canonicalize type of constant indices to i64 to simplify CSE
509 if (auto *NewIdx = getPreferredVectorIndex(IndexC))
510 return replaceOperand(EI, 1, NewIdx);
511
513 unsigned NumElts = EC.getKnownMinValue();
514 HasKnownValidIndex = IndexC->getValue().ult(NumElts);
515
517 Intrinsic::ID IID = II->getIntrinsicID();
518 // Index needs to be lower than the minimum size of the vector, because
519 // for scalable vector, the vector size is known at run time.
520 if (IID == Intrinsic::stepvector && IndexC->getValue().ult(NumElts)) {
521 Type *Ty = EI.getType();
522 unsigned BitWidth = Ty->getIntegerBitWidth();
523 Value *Idx;
524 // Return index when its value does not exceed the allowed limit
525 // for the element type of the vector.
526 // TODO: Truncate out-of-range values.
527 if (IndexC->getValue().getActiveBits() <= BitWidth)
528 Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(BitWidth));
529 else
530 return nullptr;
531 return replaceInstUsesWith(EI, Idx);
532 }
533 }
534
535 // InstSimplify should handle cases where the index is invalid.
536 // For fixed-length vector, it's invalid to extract out-of-range element.
537 if (!EC.isScalable() && IndexC->getValue().uge(NumElts))
538 return nullptr;
539
540 if (Instruction *I = foldBitcastExtElt(EI))
541 return I;
542
543 // If there's a vector PHI feeding a scalar use through this extractelement
544 // instruction, try to scalarize the PHI.
545 if (auto *Phi = dyn_cast<PHINode>(SrcVec))
546 if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
547 return ScalarPHI;
548 }
549
550 // If SrcVec is a subvector starting at index 0, extract from the
551 // wider source vector
552 Value *V;
553 if (match(SrcVec,
555 return ExtractElementInst::Create(V, Index);
556
557 // TODO come up with a n-ary matcher that subsumes both unary and
558 // binary matchers.
559 UnaryOperator *UO;
560 if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, Index)) {
561 // extelt (unop X), Index --> unop (extelt X, Index)
562 Value *X = UO->getOperand(0);
563 Value *E = Builder.CreateExtractElement(X, Index);
565 }
566
567 // If the binop is not speculatable, we cannot hoist the extractelement if
568 // it may make the operand poison.
569 BinaryOperator *BO;
570 if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, Index) &&
571 (HasKnownValidIndex ||
573 // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
574 Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
575 Value *E0 = Builder.CreateExtractElement(X, Index);
576 Value *E1 = Builder.CreateExtractElement(Y, Index);
577 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
578 }
579
580 Value *X, *Y;
581 CmpPredicate Pred;
582 if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
583 cheapToScalarize(SrcVec, Index)) {
584 // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
585 Value *E0 = Builder.CreateExtractElement(X, Index);
586 Value *E1 = Builder.CreateExtractElement(Y, Index);
587 CmpInst *SrcCmpInst = cast<CmpInst>(SrcVec);
588 return CmpInst::CreateWithCopiedFlags(SrcCmpInst->getOpcode(), Pred, E0, E1,
589 SrcCmpInst);
590 }
591
592 if (auto *I = dyn_cast<Instruction>(SrcVec)) {
593 if (auto *IE = dyn_cast<InsertElementInst>(I)) {
594 // instsimplify already handled the case where the indices are constants
595 // and equal by value, if both are constants, they must not be the same
596 // value, extract from the pre-inserted value instead.
597 if (isa<Constant>(IE->getOperand(2)) && IndexC)
598 return replaceOperand(EI, 0, IE->getOperand(0));
599 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
600 auto *VecType = cast<VectorType>(GEP->getType());
601 ElementCount EC = VecType->getElementCount();
602 uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0;
603 if (IndexC && IdxVal < EC.getKnownMinValue() && GEP->hasOneUse()) {
604 // Find out why we have a vector result - these are a few examples:
605 // 1. We have a scalar pointer and a vector of indices, or
606 // 2. We have a vector of pointers and a scalar index, or
607 // 3. We have a vector of pointers and a vector of indices, etc.
608 // Here we only consider combining when there is exactly one vector
609 // operand, since the optimization is less obviously a win due to
610 // needing more than one extractelements.
611
612 unsigned VectorOps =
613 llvm::count_if(GEP->operands(), [](const Value *V) {
614 return isa<VectorType>(V->getType());
615 });
616 if (VectorOps == 1) {
617 Value *NewPtr = GEP->getPointerOperand();
618 if (isa<VectorType>(NewPtr->getType()))
619 NewPtr = Builder.CreateExtractElement(NewPtr, IndexC);
620
622 for (unsigned I = 1; I != GEP->getNumOperands(); ++I) {
623 Value *Op = GEP->getOperand(I);
624 if (isa<VectorType>(Op->getType()))
625 NewOps.push_back(Builder.CreateExtractElement(Op, IndexC));
626 else
627 NewOps.push_back(Op);
628 }
629
631 GEP->getSourceElementType(), NewPtr, NewOps);
632 NewGEP->setNoWrapFlags(GEP->getNoWrapFlags());
633 return NewGEP;
634 }
635 }
636 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
637 int SplatIndex = getSplatIndex(SVI->getShuffleMask());
638 // We know the all-0 splat must be reading from the first operand, even
639 // in the case of scalable vectors (vscale is always > 0).
640 if (SplatIndex == 0)
641 return ExtractElementInst::Create(SVI->getOperand(0),
642 Builder.getInt64(0));
643
644 if (isa<FixedVectorType>(SVI->getType())) {
645 std::optional<int> SrcIdx;
646 // getSplatIndex returns -1 to mean not-found.
647 if (SplatIndex != -1)
648 SrcIdx = SplatIndex;
649 else if (ConstantInt *CI = dyn_cast<ConstantInt>(Index))
650 SrcIdx = SVI->getMaskValue(CI->getZExtValue());
651
652 if (SrcIdx) {
653 Value *Src;
654 unsigned LHSWidth =
655 cast<FixedVectorType>(SVI->getOperand(0)->getType())
656 ->getNumElements();
657
658 if (*SrcIdx < 0)
660 if (*SrcIdx < (int)LHSWidth)
661 Src = SVI->getOperand(0);
662 else {
663 *SrcIdx -= LHSWidth;
664 Src = SVI->getOperand(1);
665 }
666 Type *Int64Ty = Type::getInt64Ty(EI.getContext());
668 Src, ConstantInt::get(Int64Ty, *SrcIdx, false));
669 }
670 }
671 } else if (auto *CI = dyn_cast<CastInst>(I)) {
672 // Canonicalize extractelement(cast) -> cast(extractelement).
673 // Bitcasts can change the number of vector elements, and they cost
674 // nothing.
675 // If the CI has only one use, but that use is inside a loop, this
676 // canonicalization is not profitable because it would turn a vector
677 // operation into scalar operations inside the loop. Apply the transform
678 // when:
679 // - the index is constant and CI has one use, or
680 // - the CI and EI are in the same basic block, so the cast won't be sunk
681 // into a loop.
682 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast) &&
683 (EI.getParent() == CI->getParent() || isa<ConstantInt>(Index))) {
684 Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
685 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
686 }
687 }
688 }
689
690 // Run demanded elements after other transforms as this can drop flags on
691 // binops. If there's two paths to the same final result, we prefer the
692 // one which doesn't force us to drop flags.
693 if (IndexC) {
695 unsigned NumElts = EC.getKnownMinValue();
696 // This instruction only demands the single element from the input vector.
697 // Skip for scalable type, the number of elements is unknown at
698 // compile-time.
699 if (!EC.isScalable() && NumElts != 1) {
700 // If the input vector has a single use, simplify it based on this use
701 // property.
702 if (SrcVec->hasOneUse()) {
703 APInt PoisonElts(NumElts, 0);
704 APInt DemandedElts(NumElts, 0);
705 DemandedElts.setBit(IndexC->getZExtValue());
706 if (Value *V =
707 SimplifyDemandedVectorElts(SrcVec, DemandedElts, PoisonElts))
708 return replaceOperand(EI, 0, V);
709 } else {
710 // If the input vector has multiple uses, simplify it based on a union
711 // of all elements used.
712 APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec);
713 if (!DemandedElts.isAllOnes()) {
714 APInt PoisonElts(NumElts, 0);
716 SrcVec, DemandedElts, PoisonElts, 0 /* Depth */,
717 true /* AllowMultipleUsers */)) {
718 if (V != SrcVec) {
719 Worklist.addValue(SrcVec);
720 SrcVec->replaceAllUsesWith(V);
721 return &EI;
722 }
723 }
724 }
725 }
726 }
727 }
728 return nullptr;
729}
730
731/// If V is a shuffle of values that ONLY returns elements from either LHS or
732/// RHS, return the shuffle mask and true. Otherwise, return false.
734 SmallVectorImpl<int> &Mask) {
735 assert(LHS->getType() == RHS->getType() &&
736 "Invalid CollectSingleShuffleElements");
737 unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
738
739 if (match(V, m_Poison())) {
740 Mask.assign(NumElts, -1);
741 return true;
742 }
743
744 if (V == LHS) {
745 for (unsigned i = 0; i != NumElts; ++i)
746 Mask.push_back(i);
747 return true;
748 }
749
750 if (V == RHS) {
751 for (unsigned i = 0; i != NumElts; ++i)
752 Mask.push_back(i + NumElts);
753 return true;
754 }
755
757 // If this is an insert of an extract from some other vector, include it.
758 Value *VecOp = IEI->getOperand(0);
759 Value *ScalarOp = IEI->getOperand(1);
760 Value *IdxOp = IEI->getOperand(2);
761
762 if (!isa<ConstantInt>(IdxOp))
763 return false;
764 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
765
766 if (isa<PoisonValue>(ScalarOp)) { // inserting poison into vector.
767 // We can handle this if the vector we are inserting into is
768 // transitively ok.
769 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
770 // If so, update the mask to reflect the inserted poison.
771 Mask[InsertedIdx] = -1;
772 return true;
773 }
774 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
775 if (isa<ConstantInt>(EI->getOperand(1))) {
776 unsigned ExtractedIdx =
777 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
778 unsigned NumLHSElts =
779 cast<FixedVectorType>(LHS->getType())->getNumElements();
780
781 // This must be extracting from either LHS or RHS.
782 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
783 // We can handle this if the vector we are inserting into is
784 // transitively ok.
785 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
786 // If so, update the mask to reflect the inserted value.
787 if (EI->getOperand(0) == LHS) {
788 Mask[InsertedIdx % NumElts] = ExtractedIdx;
789 } else {
790 assert(EI->getOperand(0) == RHS);
791 Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts;
792 }
793 return true;
794 }
795 }
796 }
797 }
798 }
799
800 return false;
801}
802
803/// If we have insertion into a vector that is wider than the vector that we
804/// are extracting from, try to widen the source vector to allow a single
805/// shufflevector to replace one or more insert/extract pairs.
807 ExtractElementInst *ExtElt,
808 InstCombinerImpl &IC) {
809 auto *InsVecType = cast<FixedVectorType>(InsElt->getType());
810 auto *ExtVecType = cast<FixedVectorType>(ExtElt->getVectorOperandType());
811 unsigned NumInsElts = InsVecType->getNumElements();
812 unsigned NumExtElts = ExtVecType->getNumElements();
813
814 // The inserted-to vector must be wider than the extracted-from vector.
815 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
816 NumExtElts >= NumInsElts)
817 return false;
818
819 Value *ExtVecOp = ExtElt->getVectorOperand();
820 // Bail out on constant vectors.
821 if (isa<ConstantData>(ExtVecOp))
822 return false;
823
824 // Create a shuffle mask to widen the extended-from vector using poison
825 // values. The mask selects all of the values of the original vector followed
826 // by as many poison values as needed to create a vector of the same length
827 // as the inserted-to vector.
828 SmallVector<int, 16> ExtendMask;
829 for (unsigned i = 0; i < NumExtElts; ++i)
830 ExtendMask.push_back(i);
831 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
832 ExtendMask.push_back(-1);
833
834 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
835 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
836 ? ExtVecOpInst->getParent()
837 : ExtElt->getParent();
838
839 // TODO: This restriction matches the basic block check below when creating
840 // new extractelement instructions. If that limitation is removed, this one
841 // could also be removed. But for now, we just bail out to ensure that we
842 // will replace the extractelement instruction that is feeding our
843 // insertelement instruction. This allows the insertelement to then be
844 // replaced by a shufflevector. If the insertelement is not replaced, we can
845 // induce infinite looping because there's an optimization for extractelement
846 // that will delete our widening shuffle. This would trigger another attempt
847 // here to create that shuffle, and we spin forever.
848 if (InsertionBlock != InsElt->getParent())
849 return false;
850
851 // TODO: This restriction matches the check in visitInsertElementInst() and
852 // prevents an infinite loop caused by not turning the extract/insert pair
853 // into a shuffle. We really should not need either check, but we're lacking
854 // folds for shufflevectors because we're afraid to generate shuffle masks
855 // that the backend can't handle.
856 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
857 return false;
858
859 auto *WideVec = new ShuffleVectorInst(ExtVecOp, ExtendMask);
860
861 // Insert the new shuffle after the vector operand of the extract is defined
862 // (as long as it's not a PHI) or at the start of the basic block of the
863 // extract, so any subsequent extracts in the same basic block can use it.
864 // TODO: Insert before the earliest ExtractElementInst that is replaced.
865 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
866 WideVec->insertAfter(ExtVecOpInst->getIterator());
867 else
868 IC.InsertNewInstWith(WideVec, ExtElt->getParent()->getFirstInsertionPt());
869
870 // WideVec is an extension of ExtVecOp to produce a more useful value for
871 // ExtractElement instructions. If ExtVecOp is an instruction, adopt its
872 // DebugLoc; if it is not, then this is materializing a constant value, so set
873 // a CompilerGenerated location.
874 if (ExtVecOpInst)
875 WideVec->setDebugLoc(ExtVecOpInst->getDebugLoc());
876 else
877 WideVec->setDebugLoc(DebugLoc::getCompilerGenerated());
878
879 // Replace extracts from the original narrow vector with extracts from the new
880 // wide vector.
881 for (User *U : ExtVecOp->users()) {
883 if (!OldExt || OldExt->getParent() != WideVec->getParent())
884 continue;
885 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
886 IC.InsertNewInstWith(NewExt, OldExt->getIterator());
887 IC.replaceInstUsesWith(*OldExt, NewExt);
888 // Add the old extracts to the worklist for DCE. We can't remove the
889 // extracts directly, because they may still be used by the calling code.
890 IC.addToWorklist(OldExt);
891 }
892
893 return true;
894}
895
896/// We are building a shuffle to create V, which is a sequence of insertelement,
897/// extractelement pairs. If PermittedRHS is set, then we must either use it or
898/// not rely on the second vector source. Return a std::pair containing the
899/// left and right vectors of the proposed shuffle (or 0), and set the Mask
900/// parameter as required.
901///
902/// Note: we intentionally don't try to fold earlier shuffles since they have
903/// often been chosen carefully to be efficiently implementable on the target.
904using ShuffleOps = std::pair<Value *, Value *>;
905
907 Value *PermittedRHS,
908 InstCombinerImpl &IC, bool &Rerun) {
909 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
910 unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
911
912 if (match(V, m_Poison())) {
913 Mask.assign(NumElts, -1);
914 return std::make_pair(
915 PermittedRHS ? PoisonValue::get(PermittedRHS->getType()) : V, nullptr);
916 }
917
918 if (match(V, m_ZeroForbidPoison())) {
919 Mask.assign(NumElts, 0);
920 return std::make_pair(V, nullptr);
921 }
922
924 // If this is an insert of an extract from some other vector, include it.
925 Value *VecOp = IEI->getOperand(0);
926 Value *ScalarOp = IEI->getOperand(1);
927 Value *IdxOp = IEI->getOperand(2);
928
930 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
931 unsigned ExtractedIdx =
932 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
933 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
934
935 // Either the extracted from or inserted into vector must be RHSVec,
936 // otherwise we'd end up with a shuffle of three inputs.
937 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
938 Value *RHS = EI->getOperand(0);
939 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC, Rerun);
940 assert(LR.second == nullptr || LR.second == RHS);
941
942 if (LR.first->getType() != RHS->getType()) {
943 // Although we are giving up for now, see if we can create extracts
944 // that match the inserts for another round of combining.
945 if (replaceExtractElements(IEI, EI, IC))
946 Rerun = true;
947
948 // We tried our best, but we can't find anything compatible with RHS
949 // further up the chain. Return a trivial shuffle.
950 for (unsigned i = 0; i < NumElts; ++i)
951 Mask[i] = i;
952 return std::make_pair(V, nullptr);
953 }
954
955 unsigned NumLHSElts =
956 cast<FixedVectorType>(RHS->getType())->getNumElements();
957 Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx;
958 return std::make_pair(LR.first, RHS);
959 }
960
961 if (VecOp == PermittedRHS) {
962 // We've gone as far as we can: anything on the other side of the
963 // extractelement will already have been converted into a shuffle.
964 unsigned NumLHSElts =
966 ->getNumElements();
967 for (unsigned i = 0; i != NumElts; ++i)
968 Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i);
969 return std::make_pair(EI->getOperand(0), PermittedRHS);
970 }
971
972 // If this insertelement is a chain that comes from exactly these two
973 // vectors, return the vector and the effective shuffle.
974 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
975 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
976 Mask))
977 return std::make_pair(EI->getOperand(0), PermittedRHS);
978 }
979 }
980 }
981
982 // Otherwise, we can't do anything fancy. Return an identity vector.
983 for (unsigned i = 0; i != NumElts; ++i)
984 Mask.push_back(i);
985 return std::make_pair(V, nullptr);
986}
987
988/// Look for chain of insertvalue's that fully define an aggregate, and trace
989/// back the values inserted, see if they are all were extractvalue'd from
990/// the same source aggregate from the exact same element indexes.
991/// If they were, just reuse the source aggregate.
992/// This potentially deals with PHI indirections.
994 InsertValueInst &OrigIVI) {
995 Type *AggTy = OrigIVI.getType();
996 unsigned NumAggElts;
997 switch (AggTy->getTypeID()) {
998 case Type::StructTyID:
999 NumAggElts = AggTy->getStructNumElements();
1000 break;
1001 case Type::ArrayTyID:
1002 NumAggElts = AggTy->getArrayNumElements();
1003 break;
1004 default:
1005 llvm_unreachable("Unhandled aggregate type?");
1006 }
1007
1008 // Arbitrary aggregate size cut-off. Motivation for limit of 2 is to be able
1009 // to handle clang C++ exception struct (which is hardcoded as {i8*, i32}),
1010 // FIXME: any interesting patterns to be caught with larger limit?
1011 assert(NumAggElts > 0 && "Aggregate should have elements.");
1012 if (NumAggElts > 2)
1013 return nullptr;
1014
1015 static constexpr auto NotFound = std::nullopt;
1016 static constexpr auto FoundMismatch = nullptr;
1017
1018 // Try to find a value of each element of an aggregate.
1019 // FIXME: deal with more complex, not one-dimensional, aggregate types
1020 SmallVector<std::optional<Instruction *>, 2> AggElts(NumAggElts, NotFound);
1021
1022 // Do we know values for each element of the aggregate?
1023 auto KnowAllElts = [&AggElts]() {
1024 return !llvm::is_contained(AggElts, NotFound);
1025 };
1026
1027 int Depth = 0;
1028
1029 // Arbitrary `insertvalue` visitation depth limit. Let's be okay with
1030 // every element being overwritten twice, which should never happen.
1031 static const int DepthLimit = 2 * NumAggElts;
1032
1033 // Recurse up the chain of `insertvalue` aggregate operands until either we've
1034 // reconstructed full initializer or can't visit any more `insertvalue`'s.
1035 for (InsertValueInst *CurrIVI = &OrigIVI;
1036 Depth < DepthLimit && CurrIVI && !KnowAllElts();
1037 CurrIVI = dyn_cast<InsertValueInst>(CurrIVI->getAggregateOperand()),
1038 ++Depth) {
1039 auto *InsertedValue =
1040 dyn_cast<Instruction>(CurrIVI->getInsertedValueOperand());
1041 if (!InsertedValue)
1042 return nullptr; // Inserted value must be produced by an instruction.
1043
1044 ArrayRef<unsigned int> Indices = CurrIVI->getIndices();
1045
1046 // Don't bother with more than single-level aggregates.
1047 if (Indices.size() != 1)
1048 return nullptr; // FIXME: deal with more complex aggregates?
1049
1050 // Now, we may have already previously recorded the value for this element
1051 // of an aggregate. If we did, that means the CurrIVI will later be
1052 // overwritten with the already-recorded value. But if not, let's record it!
1053 std::optional<Instruction *> &Elt = AggElts[Indices.front()];
1054 Elt = Elt.value_or(InsertedValue);
1055
1056 // FIXME: should we handle chain-terminating undef base operand?
1057 }
1058
1059 // Was that sufficient to deduce the full initializer for the aggregate?
1060 if (!KnowAllElts())
1061 return nullptr; // Give up then.
1062
1063 // We now want to find the source[s] of the aggregate elements we've found.
1064 // And with "source" we mean the original aggregate[s] from which
1065 // the inserted elements were extracted. This may require PHI translation.
1066
1067 enum class AggregateDescription {
1068 /// When analyzing the value that was inserted into an aggregate, we did
1069 /// not manage to find defining `extractvalue` instruction to analyze.
1070 NotFound,
1071 /// When analyzing the value that was inserted into an aggregate, we did
1072 /// manage to find defining `extractvalue` instruction[s], and everything
1073 /// matched perfectly - aggregate type, element insertion/extraction index.
1074 Found,
1075 /// When analyzing the value that was inserted into an aggregate, we did
1076 /// manage to find defining `extractvalue` instruction, but there was
1077 /// a mismatch: either the source type from which the extraction was didn't
1078 /// match the aggregate type into which the insertion was,
1079 /// or the extraction/insertion channels mismatched,
1080 /// or different elements had different source aggregates.
1081 FoundMismatch
1082 };
1083 auto Describe = [](std::optional<Value *> SourceAggregate) {
1084 if (SourceAggregate == NotFound)
1085 return AggregateDescription::NotFound;
1086 if (*SourceAggregate == FoundMismatch)
1087 return AggregateDescription::FoundMismatch;
1088 return AggregateDescription::Found;
1089 };
1090
1091 // If an aggregate element is defined in UseBB, we can't use it in PredBB.
1092 bool EltDefinedInUseBB = false;
1093
1094 // Given the value \p Elt that was being inserted into element \p EltIdx of an
1095 // aggregate AggTy, see if \p Elt was originally defined by an
1096 // appropriate extractvalue (same element index, same aggregate type).
1097 // If found, return the source aggregate from which the extraction was.
1098 // If \p PredBB is provided, does PHI translation of an \p Elt first.
1099 auto FindSourceAggregate =
1100 [&](Instruction *Elt, unsigned EltIdx, std::optional<BasicBlock *> UseBB,
1101 std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
1102 // For now(?), only deal with, at most, a single level of PHI indirection.
1103 if (UseBB && PredBB) {
1104 Elt = dyn_cast<Instruction>(Elt->DoPHITranslation(*UseBB, *PredBB));
1105 if (Elt && Elt->getParent() == *UseBB)
1106 EltDefinedInUseBB = true;
1107 }
1108 // FIXME: deal with multiple levels of PHI indirection?
1109
1110 // Did we find an extraction?
1111 auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt);
1112 if (!EVI)
1113 return NotFound;
1114
1115 Value *SourceAggregate = EVI->getAggregateOperand();
1116
1117 // Is the extraction from the same type into which the insertion was?
1118 if (SourceAggregate->getType() != AggTy)
1119 return FoundMismatch;
1120 // And the element index doesn't change between extraction and insertion?
1121 if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front())
1122 return FoundMismatch;
1123
1124 return SourceAggregate; // AggregateDescription::Found
1125 };
1126
1127 // Given elements AggElts that were constructing an aggregate OrigIVI,
1128 // see if we can find appropriate source aggregate for each of the elements,
1129 // and see it's the same aggregate for each element. If so, return it.
1130 auto FindCommonSourceAggregate =
1131 [&](std::optional<BasicBlock *> UseBB,
1132 std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
1133 std::optional<Value *> SourceAggregate;
1134
1135 for (auto I : enumerate(AggElts)) {
1136 assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch &&
1137 "We don't store nullptr in SourceAggregate!");
1138 assert((Describe(SourceAggregate) == AggregateDescription::Found) ==
1139 (I.index() != 0) &&
1140 "SourceAggregate should be valid after the first element,");
1141
1142 // For this element, is there a plausible source aggregate?
1143 // FIXME: we could special-case undef element, IFF we know that in the
1144 // source aggregate said element isn't poison.
1145 std::optional<Value *> SourceAggregateForElement =
1146 FindSourceAggregate(*I.value(), I.index(), UseBB, PredBB);
1147
1148 // Okay, what have we found? Does that correlate with previous findings?
1149
1150 // Regardless of whether or not we have previously found source
1151 // aggregate for previous elements (if any), if we didn't find one for
1152 // this element, passthrough whatever we have just found.
1153 if (Describe(SourceAggregateForElement) != AggregateDescription::Found)
1154 return SourceAggregateForElement;
1155
1156 // Okay, we have found source aggregate for this element.
1157 // Let's see what we already know from previous elements, if any.
1158 switch (Describe(SourceAggregate)) {
1159 case AggregateDescription::NotFound:
1160 // This is apparently the first element that we have examined.
1161 SourceAggregate = SourceAggregateForElement; // Record the aggregate!
1162 continue; // Great, now look at next element.
1163 case AggregateDescription::Found:
1164 // We have previously already successfully examined other elements.
1165 // Is this the same source aggregate we've found for other elements?
1166 if (*SourceAggregateForElement != *SourceAggregate)
1167 return FoundMismatch;
1168 continue; // Still the same aggregate, look at next element.
1169 case AggregateDescription::FoundMismatch:
1170 llvm_unreachable("Can't happen. We would have early-exited then.");
1171 };
1172 }
1173
1174 assert(Describe(SourceAggregate) == AggregateDescription::Found &&
1175 "Must be a valid Value");
1176 return *SourceAggregate;
1177 };
1178
1179 std::optional<Value *> SourceAggregate;
1180
1181 // Can we find the source aggregate without looking at predecessors?
1182 SourceAggregate = FindCommonSourceAggregate(/*UseBB=*/std::nullopt,
1183 /*PredBB=*/std::nullopt);
1184 if (Describe(SourceAggregate) != AggregateDescription::NotFound) {
1185 if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch)
1186 return nullptr; // Conflicting source aggregates!
1187 ++NumAggregateReconstructionsSimplified;
1188 return replaceInstUsesWith(OrigIVI, *SourceAggregate);
1189 }
1190
1191 // Okay, apparently we need to look at predecessors.
1192
1193 // We should be smart about picking the "use" basic block, which will be the
1194 // merge point for aggregate, where we'll insert the final PHI that will be
1195 // used instead of OrigIVI. Basic block of OrigIVI is *not* the right choice.
1196 // We should look in which blocks each of the AggElts is being defined,
1197 // they all should be defined in the same basic block.
1198 BasicBlock *UseBB = nullptr;
1199
1200 for (const std::optional<Instruction *> &I : AggElts) {
1201 BasicBlock *BB = (*I)->getParent();
1202 // If it's the first instruction we've encountered, record the basic block.
1203 if (!UseBB) {
1204 UseBB = BB;
1205 continue;
1206 }
1207 // Otherwise, this must be the same basic block we've seen previously.
1208 if (UseBB != BB)
1209 return nullptr;
1210 }
1211
1212 // If *all* of the elements are basic-block-independent, meaning they are
1213 // either function arguments, or constant expressions, then if we didn't
1214 // handle them without predecessor-aware handling, we won't handle them now.
1215 if (!UseBB)
1216 return nullptr;
1217
1218 // If we didn't manage to find source aggregate without looking at
1219 // predecessors, and there are no predecessors to look at, then we're done.
1220 if (pred_empty(UseBB))
1221 return nullptr;
1222
1223 // Arbitrary predecessor count limit.
1224 static const int PredCountLimit = 64;
1225
1226 // Cache the (non-uniqified!) list of predecessors in a vector,
1227 // checking the limit at the same time for efficiency.
1228 SmallVector<BasicBlock *, 4> Preds; // May have duplicates!
1229 for (BasicBlock *Pred : predecessors(UseBB)) {
1230 // Don't bother if there are too many predecessors.
1231 if (Preds.size() >= PredCountLimit) // FIXME: only count duplicates once?
1232 return nullptr;
1233 Preds.emplace_back(Pred);
1234 }
1235
1236 // For each predecessor, what is the source aggregate,
1237 // from which all the elements were originally extracted from?
1238 // Note that we want for the map to have stable iteration order!
1240 bool FoundSrcAgg = false;
1241 for (BasicBlock *Pred : Preds) {
1242 std::pair<decltype(SourceAggregates)::iterator, bool> IV =
1243 SourceAggregates.try_emplace(Pred);
1244 // Did we already evaluate this predecessor?
1245 if (!IV.second)
1246 continue;
1247
1248 // Let's hope that when coming from predecessor Pred, all elements of the
1249 // aggregate produced by OrigIVI must have been originally extracted from
1250 // the same aggregate. Is that so? Can we find said original aggregate?
1251 SourceAggregate = FindCommonSourceAggregate(UseBB, Pred);
1252 if (Describe(SourceAggregate) == AggregateDescription::Found) {
1253 FoundSrcAgg = true;
1254 IV.first->second = *SourceAggregate;
1255 } else {
1256 // If UseBB is the single successor of Pred, we can add InsertValue to
1257 // Pred.
1258 auto *BI = dyn_cast<UncondBrInst>(Pred->getTerminator());
1259 if (!BI)
1260 return nullptr;
1261 }
1262 }
1263
1264 if (!FoundSrcAgg)
1265 return nullptr;
1266
1267 // Do some sanity check if we need to add insertvalue into predecessors.
1268 auto OrigBB = OrigIVI.getParent();
1269 for (auto &It : SourceAggregates) {
1270 if (Describe(It.second) == AggregateDescription::Found)
1271 continue;
1272
1273 // Element is defined in UseBB, so it can't be used in predecessors.
1274 if (EltDefinedInUseBB)
1275 return nullptr;
1276
1277 // Do this transformation cross loop boundary may cause dead loop. So we
1278 // should avoid this situation. But LoopInfo is not generally available, we
1279 // must be conservative here.
1280 // If OrigIVI is in UseBB and it's the only successor of PredBB, PredBB
1281 // can't be in inner loop.
1282 if (UseBB != OrigBB)
1283 return nullptr;
1284
1285 // Avoid constructing constant aggregate because constant value may expose
1286 // more optimizations.
1287 bool ConstAgg = true;
1288 for (auto Val : AggElts) {
1289 Value *Elt = (*Val)->DoPHITranslation(UseBB, It.first);
1290 if (!isa<Constant>(Elt)) {
1291 ConstAgg = false;
1292 break;
1293 }
1294 }
1295 if (ConstAgg)
1296 return nullptr;
1297 }
1298
1299 // For predecessors without appropriate source aggregate, create one in the
1300 // predecessor.
1301 for (auto &It : SourceAggregates) {
1302 if (Describe(It.second) == AggregateDescription::Found)
1303 continue;
1304
1305 BasicBlock *Pred = It.first;
1306 Builder.SetInsertPoint(Pred->getTerminator());
1307 Value *V = PoisonValue::get(AggTy);
1308 for (auto [Idx, Val] : enumerate(AggElts)) {
1309 Value *Elt = (*Val)->DoPHITranslation(UseBB, Pred);
1310 V = Builder.CreateInsertValue(V, Elt, Idx);
1311 }
1312
1313 It.second = V;
1314 }
1315
1316 // All good! Now we just need to thread the source aggregates here.
1317 // Note that we have to insert the new PHI here, ourselves, because we can't
1318 // rely on InstCombinerImpl::run() inserting it into the right basic block.
1319 // Note that the same block can be a predecessor more than once,
1320 // and we need to preserve that invariant for the PHI node.
1322 Builder.SetInsertPoint(UseBB->getFirstNonPHIIt());
1323 auto *PHI =
1324 Builder.CreatePHI(AggTy, Preds.size(), OrigIVI.getName() + ".merged");
1325 for (BasicBlock *Pred : Preds)
1326 PHI->addIncoming(SourceAggregates[Pred], Pred);
1327
1328 ++NumAggregateReconstructionsSimplified;
1329 return replaceInstUsesWith(OrigIVI, PHI);
1330}
1331
1332/// Try to find redundant insertvalue instructions, like the following ones:
1333/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
1334/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
1335/// Here the second instruction inserts values at the same indices, as the
1336/// first one, making the first one redundant.
1337/// It should be transformed to:
1338/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
1341 I.getAggregateOperand(), I.getInsertedValueOperand(), I.getIndices(),
1342 SQ.getWithInstruction(&I)))
1343 return replaceInstUsesWith(I, V);
1344
1345 bool IsRedundant = false;
1346 ArrayRef<unsigned int> FirstIndices = I.getIndices();
1347
1348 // If there is a chain of insertvalue instructions (each of them except the
1349 // last one has only one use and it's another insertvalue insn from this
1350 // chain), check if any of the 'children' uses the same indices as the first
1351 // instruction. In this case, the first one is redundant.
1352 Value *V = &I;
1353 unsigned Depth = 0;
1354 while (V->hasOneUse() && Depth < 10) {
1355 User *U = V->user_back();
1356 auto UserInsInst = dyn_cast<InsertValueInst>(U);
1357 if (!UserInsInst || U->getOperand(0) != V)
1358 break;
1359 if (UserInsInst->getIndices() == FirstIndices) {
1360 IsRedundant = true;
1361 break;
1362 }
1363 V = UserInsInst;
1364 Depth++;
1365 }
1366
1367 if (IsRedundant)
1368 return replaceInstUsesWith(I, I.getOperand(0));
1369
1371 return NewI;
1372
1373 return nullptr;
1374}
1375
1377 // Can not analyze scalable type, the number of elements is not a compile-time
1378 // constant.
1380 return false;
1381
1382 int MaskSize = Shuf.getShuffleMask().size();
1383 int VecSize =
1384 cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements();
1385
1386 // A vector select does not change the size of the operands.
1387 if (MaskSize != VecSize)
1388 return false;
1389
1390 // Each mask element must be undefined or choose a vector element from one of
1391 // the source operands without crossing vector lanes.
1392 for (int i = 0; i != MaskSize; ++i) {
1393 int Elt = Shuf.getMaskValue(i);
1394 if (Elt != -1 && Elt != i && Elt != i + VecSize)
1395 return false;
1396 }
1397
1398 return true;
1399}
1400
1401/// Turn a chain of inserts that splats a value into an insert + shuffle:
1402/// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
1403/// shufflevector(insertelt(X, %k, 0), poison, zero)
1405 // We are interested in the last insert in a chain. So if this insert has a
1406 // single user and that user is an insert, bail.
1407 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
1408 return nullptr;
1409
1410 VectorType *VecTy = InsElt.getType();
1411 // Can not handle scalable type, the number of elements is not a compile-time
1412 // constant.
1413 if (isa<ScalableVectorType>(VecTy))
1414 return nullptr;
1415 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1416
1417 // Do not try to do this for a one-element vector, since that's a nop,
1418 // and will cause an inf-loop.
1419 if (NumElements == 1)
1420 return nullptr;
1421
1422 Value *SplatVal = InsElt.getOperand(1);
1423 InsertElementInst *CurrIE = &InsElt;
1424 SmallBitVector ElementPresent(NumElements, false);
1425 InsertElementInst *FirstIE = nullptr;
1426
1427 // Walk the chain backwards, keeping track of which indices we inserted into,
1428 // until we hit something that isn't an insert of the splatted value.
1429 while (CurrIE) {
1430 auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
1431 if (!Idx || CurrIE->getOperand(1) != SplatVal)
1432 return nullptr;
1433
1434 auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
1435 // Check none of the intermediate steps have any additional uses, except
1436 // for the root insertelement instruction, which can be re-used, if it
1437 // inserts at position 0.
1438 if (CurrIE != &InsElt &&
1439 (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
1440 return nullptr;
1441
1442 ElementPresent[Idx->getZExtValue()] = true;
1443 FirstIE = CurrIE;
1444 CurrIE = NextIE;
1445 }
1446
1447 // If this is just a single insertelement (not a sequence), we are done.
1448 if (FirstIE == &InsElt)
1449 return nullptr;
1450
1451 // If we are not inserting into a poison vector, make sure we've seen an
1452 // insert into every element.
1453 // TODO: If the base vector is not undef, it might be better to create a splat
1454 // and then a select-shuffle (blend) with the base vector.
1455 if (!match(FirstIE->getOperand(0), m_Poison()))
1456 if (!ElementPresent.all())
1457 return nullptr;
1458
1459 // Create the insert + shuffle.
1460 Type *Int64Ty = Type::getInt64Ty(InsElt.getContext());
1461 PoisonValue *PoisonVec = PoisonValue::get(VecTy);
1462 Constant *Zero = ConstantInt::get(Int64Ty, 0);
1463 if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
1464 FirstIE = InsertElementInst::Create(PoisonVec, SplatVal, Zero, "",
1465 InsElt.getIterator());
1466
1467 // Splat from element 0, but replace absent elements with poison in the mask.
1468 SmallVector<int, 16> Mask(NumElements, 0);
1469 for (unsigned i = 0; i != NumElements; ++i)
1470 if (!ElementPresent[i])
1471 Mask[i] = -1;
1472
1473 return new ShuffleVectorInst(FirstIE, Mask);
1474}
1475
1476/// Try to fold an insert element into an existing splat shuffle by changing
1477/// the shuffle's mask to include the index of this insert element.
1479 // Check if the vector operand of this insert is a canonical splat shuffle.
1480 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1481 if (!Shuf || !Shuf->isZeroEltSplat())
1482 return nullptr;
1483
1484 // Bail out early if shuffle is scalable type. The number of elements in
1485 // shuffle mask is unknown at compile-time.
1486 if (isa<ScalableVectorType>(Shuf->getType()))
1487 return nullptr;
1488
1489 // Check for a constant insertion index.
1490 uint64_t IdxC;
1491 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1492 return nullptr;
1493
1494 // Check if the splat shuffle's input is the same as this insert's scalar op.
1495 Value *X = InsElt.getOperand(1);
1496 Value *Op0 = Shuf->getOperand(0);
1497 if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt())))
1498 return nullptr;
1499
1500 // Replace the shuffle mask element at the index of this insert with a zero.
1501 // For example:
1502 // inselt (shuf (inselt undef, X, 0), _, <0,undef,0,undef>), X, 1
1503 // --> shuf (inselt undef, X, 0), poison, <0,0,0,undef>
1504 unsigned NumMaskElts =
1505 cast<FixedVectorType>(Shuf->getType())->getNumElements();
1506 SmallVector<int, 16> NewMask(NumMaskElts);
1507 for (unsigned i = 0; i != NumMaskElts; ++i)
1508 NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i);
1509
1510 return new ShuffleVectorInst(Op0, NewMask);
1511}
1512
1513/// Try to fold an extract+insert element into an existing identity shuffle by
1514/// changing the shuffle's mask to include the index of this insert element.
1516 // Check if the vector operand of this insert is an identity shuffle.
1517 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1518 if (!Shuf || !match(Shuf->getOperand(1), m_Poison()) ||
1519 !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
1520 return nullptr;
1521
1522 // Bail out early if shuffle is scalable type. The number of elements in
1523 // shuffle mask is unknown at compile-time.
1524 if (isa<ScalableVectorType>(Shuf->getType()))
1525 return nullptr;
1526
1527 // Check for a constant insertion index.
1528 uint64_t IdxC;
1529 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1530 return nullptr;
1531
1532 // Check if this insert's scalar op is extracted from the identity shuffle's
1533 // input vector.
1534 Value *Scalar = InsElt.getOperand(1);
1535 Value *X = Shuf->getOperand(0);
1536 if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC))))
1537 return nullptr;
1538
1539 // Replace the shuffle mask element at the index of this extract+insert with
1540 // that same index value.
1541 // For example:
1542 // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask'
1543 unsigned NumMaskElts =
1544 cast<FixedVectorType>(Shuf->getType())->getNumElements();
1545 SmallVector<int, 16> NewMask(NumMaskElts);
1546 ArrayRef<int> OldMask = Shuf->getShuffleMask();
1547 for (unsigned i = 0; i != NumMaskElts; ++i) {
1548 if (i != IdxC) {
1549 // All mask elements besides the inserted element remain the same.
1550 NewMask[i] = OldMask[i];
1551 } else if (OldMask[i] == (int)IdxC) {
1552 // If the mask element was already set, there's nothing to do
1553 // (demanded elements analysis may unset it later).
1554 return nullptr;
1555 } else {
1556 assert(OldMask[i] == PoisonMaskElem &&
1557 "Unexpected shuffle mask element for identity shuffle");
1558 NewMask[i] = IdxC;
1559 }
1560 }
1561
1562 return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask);
1563}
1564
1565/// If we have an insertelement instruction feeding into another insertelement
1566/// and the 2nd is inserting a constant into the vector, canonicalize that
1567/// constant insertion before the insertion of a variable:
1568///
1569/// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
1570/// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
1571///
1572/// This has the potential of eliminating the 2nd insertelement instruction
1573/// via constant folding of the scalar constant into a vector constant.
1575 InstCombiner::BuilderTy &Builder) {
1576 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
1577 if (!InsElt1 || !InsElt1->hasOneUse())
1578 return nullptr;
1579
1580 Value *X, *Y;
1581 Constant *ScalarC;
1582 ConstantInt *IdxC1, *IdxC2;
1583 if (match(InsElt1->getOperand(0), m_Value(X)) &&
1584 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
1585 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
1586 match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
1587 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
1588 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
1589 return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
1590 }
1591
1592 return nullptr;
1593}
1594
1595/// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
1596/// --> shufflevector X, CVec', Mask'
1598 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
1599 // Bail out if the parent has more than one use. In that case, we'd be
1600 // replacing the insertelt with a shuffle, and that's not a clear win.
1601 if (!Inst || !Inst->hasOneUse())
1602 return nullptr;
1603 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
1604 // The shuffle must have a constant vector operand. The insertelt must have
1605 // a constant scalar being inserted at a constant position in the vector.
1606 Constant *ShufConstVec, *InsEltScalar;
1607 uint64_t InsEltIndex;
1608 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
1609 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
1610 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
1611 return nullptr;
1612
1613 // Adding an element to an arbitrary shuffle could be expensive, but a
1614 // shuffle that selects elements from vectors without crossing lanes is
1615 // assumed cheap.
1616 // If we're just adding a constant into that shuffle, it will still be
1617 // cheap.
1618 if (!isShuffleEquivalentToSelect(*Shuf))
1619 return nullptr;
1620
1621 // From the above 'select' check, we know that the mask has the same number
1622 // of elements as the vector input operands. We also know that each constant
1623 // input element is used in its lane and can not be used more than once by
1624 // the shuffle. Therefore, replace the constant in the shuffle's constant
1625 // vector with the insertelt constant. Replace the constant in the shuffle's
1626 // mask vector with the insertelt index plus the length of the vector
1627 // (because the constant vector operand of a shuffle is always the 2nd
1628 // operand).
1629 ArrayRef<int> Mask = Shuf->getShuffleMask();
1630 unsigned NumElts = Mask.size();
1631 SmallVector<Constant *, 16> NewShufElts(NumElts);
1632 SmallVector<int, 16> NewMaskElts(NumElts);
1633 for (unsigned I = 0; I != NumElts; ++I) {
1634 if (I == InsEltIndex) {
1635 NewShufElts[I] = InsEltScalar;
1636 NewMaskElts[I] = InsEltIndex + NumElts;
1637 } else {
1638 // Copy over the existing values.
1639 NewShufElts[I] = ShufConstVec->getAggregateElement(I);
1640 NewMaskElts[I] = Mask[I];
1641 }
1642
1643 // Bail if we failed to find an element.
1644 if (!NewShufElts[I])
1645 return nullptr;
1646 }
1647
1648 // Create new operands for a shuffle that includes the constant of the
1649 // original insertelt. The old shuffle will be dead now.
1650 return new ShuffleVectorInst(Shuf->getOperand(0),
1651 ConstantVector::get(NewShufElts), NewMaskElts);
1652 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
1653 // Transform sequences of insertelements ops with constant data/indexes into
1654 // a single shuffle op.
1655 // Can not handle scalable type, the number of elements needed to create
1656 // shuffle mask is not a compile-time constant.
1657 if (isa<ScalableVectorType>(InsElt.getType()))
1658 return nullptr;
1659 unsigned NumElts =
1660 cast<FixedVectorType>(InsElt.getType())->getNumElements();
1661
1662 uint64_t InsertIdx[2];
1663 Constant *Val[2];
1664 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
1665 !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
1666 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
1667 !match(IEI->getOperand(1), m_Constant(Val[1])))
1668 return nullptr;
1670 SmallVector<int, 16> Mask(NumElts);
1671 auto ValI = std::begin(Val);
1672 // Generate new constant vector and mask.
1673 // We have 2 values/masks from the insertelements instructions. Insert them
1674 // into new value/mask vectors.
1675 for (uint64_t I : InsertIdx) {
1676 if (!Values[I]) {
1677 Values[I] = *ValI;
1678 Mask[I] = NumElts + I;
1679 }
1680 ++ValI;
1681 }
1682 // Remaining values are filled with 'poison' values.
1683 for (unsigned I = 0; I < NumElts; ++I) {
1684 if (!Values[I]) {
1686 Mask[I] = I;
1687 }
1688 }
1689 // Create new operands for a shuffle that includes the constant of the
1690 // original insertelt.
1691 return new ShuffleVectorInst(IEI->getOperand(0),
1693 }
1694 return nullptr;
1695}
1696
1697/// If both the base vector and the inserted element are extended from the same
1698/// type, do the insert element in the narrow source type followed by extend.
1699/// TODO: This can be extended to include other cast opcodes, but particularly
1700/// if we create a wider insertelement, make sure codegen is not harmed.
1702 InstCombiner::BuilderTy &Builder) {
1703 // We are creating a vector extend. If the original vector extend has another
1704 // use, that would mean we end up with 2 vector extends, so avoid that.
1705 // TODO: We could ease the use-clause to "if at least one op has one use"
1706 // (assuming that the source types match - see next TODO comment).
1707 Value *Vec = InsElt.getOperand(0);
1708 if (!Vec->hasOneUse())
1709 return nullptr;
1710
1711 Value *Scalar = InsElt.getOperand(1);
1712 Value *X, *Y;
1713 CastInst::CastOps CastOpcode;
1714 if (match(Vec, m_FPExt(m_Value(X))) && match(Scalar, m_FPExt(m_Value(Y))))
1715 CastOpcode = Instruction::FPExt;
1716 else if (match(Vec, m_SExt(m_Value(X))) && match(Scalar, m_SExt(m_Value(Y))))
1717 CastOpcode = Instruction::SExt;
1718 else if (match(Vec, m_ZExt(m_Value(X))) && match(Scalar, m_ZExt(m_Value(Y))))
1719 CastOpcode = Instruction::ZExt;
1720 else
1721 return nullptr;
1722
1723 // TODO: We can allow mismatched types by creating an intermediate cast.
1724 if (X->getType()->getScalarType() != Y->getType())
1725 return nullptr;
1726
1727 // inselt (ext X), (ext Y), Index --> ext (inselt X, Y, Index)
1728 Value *NewInsElt = Builder.CreateInsertElement(X, Y, InsElt.getOperand(2));
1729 return CastInst::Create(CastOpcode, NewInsElt, InsElt.getType());
1730}
1731
1732/// If we are inserting 2 halves of a value into adjacent elements of a vector,
1733/// try to convert to a single insert with appropriate bitcasts.
1735 bool IsBigEndian,
1736 InstCombiner::BuilderTy &Builder) {
1737 Value *VecOp = InsElt.getOperand(0);
1738 Value *ScalarOp = InsElt.getOperand(1);
1739 Value *IndexOp = InsElt.getOperand(2);
1740
1741 // Pattern depends on endian because we expect lower index is inserted first.
1742 // Big endian:
1743 // inselt (inselt BaseVec, (trunc (lshr X, BW/2), Index0), (trunc X), Index1
1744 // Little endian:
1745 // inselt (inselt BaseVec, (trunc X), Index0), (trunc (lshr X, BW/2)), Index1
1746 // Note: It is not safe to do this transform with an arbitrary base vector
1747 // because the bitcast of that vector to fewer/larger elements could
1748 // allow poison to spill into an element that was not poison before.
1749 // TODO: Detect smaller fractions of the scalar.
1750 // TODO: One-use checks are conservative.
1751 auto *VTy = dyn_cast<FixedVectorType>(InsElt.getType());
1752 Value *Scalar0, *BaseVec;
1753 uint64_t Index0, Index1;
1754 if (!VTy || (VTy->getNumElements() & 1) ||
1755 !match(IndexOp, m_ConstantInt(Index1)) ||
1756 !match(VecOp, m_InsertElt(m_Value(BaseVec), m_Value(Scalar0),
1757 m_ConstantInt(Index0))) ||
1758 !match(BaseVec, m_Undef()))
1759 return nullptr;
1760
1761 // The first insert must be to the index one less than this one, and
1762 // the first insert must be to an even index.
1763 if (Index0 + 1 != Index1 || Index0 & 1)
1764 return nullptr;
1765
1766 // For big endian, the high half of the value should be inserted first.
1767 // For little endian, the low half of the value should be inserted first.
1768 Value *X;
1769 uint64_t ShAmt;
1770 if (IsBigEndian) {
1771 if (!match(ScalarOp, m_Trunc(m_Value(X))) ||
1772 !match(Scalar0, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
1773 return nullptr;
1774 } else {
1775 if (!match(Scalar0, m_Trunc(m_Value(X))) ||
1776 !match(ScalarOp, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
1777 return nullptr;
1778 }
1779
1780 Type *SrcTy = X->getType();
1781 unsigned ScalarWidth = SrcTy->getScalarSizeInBits();
1782 unsigned VecEltWidth = VTy->getScalarSizeInBits();
1783 if (ScalarWidth != VecEltWidth * 2 || ShAmt != VecEltWidth)
1784 return nullptr;
1785
1786 // Bitcast the base vector to a vector type with the source element type.
1787 Type *CastTy = FixedVectorType::get(SrcTy, VTy->getNumElements() / 2);
1788 Value *CastBaseVec = Builder.CreateBitCast(BaseVec, CastTy);
1789
1790 // Scale the insert index for a vector with half as many elements.
1791 // bitcast (inselt (bitcast BaseVec), X, NewIndex)
1792 uint64_t NewIndex = IsBigEndian ? Index1 / 2 : Index0 / 2;
1793 Value *NewInsert = Builder.CreateInsertElement(CastBaseVec, X, NewIndex);
1794 return new BitCastInst(NewInsert, VTy);
1795}
1796
1798 Value *VecOp = IE.getOperand(0);
1799 Value *ScalarOp = IE.getOperand(1);
1800 Value *IdxOp = IE.getOperand(2);
1801
1802 if (auto *V = simplifyInsertElementInst(
1803 VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
1804 return replaceInstUsesWith(IE, V);
1805
1806 // Canonicalize type of constant indices to i64 to simplify CSE
1807 if (auto *IndexC = dyn_cast<ConstantInt>(IdxOp)) {
1808 if (auto *NewIdx = getPreferredVectorIndex(IndexC))
1809 return replaceOperand(IE, 2, NewIdx);
1810
1811 Value *BaseVec, *OtherScalar;
1812 uint64_t OtherIndexVal;
1813 if (match(VecOp, m_OneUse(m_InsertElt(m_Value(BaseVec),
1814 m_Value(OtherScalar),
1815 m_ConstantInt(OtherIndexVal)))) &&
1816 !isa<Constant>(OtherScalar) && OtherIndexVal > IndexC->getZExtValue()) {
1817 Value *NewIns = Builder.CreateInsertElement(BaseVec, ScalarOp, IdxOp);
1818 return InsertElementInst::Create(NewIns, OtherScalar,
1819 Builder.getInt64(OtherIndexVal));
1820 }
1821 }
1822
1823 // If the scalar is bitcast and inserted into undef, do the insert in the
1824 // source type followed by bitcast.
1825 // TODO: Generalize for insert into any constant, not just undef?
1826 Value *ScalarSrc;
1827 if (match(VecOp, m_Undef()) &&
1828 match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) &&
1829 (ScalarSrc->getType()->isIntegerTy() ||
1830 ScalarSrc->getType()->isFloatingPointTy())) {
1831 // inselt undef, (bitcast ScalarSrc), IdxOp -->
1832 // bitcast (inselt undef, ScalarSrc, IdxOp)
1833 Type *ScalarTy = ScalarSrc->getType();
1834 Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount());
1835 Constant *NewUndef = isa<PoisonValue>(VecOp) ? PoisonValue::get(VecTy)
1836 : UndefValue::get(VecTy);
1837 Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp);
1838 return new BitCastInst(NewInsElt, IE.getType());
1839 }
1840
1841 // If the vector and scalar are both bitcast from the same element type, do
1842 // the insert in that source type followed by bitcast.
1843 Value *VecSrc;
1844 if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
1845 match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
1846 (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
1847 VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
1848 cast<VectorType>(VecSrc->getType())->getElementType() ==
1849 ScalarSrc->getType()) {
1850 // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
1851 // bitcast (inselt VecSrc, ScalarSrc, IdxOp)
1852 Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
1853 return new BitCastInst(NewInsElt, IE.getType());
1854 }
1855
1856 // If the inserted element was extracted from some other fixed-length vector
1857 // and both indexes are valid constants, try to turn this into a shuffle.
1858 // Can not handle scalable vector type, the number of elements needed to
1859 // create shuffle mask is not a compile-time constant.
1860 uint64_t InsertedIdx, ExtractedIdx;
1861 Value *ExtVecOp;
1862 if (isa<FixedVectorType>(IE.getType()) &&
1863 match(IdxOp, m_ConstantInt(InsertedIdx)) &&
1864 match(ScalarOp,
1865 m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) &&
1866 isa<FixedVectorType>(ExtVecOp->getType()) &&
1867 ExtractedIdx <
1868 cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) {
1869 // TODO: Looking at the user(s) to determine if this insert is a
1870 // fold-to-shuffle opportunity does not match the usual instcombine
1871 // constraints. We should decide if the transform is worthy based only
1872 // on this instruction and its operands, but that may not work currently.
1873 //
1874 // Here, we are trying to avoid creating shuffles before reaching
1875 // the end of a chain of extract-insert pairs. This is complicated because
1876 // we do not generally form arbitrary shuffle masks in instcombine
1877 // (because those may codegen poorly), but collectShuffleElements() does
1878 // exactly that.
1879 //
1880 // The rules for determining what is an acceptable target-independent
1881 // shuffle mask are fuzzy because they evolve based on the backend's
1882 // capabilities and real-world impact.
1883 auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
1884 if (!Insert.hasOneUse())
1885 return true;
1886 auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
1887 if (!InsertUser)
1888 return true;
1889 return false;
1890 };
1891
1892 // Try to form a shuffle from a chain of extract-insert ops.
1893 if (isShuffleRootCandidate(IE)) {
1894 bool Rerun = true;
1895 while (Rerun) {
1896 Rerun = false;
1897
1899 ShuffleOps LR =
1900 collectShuffleElements(&IE, Mask, nullptr, *this, Rerun);
1901
1902 // The proposed shuffle may be trivial, in which case we shouldn't
1903 // perform the combine.
1904 if (LR.first != &IE && LR.second != &IE) {
1905 // We now have a shuffle of LHS, RHS, Mask.
1906 if (LR.second == nullptr)
1907 LR.second = PoisonValue::get(LR.first->getType());
1908 return new ShuffleVectorInst(LR.first, LR.second, Mask);
1909 }
1910 }
1911 }
1912 }
1913
1914 if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) {
1915 unsigned VWidth = VecTy->getNumElements();
1916 APInt PoisonElts(VWidth, 0);
1917 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1918 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask,
1919 PoisonElts)) {
1920 if (V != &IE)
1921 return replaceInstUsesWith(IE, V);
1922 return &IE;
1923 }
1924 }
1925
1927 return Shuf;
1928
1929 if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
1930 return NewInsElt;
1931
1932 if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE))
1933 return Broadcast;
1934
1936 return Splat;
1937
1938 if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE))
1939 return IdentityShuf;
1940
1941 if (Instruction *Ext = narrowInsElt(IE, Builder))
1942 return Ext;
1943
1944 if (Instruction *Ext = foldTruncInsEltPair(IE, DL.isBigEndian(), Builder))
1945 return Ext;
1946
1947 return nullptr;
1948}
1949
1950/// Return true if we can evaluate the specified expression tree if the vector
1951/// elements were shuffled in a different order.
1953 unsigned Depth = 5) {
1954 // We can always reorder the elements of a constant.
1955 if (isa<Constant>(V))
1956 return true;
1957
1958 // We won't reorder vector arguments. No IPO here.
1960 if (!I) return false;
1961
1962 // Two users may expect different orders of the elements. Don't try it.
1963 if (!I->hasOneUse())
1964 return false;
1965
1966 if (Depth == 0) return false;
1967
1968 switch (I->getOpcode()) {
1969 case Instruction::UDiv:
1970 case Instruction::SDiv:
1971 case Instruction::URem:
1972 case Instruction::SRem:
1973 // Propagating an undefined shuffle mask element to integer div/rem is not
1974 // allowed because those opcodes can create immediate undefined behavior
1975 // from an undefined element in an operand.
1976 if (llvm::is_contained(Mask, -1))
1977 return false;
1978 [[fallthrough]];
1979 case Instruction::Add:
1980 case Instruction::FAdd:
1981 case Instruction::Sub:
1982 case Instruction::FSub:
1983 case Instruction::Mul:
1984 case Instruction::FMul:
1985 case Instruction::FDiv:
1986 case Instruction::FRem:
1987 case Instruction::Shl:
1988 case Instruction::LShr:
1989 case Instruction::AShr:
1990 case Instruction::And:
1991 case Instruction::Or:
1992 case Instruction::Xor:
1993 case Instruction::ICmp:
1994 case Instruction::FCmp:
1995 case Instruction::Trunc:
1996 case Instruction::ZExt:
1997 case Instruction::SExt:
1998 case Instruction::FPToUI:
1999 case Instruction::FPToSI:
2000 case Instruction::UIToFP:
2001 case Instruction::SIToFP:
2002 case Instruction::FPTrunc:
2003 case Instruction::FPExt:
2004 case Instruction::GetElementPtr: {
2005 // Bail out if we would create longer vector ops. We could allow creating
2006 // longer vector ops, but that may result in more expensive codegen.
2007 Type *ITy = I->getType();
2008 if (ITy->isVectorTy() &&
2009 Mask.size() > cast<FixedVectorType>(ITy)->getNumElements())
2010 return false;
2011 for (Value *Operand : I->operands()) {
2012 if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
2013 return false;
2014 }
2015 return true;
2016 }
2017 case Instruction::InsertElement: {
2018 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
2019 if (!CI) return false;
2020 int ElementNumber = CI->getLimitedValue();
2021
2022 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
2023 // can't put an element into multiple indices.
2024 bool SeenOnce = false;
2025 for (int I : Mask) {
2026 if (I == ElementNumber) {
2027 if (SeenOnce)
2028 return false;
2029 SeenOnce = true;
2030 }
2031 }
2032 return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
2033 }
2034 }
2035 return false;
2036}
2037
2038/// Rebuild a new instruction just like 'I' but with the new operands given.
2039/// In the event of type mismatch, the type of the operands is correct.
2041 IRBuilderBase &Builder) {
2042 Builder.SetInsertPoint(I);
2043 switch (I->getOpcode()) {
2044 case Instruction::Add:
2045 case Instruction::FAdd:
2046 case Instruction::Sub:
2047 case Instruction::FSub:
2048 case Instruction::Mul:
2049 case Instruction::FMul:
2050 case Instruction::UDiv:
2051 case Instruction::SDiv:
2052 case Instruction::FDiv:
2053 case Instruction::URem:
2054 case Instruction::SRem:
2055 case Instruction::FRem:
2056 case Instruction::Shl:
2057 case Instruction::LShr:
2058 case Instruction::AShr:
2059 case Instruction::And:
2060 case Instruction::Or:
2061 case Instruction::Xor: {
2063 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
2064 Value *New = Builder.CreateBinOp(cast<BinaryOperator>(I)->getOpcode(),
2065 NewOps[0], NewOps[1]);
2066 if (auto *NewI = dyn_cast<Instruction>(New)) {
2068 NewI->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
2069 NewI->setHasNoSignedWrap(BO->hasNoSignedWrap());
2070 }
2072 NewI->setIsExact(BO->isExact());
2073 }
2074 if (isa<FPMathOperator>(BO))
2075 NewI->copyFastMathFlags(I);
2076 }
2077 return New;
2078 }
2079 case Instruction::ICmp: {
2080 assert(NewOps.size() == 2 && "icmp with #ops != 2");
2081 Value *New = Builder.CreateICmp(cast<ICmpInst>(I)->getPredicate(),
2082 NewOps[0], NewOps[1]);
2083 if (auto *NewI = dyn_cast<Instruction>(New))
2084 NewI->copyIRFlags(I);
2085 return New;
2086 }
2087 case Instruction::FCmp:
2088 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
2089 return Builder.CreateFCmpFMF(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
2090 NewOps[1], I);
2091 case Instruction::Trunc:
2092 case Instruction::ZExt:
2093 case Instruction::SExt:
2094 case Instruction::FPToUI:
2095 case Instruction::FPToSI:
2096 case Instruction::UIToFP:
2097 case Instruction::SIToFP:
2098 case Instruction::FPTrunc:
2099 case Instruction::FPExt: {
2100 // It's possible that the mask has a different number of elements from
2101 // the original cast. We recompute the destination type to match the mask.
2102 Type *DestTy = VectorType::get(
2103 I->getType()->getScalarType(),
2104 cast<VectorType>(NewOps[0]->getType())->getElementCount());
2105 assert(NewOps.size() == 1 && "cast with #ops != 1");
2106 Value *New =
2107 Builder.CreateCast(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy);
2108 if (auto *NewI = dyn_cast<Instruction>(New))
2109 NewI->copyIRFlags(I);
2110 return New;
2111 }
2112 case Instruction::GetElementPtr: {
2113 Value *Ptr = NewOps[0];
2114 ArrayRef<Value*> Idx = NewOps.slice(1);
2115 return Builder.CreateGEP(cast<GEPOperator>(I)->getSourceElementType(),
2116 Ptr, Idx, "",
2117 cast<GEPOperator>(I)->getNoWrapFlags());
2118 }
2119 }
2120 llvm_unreachable("failed to rebuild vector instructions");
2121}
2122
2124 IRBuilderBase &Builder) {
2125 // Mask.size() does not need to be equal to the number of vector elements.
2126
2127 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
2128 Type *EltTy = V->getType()->getScalarType();
2129
2130 if (isa<PoisonValue>(V))
2131 return PoisonValue::get(FixedVectorType::get(EltTy, Mask.size()));
2132
2133 if (match(V, m_Undef()))
2134 return UndefValue::get(FixedVectorType::get(EltTy, Mask.size()));
2135
2137 return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size()));
2138
2141 Mask);
2142
2144 switch (I->getOpcode()) {
2145 case Instruction::Add:
2146 case Instruction::FAdd:
2147 case Instruction::Sub:
2148 case Instruction::FSub:
2149 case Instruction::Mul:
2150 case Instruction::FMul:
2151 case Instruction::UDiv:
2152 case Instruction::SDiv:
2153 case Instruction::FDiv:
2154 case Instruction::URem:
2155 case Instruction::SRem:
2156 case Instruction::FRem:
2157 case Instruction::Shl:
2158 case Instruction::LShr:
2159 case Instruction::AShr:
2160 case Instruction::And:
2161 case Instruction::Or:
2162 case Instruction::Xor:
2163 case Instruction::ICmp:
2164 case Instruction::FCmp:
2165 case Instruction::Trunc:
2166 case Instruction::ZExt:
2167 case Instruction::SExt:
2168 case Instruction::FPToUI:
2169 case Instruction::FPToSI:
2170 case Instruction::UIToFP:
2171 case Instruction::SIToFP:
2172 case Instruction::FPTrunc:
2173 case Instruction::FPExt:
2174 case Instruction::Select:
2175 case Instruction::GetElementPtr: {
2177 bool NeedsRebuild =
2178 (Mask.size() !=
2179 cast<FixedVectorType>(I->getType())->getNumElements());
2180 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
2181 Value *V;
2182 // Recursively call evaluateInDifferentElementOrder on vector arguments
2183 // as well. E.g. GetElementPtr may have scalar operands even if the
2184 // return value is a vector, so we need to examine the operand type.
2185 if (I->getOperand(i)->getType()->isVectorTy())
2186 V = evaluateInDifferentElementOrder(I->getOperand(i), Mask, Builder);
2187 else
2188 V = I->getOperand(i);
2189 NewOps.push_back(V);
2190 NeedsRebuild |= (V != I->getOperand(i));
2191 }
2192 if (NeedsRebuild)
2193 return buildNew(I, NewOps, Builder);
2194 return I;
2195 }
2196 case Instruction::InsertElement: {
2197 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
2198
2199 // The insertelement was inserting at Element. Figure out which element
2200 // that becomes after shuffling. The answer is guaranteed to be unique
2201 // by CanEvaluateShuffled.
2202 bool Found = false;
2203 int Index = 0;
2204 for (int e = Mask.size(); Index != e; ++Index) {
2205 if (Mask[Index] == Element) {
2206 Found = true;
2207 break;
2208 }
2209 }
2210
2211 // If element is not in Mask, no need to handle the operand 1 (element to
2212 // be inserted). Just evaluate values in operand 0 according to Mask.
2213 if (!Found)
2214 return evaluateInDifferentElementOrder(I->getOperand(0), Mask, Builder);
2215
2216 Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask,
2217 Builder);
2218 Builder.SetInsertPoint(I);
2219 return Builder.CreateInsertElement(V, I->getOperand(1), Index);
2220 }
2221 }
2222 llvm_unreachable("failed to reorder elements of vector instruction!");
2223}
2224
2225// Returns true if the shuffle is extracting a contiguous range of values from
2226// LHS, for example:
2227// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
2228// Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
2229// Shuffles to: |EE|FF|GG|HH|
2230// +--+--+--+--+
2232 ArrayRef<int> Mask) {
2233 unsigned LHSElems =
2234 cast<FixedVectorType>(SVI.getOperand(0)->getType())->getNumElements();
2235 unsigned MaskElems = Mask.size();
2236 unsigned BegIdx = Mask.front();
2237 unsigned EndIdx = Mask.back();
2238 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
2239 return false;
2240 for (unsigned I = 0; I != MaskElems; ++I)
2241 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
2242 return false;
2243 return true;
2244}
2245
2246/// These are the ingredients in an alternate form binary operator as described
2247/// below.
2253 Value *V0 = nullptr, Value *V1 = nullptr) :
2254 Opcode(Opc), Op0(V0), Op1(V1) {}
2255 operator bool() const { return Opcode != 0; }
2256};
2257
2258/// Binops may be transformed into binops with different opcodes and operands.
2259/// Reverse the usual canonicalization to enable folds with the non-canonical
2260/// form of the binop. If a transform is possible, return the elements of the
2261/// new binop. If not, return invalid elements.
2263 Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
2264 Type *Ty = BO->getType();
2265 switch (BO->getOpcode()) {
2266 case Instruction::Shl: {
2267 // shl X, C --> mul X, (1 << C)
2268 Constant *C;
2269 if (match(BO1, m_ImmConstant(C))) {
2271 Instruction::Shl, ConstantInt::get(Ty, 1), C, DL);
2272 assert(ShlOne && "Constant folding of immediate constants failed");
2273 return {Instruction::Mul, BO0, ShlOne};
2274 }
2275 break;
2276 }
2277 case Instruction::Or: {
2278 // or disjoin X, C --> add X, C
2279 if (cast<PossiblyDisjointInst>(BO)->isDisjoint())
2280 return {Instruction::Add, BO0, BO1};
2281 break;
2282 }
2283 case Instruction::Sub:
2284 // sub 0, X --> mul X, -1
2285 if (match(BO0, m_ZeroInt()))
2286 return {Instruction::Mul, BO1, ConstantInt::getAllOnesValue(Ty)};
2287 break;
2288 default:
2289 break;
2290 }
2291 return {};
2292}
2293
2294/// A select shuffle of a select shuffle with a shared operand can be reduced
2295/// to a single select shuffle. This is an obvious improvement in IR, and the
2296/// backend is expected to lower select shuffles efficiently.
2298 assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
2299
2300 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2302 Shuf.getShuffleMask(Mask);
2303 unsigned NumElts = Mask.size();
2304
2305 // Canonicalize a select shuffle with common operand as Op1.
2306 auto *ShufOp = dyn_cast<ShuffleVectorInst>(Op0);
2307 if (ShufOp && ShufOp->isSelect() &&
2308 (ShufOp->getOperand(0) == Op1 || ShufOp->getOperand(1) == Op1)) {
2309 std::swap(Op0, Op1);
2311 }
2312
2313 ShufOp = dyn_cast<ShuffleVectorInst>(Op1);
2314 if (!ShufOp || !ShufOp->isSelect() ||
2315 (ShufOp->getOperand(0) != Op0 && ShufOp->getOperand(1) != Op0))
2316 return nullptr;
2317
2318 Value *X = ShufOp->getOperand(0), *Y = ShufOp->getOperand(1);
2320 ShufOp->getShuffleMask(Mask1);
2321 assert(Mask1.size() == NumElts && "Vector size changed with select shuffle");
2322
2323 // Canonicalize common operand (Op0) as X (first operand of first shuffle).
2324 if (Y == Op0) {
2325 std::swap(X, Y);
2327 }
2328
2329 // If the mask chooses from X (operand 0), it stays the same.
2330 // If the mask chooses from the earlier shuffle, the other mask value is
2331 // transferred to the combined select shuffle:
2332 // shuf X, (shuf X, Y, M1), M --> shuf X, Y, M'
2333 SmallVector<int, 16> NewMask(NumElts);
2334 for (unsigned i = 0; i != NumElts; ++i)
2335 NewMask[i] = Mask[i] < (signed)NumElts ? Mask[i] : Mask1[i];
2336
2337 // A select mask with undef elements might look like an identity mask.
2338 assert((ShuffleVectorInst::isSelectMask(NewMask, NumElts) ||
2339 ShuffleVectorInst::isIdentityMask(NewMask, NumElts)) &&
2340 "Unexpected shuffle mask");
2341 return new ShuffleVectorInst(X, Y, NewMask);
2342}
2343
2345 const SimplifyQuery &SQ) {
2346 assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
2347
2348 // Are we shuffling together some value and that same value after it has been
2349 // modified by a binop with a constant?
2350 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2351 Constant *C;
2352 bool Op0IsBinop;
2353 if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
2354 Op0IsBinop = true;
2355 else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
2356 Op0IsBinop = false;
2357 else
2358 return nullptr;
2359
2360 // The identity constant for a binop leaves a variable operand unchanged. For
2361 // a vector, this is a splat of something like 0, -1, or 1.
2362 // If there's no identity constant for this binop, we're done.
2363 auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
2364 BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
2365 Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
2366 if (!IdC)
2367 return nullptr;
2368
2369 Value *X = Op0IsBinop ? Op1 : Op0;
2370
2371 // Prevent folding in the case the non-binop operand might have NaN values.
2372 // If X can have NaN elements then we have that the floating point math
2373 // operation in the transformed code may not preserve the exact NaN
2374 // bit-pattern -- e.g. `fadd sNaN, 0.0 -> qNaN`.
2375 // This makes the transformation incorrect since the original program would
2376 // have preserved the exact NaN bit-pattern.
2377 // Avoid the folding if X can have NaN elements.
2378 bool IsFloatingPointTy =
2380 if (IsFloatingPointTy && !isKnownNeverNaN(X, SQ))
2381 return nullptr;
2382
2383 // Shuffle identity constants into the lanes that return the original value.
2384 // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
2385 // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
2386 // The existing binop constant vector remains in the same operand position.
2387 ArrayRef<int> Mask = Shuf.getShuffleMask();
2388 Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
2390
2391 bool MightCreatePoisonOrUB =
2393 (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
2394 if (MightCreatePoisonOrUB)
2395 NewC = InstCombiner::getSafeVectorConstantForBinop(BOpcode, NewC, true);
2396
2397 // shuf (bop X, C), X, M --> bop X, C'
2398 // shuf X, (bop X, C), M --> bop X, C'
2399 BinaryOperator *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
2400 NewBO->copyIRFlags(BO);
2401
2402 // Drop noinf FMF if X can be Inf. If X can have Inf elements and noinf FMF is
2403 // set, the transformation may generate poison where the original program
2404 // would preserve the Inf value.
2405 if (IsFloatingPointTy && NewBO->hasNoInfs() && !isKnownNeverInfinity(X, SQ))
2406 NewBO->setHasNoInfs(false);
2407
2408 // An undef shuffle mask element may propagate as an undef constant element in
2409 // the new binop. That would produce poison where the original code might not.
2410 // If we already made a safe constant, then there's no danger.
2411 if (is_contained(Mask, PoisonMaskElem) && !MightCreatePoisonOrUB)
2413 return NewBO;
2414}
2415
2416/// If we have an insert of a scalar to a non-zero element of an undefined
2417/// vector and then shuffle that value, that's the same as inserting to the zero
2418/// element and shuffling. Splatting from the zero element is recognized as the
2419/// canonical form of splat.
2421 InstCombiner::BuilderTy &Builder) {
2422 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2423 ArrayRef<int> Mask = Shuf.getShuffleMask();
2424 Value *X;
2425 uint64_t IndexC;
2426
2427 // Match a shuffle that is a splat to a non-zero element.
2429 m_ConstantInt(IndexC)))) ||
2430 !match(Op1, m_Poison()) || match(Mask, m_ZeroMask()) || IndexC == 0)
2431 return nullptr;
2432
2433 // Insert into element 0 of a poison vector.
2434 PoisonValue *PoisonVec = PoisonValue::get(Shuf.getType());
2435 Value *NewIns = Builder.CreateInsertElement(PoisonVec, X, (uint64_t)0);
2436
2437 // Splat from element 0. Any mask element that is poison remains poison.
2438 // For example:
2439 // shuf (inselt poison, X, 2), _, <2,2,undef>
2440 // --> shuf (inselt poison, X, 0), poison, <0,0,undef>
2441 unsigned NumMaskElts =
2442 cast<FixedVectorType>(Shuf.getType())->getNumElements();
2443 SmallVector<int, 16> NewMask(NumMaskElts, 0);
2444 for (unsigned i = 0; i != NumMaskElts; ++i)
2445 if (Mask[i] == PoisonMaskElem)
2446 NewMask[i] = Mask[i];
2447
2448 return new ShuffleVectorInst(NewIns, NewMask);
2449}
2450
2451/// Try to fold shuffles that are the equivalent of a vector select.
2453 if (!Shuf.isSelect())
2454 return nullptr;
2455
2456 // Canonicalize to choose from operand 0 first unless operand 1 is
2457 // undefined/zero. Commuting undef/zero to operand 0 conflicts with other
2458 // canonicalization.
2459 unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2460 if (!match(Shuf.getOperand(1), m_Undef()) &&
2461 !match(Shuf.getOperand(1), m_CombineOr(m_Zero(), m_AnyZeroFP())) &&
2462 Shuf.getMaskValue(0) >= (int)NumElts) {
2463 // TODO: Can we assert that both operands of a shuffle-select are not undef
2464 // (otherwise, it would have been folded by instsimplify?
2465 Shuf.commute();
2466 return &Shuf;
2467 }
2468
2470 return I;
2471
2473 Shuf, getSimplifyQuery().getWithInstruction(&Shuf)))
2474 return I;
2475
2476 BinaryOperator *B0, *B1;
2477 if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
2478 !match(Shuf.getOperand(1), m_BinOp(B1)))
2479 return nullptr;
2480
2481 // If one operand is "0 - X", allow that to be viewed as "X * -1"
2482 // (ConstantsAreOp1) by getAlternateBinop below. If the neg is not paired
2483 // with a multiply, we will exit because C0/C1 will not be set.
2484 Value *X, *Y;
2485 Constant *C0 = nullptr, *C1 = nullptr;
2486 bool ConstantsAreOp1;
2487 if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
2489 ConstantsAreOp1 = false;
2490 else if (match(B0, m_CombineOr(m_BinOp(m_Value(X), m_Constant(C0)),
2491 m_Neg(m_Value(X)))) &&
2493 m_Neg(m_Value(Y)))))
2494 ConstantsAreOp1 = true;
2495 else
2496 return nullptr;
2497
2498 // We need matching binops to fold the lanes together.
2499 BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
2500 BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
2501 bool DropNSW = false;
2502 if (ConstantsAreOp1 && Opc0 != Opc1) {
2503 // TODO: We drop "nsw" if shift is converted into multiply because it may
2504 // not be correct when the shift amount is BitWidth - 1. We could examine
2505 // each vector element to determine if it is safe to keep that flag.
2506 if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
2507 DropNSW = true;
2508 if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
2509 assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
2510 Opc0 = AltB0.Opcode;
2511 C0 = cast<Constant>(AltB0.Op1);
2512 } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
2513 assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
2514 Opc1 = AltB1.Opcode;
2515 C1 = cast<Constant>(AltB1.Op1);
2516 }
2517 }
2518
2519 if (Opc0 != Opc1 || !C0 || !C1)
2520 return nullptr;
2521
2522 // The opcodes must be the same. Use a new name to make that clear.
2523 BinaryOperator::BinaryOps BOpc = Opc0;
2524
2525 // Select the constant elements needed for the single binop.
2526 ArrayRef<int> Mask = Shuf.getShuffleMask();
2528
2529 // We are moving a binop after a shuffle. When a shuffle has an undefined
2530 // mask element, the result is undefined, but it is not poison or undefined
2531 // behavior. That is not necessarily true for div/rem/shift.
2532 bool MightCreatePoisonOrUB =
2535 if (MightCreatePoisonOrUB)
2537 ConstantsAreOp1);
2538
2539 Value *V;
2540 if (X == Y) {
2541 // Remove a binop and the shuffle by rearranging the constant:
2542 // shuffle (op V, C0), (op V, C1), M --> op V, C'
2543 // shuffle (op C0, V), (op C1, V), M --> op C', V
2544 V = X;
2545 } else {
2546 // If there are 2 different variable operands, we must create a new shuffle
2547 // (select) first, so check uses to ensure that we don't end up with more
2548 // instructions than we started with.
2549 if (!B0->hasOneUse() && !B1->hasOneUse())
2550 return nullptr;
2551
2552 // If we use the original shuffle mask and op1 is *variable*, we would be
2553 // putting an undef into operand 1 of div/rem/shift. This is either UB or
2554 // poison. We do not have to guard against UB when *constants* are op1
2555 // because safe constants guarantee that we do not overflow sdiv/srem (and
2556 // there's no danger for other opcodes).
2557 // TODO: To allow this case, create a new shuffle mask with no undefs.
2558 if (MightCreatePoisonOrUB && !ConstantsAreOp1)
2559 return nullptr;
2560
2561 // Note: In general, we do not create new shuffles in InstCombine because we
2562 // do not know if a target can lower an arbitrary shuffle optimally. In this
2563 // case, the shuffle uses the existing mask, so there is no additional risk.
2564
2565 // Select the variable vectors first, then perform the binop:
2566 // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
2567 // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
2568 V = Builder.CreateShuffleVector(X, Y, Mask);
2569 }
2570
2571 Value *NewBO = ConstantsAreOp1 ? Builder.CreateBinOp(BOpc, V, NewC) :
2572 Builder.CreateBinOp(BOpc, NewC, V);
2573
2574 // Flags are intersected from the 2 source binops. But there are 2 exceptions:
2575 // 1. If we changed an opcode, poison conditions might have changed.
2576 // 2. If the shuffle had undef mask elements, the new binop might have undefs
2577 // where the original code did not. But if we already made a safe constant,
2578 // then there's no danger.
2579 if (auto *NewI = dyn_cast<Instruction>(NewBO)) {
2580 NewI->copyIRFlags(B0);
2581 NewI->andIRFlags(B1);
2582 if (DropNSW)
2583 NewI->setHasNoSignedWrap(false);
2584 if (is_contained(Mask, PoisonMaskElem) && !MightCreatePoisonOrUB)
2585 NewI->dropPoisonGeneratingFlags();
2586 }
2587 return replaceInstUsesWith(Shuf, NewBO);
2588}
2589
2590/// Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
2591/// Example (little endian):
2592/// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8>
2594 bool IsBigEndian) {
2595 // This must be a bitcasted shuffle of 1 vector integer operand.
2596 Type *DestType = Shuf.getType();
2597 Value *X;
2598 if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) ||
2599 !match(Shuf.getOperand(1), m_Poison()) || !DestType->isIntOrIntVectorTy())
2600 return nullptr;
2601
2602 // The source type must have the same number of elements as the shuffle,
2603 // and the source element type must be larger than the shuffle element type.
2604 Type *SrcType = X->getType();
2605 if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() ||
2606 cast<FixedVectorType>(SrcType)->getNumElements() !=
2607 cast<FixedVectorType>(DestType)->getNumElements() ||
2608 SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0)
2609 return nullptr;
2610
2611 assert(Shuf.changesLength() && !Shuf.increasesLength() &&
2612 "Expected a shuffle that decreases length");
2613
2614 // Last, check that the mask chooses the correct low bits for each narrow
2615 // element in the result.
2616 uint64_t TruncRatio =
2617 SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits();
2618 ArrayRef<int> Mask = Shuf.getShuffleMask();
2619 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
2620 if (Mask[i] == PoisonMaskElem)
2621 continue;
2622 uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio;
2623 assert(LSBIndex <= INT32_MAX && "Overflowed 32-bits");
2624 if (Mask[i] != (int)LSBIndex)
2625 return nullptr;
2626 }
2627
2628 return new TruncInst(X, DestType);
2629}
2630
2631/// Match a shuffle-select-shuffle pattern where the shuffles are widening and
2632/// narrowing (concatenating with poison and extracting back to the original
2633/// length). This allows replacing the wide select with a narrow select.
2635 InstCombiner::BuilderTy &Builder) {
2636 // This must be a narrowing identity shuffle. It extracts the 1st N elements
2637 // of the 1st vector operand of a shuffle.
2638 if (!match(Shuf.getOperand(1), m_Poison()) || !Shuf.isIdentityWithExtract())
2639 return nullptr;
2640
2641 // The vector being shuffled must be a vector select that we can eliminate.
2642 // TODO: The one-use requirement could be eased if X and/or Y are constants.
2643 Value *Cond, *X, *Y;
2644 if (!match(Shuf.getOperand(0),
2646 return nullptr;
2647
2648 // We need a narrow condition value. It must be extended with poison elements
2649 // and have the same number of elements as this shuffle.
2650 unsigned NarrowNumElts =
2651 cast<FixedVectorType>(Shuf.getType())->getNumElements();
2652 Value *NarrowCond;
2653 if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Poison()))) ||
2654 cast<FixedVectorType>(NarrowCond->getType())->getNumElements() !=
2655 NarrowNumElts ||
2656 !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
2657 return nullptr;
2658
2659 // shuf (sel (shuf NarrowCond, poison, WideMask), X, Y), poison, NarrowMask)
2660 // -->
2661 // sel NarrowCond, (shuf X, poison, NarrowMask), (shuf Y, poison, NarrowMask)
2662 Value *NarrowX = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
2663 Value *NarrowY = Builder.CreateShuffleVector(Y, Shuf.getShuffleMask());
2664 return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
2665}
2666
2667/// Canonicalize FP negate/abs after shuffle.
2669 InstCombiner::BuilderTy &Builder) {
2670 auto *S0 = dyn_cast<Instruction>(Shuf.getOperand(0));
2671 Value *X;
2672 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2673 if (!S0 || !match(S0, m_CombineOr(m_FNegOrFSubNegZero(m_Value(X)),
2674 m_FAbs(m_Value(X)))))
2675 return nullptr;
2676
2677 bool IsFNeg = S0->getOpcode() == Instruction::FNeg;
2678
2679 // Match 2-input (binary) shuffle.
2680 auto *S1 = dyn_cast<Instruction>(Shuf.getOperand(1));
2681 Value *Y;
2682 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2683 if (!S1 ||
2685 m_FAbs(m_Value(Y)))) ||
2686 S0->getOpcode() != S1->getOpcode() ||
2687 (!S0->hasOneUse() && !S1->hasOneUse()))
2688 return nullptr;
2689
2690 // shuf (fneg/fabs X), (fneg/fabs Y), Mask --> fneg/fabs (shuf X, Y, Mask)
2691 Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2692 Instruction *NewF;
2693 if (IsFNeg) {
2694 NewF = UnaryOperator::CreateFNeg(NewShuf);
2695 } else {
2697 Shuf.getModule(), Intrinsic::fabs, Shuf.getType());
2698 NewF = CallInst::Create(FAbs, {NewShuf});
2699 }
2700 NewF->copyIRFlags(S0);
2701 NewF->andIRFlags(S1);
2702 return NewF;
2703}
2704
2705/// Canonicalize casts after shuffle.
2707 InstCombiner::BuilderTy &Builder) {
2708 auto *Cast0 = dyn_cast<CastInst>(Shuf.getOperand(0));
2709 if (!Cast0)
2710 return nullptr;
2711
2712 // TODO: Allow other opcodes? That would require easing the type restrictions
2713 // below here.
2714 CastInst::CastOps CastOpcode = Cast0->getOpcode();
2715 switch (CastOpcode) {
2716 case Instruction::SExt:
2717 case Instruction::ZExt:
2718 case Instruction::FPToSI:
2719 case Instruction::FPToUI:
2720 case Instruction::SIToFP:
2721 case Instruction::UIToFP:
2722 break;
2723 default:
2724 return nullptr;
2725 }
2726
2727 VectorType *CastSrcTy = cast<VectorType>(Cast0->getSrcTy());
2728 VectorType *ShufTy = Shuf.getType();
2729 VectorType *ShufOpTy = cast<VectorType>(Shuf.getOperand(0)->getType());
2730
2731 // TODO: Allow length-increasing shuffles?
2732 if (ShufTy->getElementCount().getKnownMinValue() >
2733 ShufOpTy->getElementCount().getKnownMinValue())
2734 return nullptr;
2735
2736 // shuffle (cast X), Poison, identity-with-extract-mask -->
2737 // cast (shuffle X, Poison, identity-with-extract-mask).
2738 if (isa<PoisonValue>(Shuf.getOperand(1)) && Cast0->hasOneUse() &&
2739 Shuf.isIdentityWithExtract()) {
2740 auto *NewIns = Builder.CreateShuffleVector(Cast0->getOperand(0),
2741 PoisonValue::get(CastSrcTy),
2742 Shuf.getShuffleMask());
2743 return CastInst::Create(Cast0->getOpcode(), NewIns, Shuf.getType());
2744 }
2745
2746 auto *Cast1 = dyn_cast<CastInst>(Shuf.getOperand(1));
2747 // Do we have 2 matching cast operands?
2748 if (!Cast1 || Cast0->getOpcode() != Cast1->getOpcode() ||
2749 Cast0->getSrcTy() != Cast1->getSrcTy())
2750 return nullptr;
2751
2752 // TODO: Allow element-size-decreasing casts (ex: fptosi float to i8)?
2753 assert(isa<FixedVectorType>(CastSrcTy) && isa<FixedVectorType>(ShufOpTy) &&
2754 "Expected fixed vector operands for casts and binary shuffle");
2755 if (CastSrcTy->getPrimitiveSizeInBits() > ShufOpTy->getPrimitiveSizeInBits())
2756 return nullptr;
2757
2758 // At least one of the operands must have only one use (the shuffle).
2759 if (!Cast0->hasOneUse() && !Cast1->hasOneUse())
2760 return nullptr;
2761
2762 // shuffle (cast X), (cast Y), Mask --> cast (shuffle X, Y, Mask)
2763 Value *X = Cast0->getOperand(0);
2764 Value *Y = Cast1->getOperand(0);
2765 Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2766 return CastInst::Create(CastOpcode, NewShuf, ShufTy);
2767}
2768
2769/// Try to fold an extract subvector operation.
2771 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2772 if (!Shuf.isIdentityWithExtract() || !match(Op1, m_Poison()))
2773 return nullptr;
2774
2775 // Check if we are extracting all bits of an inserted scalar:
2776 // extract-subvec (bitcast (inselt ?, X, 0) --> bitcast X to subvec type
2777 Value *X;
2778 if (match(Op0, m_BitCast(m_InsertElt(m_Value(), m_Value(X), m_Zero()))) &&
2779 X->getType()->getPrimitiveSizeInBits() ==
2781 return new BitCastInst(X, Shuf.getType());
2782
2783 // Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
2784 Value *Y;
2785 ArrayRef<int> Mask;
2786 if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask))))
2787 return nullptr;
2788
2789 // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
2790 // then combining may result in worse codegen.
2791 if (!Op0->hasOneUse())
2792 return nullptr;
2793
2794 // We are extracting a subvector from a shuffle. Remove excess elements from
2795 // the 1st shuffle mask to eliminate the extract.
2796 //
2797 // This transform is conservatively limited to identity extracts because we do
2798 // not allow arbitrary shuffle mask creation as a target-independent transform
2799 // (because we can't guarantee that will lower efficiently).
2800 //
2801 // If the extracting shuffle has an poison mask element, it transfers to the
2802 // new shuffle mask. Otherwise, copy the original mask element. Example:
2803 // shuf (shuf X, Y, <C0, C1, C2, poison, C4>), poison, <0, poison, 2, 3> -->
2804 // shuf X, Y, <C0, poison, C2, poison>
2805 unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2806 SmallVector<int, 16> NewMask(NumElts);
2807 assert(NumElts < Mask.size() &&
2808 "Identity with extract must have less elements than its inputs");
2809
2810 for (unsigned i = 0; i != NumElts; ++i) {
2811 int ExtractMaskElt = Shuf.getMaskValue(i);
2812 int MaskElt = Mask[i];
2813 NewMask[i] = ExtractMaskElt == PoisonMaskElem ? ExtractMaskElt : MaskElt;
2814 }
2815 return new ShuffleVectorInst(X, Y, NewMask);
2816}
2817
2818/// Try to replace a shuffle with an insertelement or try to replace a shuffle
2819/// operand with the operand of an insertelement.
2821 InstCombinerImpl &IC) {
2822 Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
2824 Shuf.getShuffleMask(Mask);
2825
2826 int NumElts = Mask.size();
2827 int InpNumElts = cast<FixedVectorType>(V0->getType())->getNumElements();
2828
2829 // This is a specialization of a fold in SimplifyDemandedVectorElts. We may
2830 // not be able to handle it there if the insertelement has >1 use.
2831 // If the shuffle has an insertelement operand but does not choose the
2832 // inserted scalar element from that value, then we can replace that shuffle
2833 // operand with the source vector of the insertelement.
2834 Value *X;
2835 uint64_t IdxC;
2836 if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2837 // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask
2838 if (!is_contained(Mask, (int)IdxC))
2839 return IC.replaceOperand(Shuf, 0, X);
2840 }
2841 if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2842 // Offset the index constant by the vector width because we are checking for
2843 // accesses to the 2nd vector input of the shuffle.
2844 IdxC += InpNumElts;
2845 // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask
2846 if (!is_contained(Mask, (int)IdxC))
2847 return IC.replaceOperand(Shuf, 1, X);
2848 }
2849 // For the rest of the transform, the shuffle must not change vector sizes.
2850 // TODO: This restriction could be removed if the insert has only one use
2851 // (because the transform would require a new length-changing shuffle).
2852 if (NumElts != InpNumElts)
2853 return nullptr;
2854
2855 // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
2856 auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
2857 // We need an insertelement with a constant index.
2858 if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar),
2859 m_ConstantInt(IndexC))))
2860 return false;
2861
2862 // Test the shuffle mask to see if it splices the inserted scalar into the
2863 // operand 1 vector of the shuffle.
2864 int NewInsIndex = -1;
2865 for (int i = 0; i != NumElts; ++i) {
2866 // Ignore undef mask elements.
2867 if (Mask[i] == -1)
2868 continue;
2869
2870 // The shuffle takes elements of operand 1 without lane changes.
2871 if (Mask[i] == NumElts + i)
2872 continue;
2873
2874 // The shuffle must choose the inserted scalar exactly once.
2875 if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
2876 return false;
2877
2878 // The shuffle is placing the inserted scalar into element i.
2879 NewInsIndex = i;
2880 }
2881
2882 assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
2883
2884 // Index is updated to the potentially translated insertion lane.
2885 IndexC = ConstantInt::get(IndexC->getIntegerType(), NewInsIndex);
2886 return true;
2887 };
2888
2889 // If the shuffle is unnecessary, insert the scalar operand directly into
2890 // operand 1 of the shuffle. Example:
2891 // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
2892 Value *Scalar;
2893 ConstantInt *IndexC;
2894 if (isShufflingScalarIntoOp1(Scalar, IndexC))
2895 return InsertElementInst::Create(V1, Scalar, IndexC);
2896
2897 // Try again after commuting shuffle. Example:
2898 // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
2899 // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
2900 std::swap(V0, V1);
2902 if (isShufflingScalarIntoOp1(Scalar, IndexC))
2903 return InsertElementInst::Create(V1, Scalar, IndexC);
2904
2905 return nullptr;
2906}
2907
2909 // Match the operands as identity with padding (also known as concatenation
2910 // with undef) shuffles of the same source type. The backend is expected to
2911 // recreate these concatenations from a shuffle of narrow operands.
2912 auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0));
2913 auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1));
2914 if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
2915 !Shuffle1 || !Shuffle1->isIdentityWithPadding())
2916 return nullptr;
2917
2918 // We limit this transform to power-of-2 types because we expect that the
2919 // backend can convert the simplified IR patterns to identical nodes as the
2920 // original IR.
2921 // TODO: If we can verify the same behavior for arbitrary types, the
2922 // power-of-2 checks can be removed.
2923 Value *X = Shuffle0->getOperand(0);
2924 Value *Y = Shuffle1->getOperand(0);
2925 if (X->getType() != Y->getType() ||
2926 !isPowerOf2_32(cast<FixedVectorType>(Shuf.getType())->getNumElements()) ||
2928 cast<FixedVectorType>(Shuffle0->getType())->getNumElements()) ||
2929 !isPowerOf2_32(cast<FixedVectorType>(X->getType())->getNumElements()) ||
2930 match(X, m_Undef()) || match(Y, m_Undef()))
2931 return nullptr;
2932 assert(match(Shuffle0->getOperand(1), m_Undef()) &&
2933 match(Shuffle1->getOperand(1), m_Undef()) &&
2934 "Unexpected operand for identity shuffle");
2935
2936 // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source
2937 // operands directly by adjusting the shuffle mask to account for the narrower
2938 // types:
2939 // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask'
2940 int NarrowElts = cast<FixedVectorType>(X->getType())->getNumElements();
2941 int WideElts = cast<FixedVectorType>(Shuffle0->getType())->getNumElements();
2942 assert(WideElts > NarrowElts && "Unexpected types for identity with padding");
2943
2944 ArrayRef<int> Mask = Shuf.getShuffleMask();
2945 SmallVector<int, 16> NewMask(Mask.size(), -1);
2946 for (int i = 0, e = Mask.size(); i != e; ++i) {
2947 if (Mask[i] == -1)
2948 continue;
2949
2950 // If this shuffle is choosing an undef element from 1 of the sources, that
2951 // element is undef.
2952 if (Mask[i] < WideElts) {
2953 if (Shuffle0->getMaskValue(Mask[i]) == -1)
2954 continue;
2955 } else {
2956 if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
2957 continue;
2958 }
2959
2960 // If this shuffle is choosing from the 1st narrow op, the mask element is
2961 // the same. If this shuffle is choosing from the 2nd narrow op, the mask
2962 // element is offset down to adjust for the narrow vector widths.
2963 if (Mask[i] < WideElts) {
2964 assert(Mask[i] < NarrowElts && "Unexpected shuffle mask");
2965 NewMask[i] = Mask[i];
2966 } else {
2967 assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask");
2968 NewMask[i] = Mask[i] - (WideElts - NarrowElts);
2969 }
2970 }
2971 return new ShuffleVectorInst(X, Y, NewMask);
2972}
2973
2974// Splatting the first element of the result of a BinOp, where any of the
2975// BinOp's operands are the result of a first element splat can be simplified to
2976// splatting the first element of the result of the BinOp
2978 if (!match(SVI.getOperand(1), m_Poison()) ||
2979 !match(SVI.getShuffleMask(), m_ZeroMask()) ||
2980 !SVI.getOperand(0)->hasOneUse())
2981 return nullptr;
2982
2983 Value *Op0 = SVI.getOperand(0);
2984 Value *X, *Y;
2986 m_Value(Y))) &&
2987 !match(Op0, m_BinOp(m_Value(X),
2989 return nullptr;
2990 if (X->getType() != Y->getType())
2991 return nullptr;
2992
2993 auto *BinOp = cast<BinaryOperator>(Op0);
2995 return nullptr;
2996
2997 Value *NewBO = Builder.CreateBinOp(BinOp->getOpcode(), X, Y);
2998 if (auto NewBOI = dyn_cast<Instruction>(NewBO))
2999 NewBOI->copyIRFlags(BinOp);
3000
3001 return new ShuffleVectorInst(NewBO, SVI.getShuffleMask());
3002}
3003
3005 Value *LHS = SVI.getOperand(0);
3006 Value *RHS = SVI.getOperand(1);
3007 SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI);
3008 if (auto *V = simplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(),
3009 SVI.getType(), ShufQuery))
3010 return replaceInstUsesWith(SVI, V);
3011
3012 if (Instruction *I = simplifyBinOpSplats(SVI))
3013 return I;
3014
3015 // Canonicalize splat shuffle to use poison RHS. Handle this explicitly in
3016 // order to support scalable vectors.
3017 if (match(SVI.getShuffleMask(), m_ZeroMask()) && !isa<PoisonValue>(RHS))
3018 return replaceOperand(SVI, 1, PoisonValue::get(RHS->getType()));
3019
3020 if (isa<ScalableVectorType>(LHS->getType()))
3021 return nullptr;
3022
3023 unsigned VWidth = cast<FixedVectorType>(SVI.getType())->getNumElements();
3024 unsigned LHSWidth = cast<FixedVectorType>(LHS->getType())->getNumElements();
3025
3026 // shuffle (bitcast X), (bitcast Y), Mask --> bitcast (shuffle X, Y, Mask)
3027 //
3028 // if X and Y are of the same (vector) type, and the element size is not
3029 // changed by the bitcasts, we can distribute the bitcasts through the
3030 // shuffle, hopefully reducing the number of instructions. We make sure that
3031 // at least one bitcast only has one use, so we don't *increase* the number of
3032 // instructions here.
3033 Value *X, *Y;
3034 if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_BitCast(m_Value(Y))) &&
3035 X->getType()->isVectorTy() && X->getType() == Y->getType() &&
3036 X->getType()->getScalarSizeInBits() ==
3037 SVI.getType()->getScalarSizeInBits() &&
3038 (LHS->hasOneUse() || RHS->hasOneUse())) {
3039 Value *V = Builder.CreateShuffleVector(X, Y, SVI.getShuffleMask(),
3040 SVI.getName() + ".uncasted");
3041 return new BitCastInst(V, SVI.getType());
3042 }
3043
3044 ArrayRef<int> Mask = SVI.getShuffleMask();
3045
3046 // Peek through a bitcasted shuffle operand by scaling the mask. If the
3047 // simulated shuffle can simplify, then this shuffle is unnecessary:
3048 // shuf (bitcast X), undef, Mask --> bitcast X'
3049 // TODO: This could be extended to allow length-changing shuffles.
3050 // The transform might also be obsoleted if we allowed canonicalization
3051 // of bitcasted shuffles.
3052 if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) &&
3053 X->getType()->isVectorTy() && VWidth == LHSWidth) {
3054 // Try to create a scaled mask constant.
3055 auto *XType = cast<FixedVectorType>(X->getType());
3056 unsigned XNumElts = XType->getNumElements();
3057 SmallVector<int, 16> ScaledMask;
3058 if (scaleShuffleMaskElts(XNumElts, Mask, ScaledMask)) {
3059 // If the shuffled source vector simplifies, cast that value to this
3060 // shuffle's type.
3061 if (auto *V = simplifyShuffleVectorInst(X, UndefValue::get(XType),
3062 ScaledMask, XType, ShufQuery))
3063 return BitCastInst::Create(Instruction::BitCast, V, SVI.getType());
3064 }
3065 }
3066
3067 // shuffle x, x, mask --> shuffle x, undef, mask'
3068 if (LHS == RHS) {
3069 assert(!match(RHS, m_Undef()) &&
3070 "Shuffle with 2 undef ops not simplified?");
3071 return new ShuffleVectorInst(LHS, createUnaryMask(Mask, LHSWidth));
3072 }
3073
3074 // shuffle undef, x, mask --> shuffle x, undef, mask'
3075 if (match(LHS, m_Undef())) {
3076 SVI.commute();
3077 return &SVI;
3078 }
3079
3080 // shuffle zero, x, mask --> shuffle x, zero, mask'
3081 if (match(LHS, m_CombineOr(m_Zero(), m_AnyZeroFP())) && LHS != RHS) {
3082 SVI.commute();
3083 return &SVI;
3084 }
3085
3087 return I;
3088
3089 if (Instruction *I = foldSelectShuffle(SVI))
3090 return I;
3091
3092 if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian()))
3093 return I;
3094
3096 return I;
3097
3099 return I;
3100
3101 if (Instruction *I = foldCastShuffle(SVI, Builder))
3102 return I;
3103
3104 APInt PoisonElts(VWidth, 0);
3105 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
3106 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, PoisonElts)) {
3107 if (V != &SVI)
3108 return replaceInstUsesWith(SVI, V);
3109 return &SVI;
3110 }
3111
3113 return I;
3114
3115 // These transforms have the potential to lose undef knowledge, so they are
3116 // intentionally placed after SimplifyDemandedVectorElts().
3117 if (Instruction *I = foldShuffleWithInsert(SVI, *this))
3118 return I;
3120 return I;
3121
3122 if (match(RHS, m_Constant())) {
3123 if (auto *SI = dyn_cast<SelectInst>(LHS)) {
3124 // We cannot do this fold for elementwise select since ShuffleVector is
3125 // not elementwise.
3126 if (SI->getCondition()->getType()->isIntegerTy() &&
3127 (isa<PoisonValue>(RHS) ||
3128 isGuaranteedNotToBePoison(SI->getCondition()))) {
3129 if (Instruction *I = FoldOpIntoSelect(SVI, SI))
3130 return I;
3131 }
3132 }
3133 if (auto *PN = dyn_cast<PHINode>(LHS)) {
3134 if (Instruction *I = foldOpIntoPhi(SVI, PN, /*AllowMultipleUses=*/true))
3135 return I;
3136 }
3137 }
3138
3139 if (match(RHS, m_Poison()) && canEvaluateShuffled(LHS, Mask)) {
3141 return replaceInstUsesWith(SVI, V);
3142 }
3143
3144 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
3145 // a non-vector type. We can instead bitcast the original vector followed by
3146 // an extract of the desired element:
3147 //
3148 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
3149 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
3150 // %1 = bitcast <4 x i8> %sroa to i32
3151 // Becomes:
3152 // %bc = bitcast <16 x i8> %in to <4 x i32>
3153 // %ext = extractelement <4 x i32> %bc, i32 0
3154 //
3155 // If the shuffle is extracting a contiguous range of values from the input
3156 // vector then each use which is a bitcast of the extracted size can be
3157 // replaced. This will work if the vector types are compatible, and the begin
3158 // index is aligned to a value in the casted vector type. If the begin index
3159 // isn't aligned then we can shuffle the original vector (keeping the same
3160 // vector type) before extracting.
3161 //
3162 // This code will bail out if the target type is fundamentally incompatible
3163 // with vectors of the source type.
3164 //
3165 // Example of <16 x i8>, target type i32:
3166 // Index range [4,8): v-----------v Will work.
3167 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3168 // <16 x i8>: | | | | | | | | | | | | | | | | |
3169 // <4 x i32>: | | | | |
3170 // +-----------+-----------+-----------+-----------+
3171 // Index range [6,10): ^-----------^ Needs an extra shuffle.
3172 // Target type i40: ^--------------^ Won't work, bail.
3173 bool MadeChange = false;
3174 if (isShuffleExtractingFromLHS(SVI, Mask)) {
3175 Value *V = LHS;
3176 unsigned MaskElems = Mask.size();
3177 auto *SrcTy = cast<FixedVectorType>(V->getType());
3178 unsigned VecBitWidth = DL.getTypeSizeInBits(SrcTy);
3179 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
3180 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
3181 unsigned SrcNumElems = SrcTy->getNumElements();
3184 for (User *U : SVI.users())
3185 if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) {
3186 // Only visit bitcasts that weren't previously handled.
3187 if (BC->use_empty())
3188 continue;
3189 // Prefer to combine bitcasts of bitcasts before attempting this fold.
3190 if (BC->hasOneUse()) {
3191 auto *BC2 = dyn_cast<BitCastInst>(BC->user_back());
3192 if (BC2 && isEliminableCastPair(BC, BC2))
3193 continue;
3194 }
3195 BCs.push_back(BC);
3196 }
3197 for (BitCastInst *BC : BCs) {
3198 unsigned BegIdx = Mask.front();
3199 Type *TgtTy = BC->getDestTy();
3200 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
3201 if (!TgtElemBitWidth)
3202 continue;
3203 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
3204 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
3205 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
3206 if (!VecBitWidthsEqual)
3207 continue;
3209 continue;
3210 auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems);
3211 if (!BegIsAligned) {
3212 // Shuffle the input so [0,NumElements) contains the output, and
3213 // [NumElems,SrcNumElems) is undef.
3214 SmallVector<int, 16> ShuffleMask(SrcNumElems, -1);
3215 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
3216 ShuffleMask[I] = Idx;
3217 V = Builder.CreateShuffleVector(V, ShuffleMask,
3218 SVI.getName() + ".extract");
3219 BegIdx = 0;
3220 }
3221 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
3222 assert(SrcElemsPerTgtElem);
3223 BegIdx /= SrcElemsPerTgtElem;
3224 auto [It, Inserted] = NewBCs.try_emplace(CastSrcTy);
3225 if (Inserted)
3226 It->second = Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
3227 auto *Ext = Builder.CreateExtractElement(It->second, BegIdx,
3228 SVI.getName() + ".extract");
3229 // The shufflevector isn't being replaced: the bitcast that used it
3230 // is. InstCombine will visit the newly-created instructions.
3231 replaceInstUsesWith(*BC, Ext);
3232 MadeChange = true;
3233 }
3234 }
3235
3236 // If the LHS is a shufflevector itself, see if we can combine it with this
3237 // one without producing an unusual shuffle.
3238 // Cases that might be simplified:
3239 // 1.
3240 // x1=shuffle(v1,v2,mask1)
3241 // x=shuffle(x1,undef,mask)
3242 // ==>
3243 // x=shuffle(v1,undef,newMask)
3244 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
3245 // 2.
3246 // x1=shuffle(v1,undef,mask1)
3247 // x=shuffle(x1,x2,mask)
3248 // where v1.size() == mask1.size()
3249 // ==>
3250 // x=shuffle(v1,x2,newMask)
3251 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
3252 // 3.
3253 // x2=shuffle(v2,undef,mask2)
3254 // x=shuffle(x1,x2,mask)
3255 // where v2.size() == mask2.size()
3256 // ==>
3257 // x=shuffle(x1,v2,newMask)
3258 // newMask[i] = (mask[i] < x1.size())
3259 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
3260 // 4.
3261 // x1=shuffle(v1,undef,mask1)
3262 // x2=shuffle(v2,undef,mask2)
3263 // x=shuffle(x1,x2,mask)
3264 // where v1.size() == v2.size()
3265 // ==>
3266 // x=shuffle(v1,v2,newMask)
3267 // newMask[i] = (mask[i] < x1.size())
3268 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
3269 //
3270 // Here we are really conservative:
3271 // we are absolutely afraid of producing a shuffle mask not in the input
3272 // program, because the code gen may not be smart enough to turn a merged
3273 // shuffle into two specific shuffles: it may produce worse code. As such,
3274 // we only merge two shuffles if the result is either a splat or one of the
3275 // input shuffle masks. In this case, merging the shuffles just removes
3276 // one instruction, which we know is safe. This is good for things like
3277 // turning: (splat(splat)) -> splat, or
3278 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
3281 if (LHSShuffle)
3282 if (!match(LHSShuffle->getOperand(1), m_Poison()) &&
3283 !match(RHS, m_Poison()))
3284 LHSShuffle = nullptr;
3285 if (RHSShuffle)
3286 if (!match(RHSShuffle->getOperand(1), m_Poison()))
3287 RHSShuffle = nullptr;
3288 if (!LHSShuffle && !RHSShuffle)
3289 return MadeChange ? &SVI : nullptr;
3290
3291 Value* LHSOp0 = nullptr;
3292 Value* LHSOp1 = nullptr;
3293 Value* RHSOp0 = nullptr;
3294 unsigned LHSOp0Width = 0;
3295 unsigned RHSOp0Width = 0;
3296 if (LHSShuffle) {
3297 LHSOp0 = LHSShuffle->getOperand(0);
3298 LHSOp1 = LHSShuffle->getOperand(1);
3299 LHSOp0Width = cast<FixedVectorType>(LHSOp0->getType())->getNumElements();
3300 }
3301 if (RHSShuffle) {
3302 RHSOp0 = RHSShuffle->getOperand(0);
3303 RHSOp0Width = cast<FixedVectorType>(RHSOp0->getType())->getNumElements();
3304 }
3305 Value* newLHS = LHS;
3306 Value* newRHS = RHS;
3307 if (LHSShuffle) {
3308 // case 1
3309 if (match(RHS, m_Poison())) {
3310 newLHS = LHSOp0;
3311 newRHS = LHSOp1;
3312 }
3313 // case 2 or 4
3314 else if (LHSOp0Width == LHSWidth) {
3315 newLHS = LHSOp0;
3316 }
3317 }
3318 // case 3 or 4
3319 if (RHSShuffle && RHSOp0Width == LHSWidth) {
3320 newRHS = RHSOp0;
3321 }
3322 // case 4
3323 if (LHSOp0 == RHSOp0) {
3324 newLHS = LHSOp0;
3325 newRHS = nullptr;
3326 }
3327
3328 if (newLHS == LHS && newRHS == RHS)
3329 return MadeChange ? &SVI : nullptr;
3330
3331 ArrayRef<int> LHSMask;
3332 ArrayRef<int> RHSMask;
3333 if (newLHS != LHS)
3334 LHSMask = LHSShuffle->getShuffleMask();
3335 if (RHSShuffle && newRHS != RHS)
3336 RHSMask = RHSShuffle->getShuffleMask();
3337
3338 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
3339 SmallVector<int, 16> newMask;
3340 bool isSplat = true;
3341 int SplatElt = -1;
3342 // Create a new mask for the new ShuffleVectorInst so that the new
3343 // ShuffleVectorInst is equivalent to the original one.
3344 for (unsigned i = 0; i < VWidth; ++i) {
3345 int eltMask;
3346 if (Mask[i] < 0) {
3347 // This element is a poison value.
3348 eltMask = -1;
3349 } else if (Mask[i] < (int)LHSWidth) {
3350 // This element is from left hand side vector operand.
3351 //
3352 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
3353 // new mask value for the element.
3354 if (newLHS != LHS) {
3355 eltMask = LHSMask[Mask[i]];
3356 // If the value selected is an poison value, explicitly specify it
3357 // with a -1 mask value.
3358 if (eltMask >= (int)LHSOp0Width && isa<PoisonValue>(LHSOp1))
3359 eltMask = -1;
3360 } else
3361 eltMask = Mask[i];
3362 } else {
3363 // This element is from right hand side vector operand
3364 //
3365 // If the value selected is a poison value, explicitly specify it
3366 // with a -1 mask value. (case 1)
3367 if (match(RHS, m_Poison()))
3368 eltMask = -1;
3369 // If RHS is going to be replaced (case 3 or 4), calculate the
3370 // new mask value for the element.
3371 else if (newRHS != RHS) {
3372 eltMask = RHSMask[Mask[i]-LHSWidth];
3373 // If the value selected is an poison value, explicitly specify it
3374 // with a -1 mask value.
3375 if (eltMask >= (int)RHSOp0Width) {
3376 assert(match(RHSShuffle->getOperand(1), m_Poison()) &&
3377 "should have been check above");
3378 eltMask = -1;
3379 }
3380 } else
3381 eltMask = Mask[i]-LHSWidth;
3382
3383 // If LHS's width is changed, shift the mask value accordingly.
3384 // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
3385 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
3386 // If newRHS == newLHS, we want to remap any references from newRHS to
3387 // newLHS so that we can properly identify splats that may occur due to
3388 // obfuscation across the two vectors.
3389 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
3390 eltMask += newLHSWidth;
3391 }
3392
3393 // Check if this could still be a splat.
3394 if (eltMask >= 0) {
3395 if (SplatElt >= 0 && SplatElt != eltMask)
3396 isSplat = false;
3397 SplatElt = eltMask;
3398 }
3399
3400 newMask.push_back(eltMask);
3401 }
3402
3403 // If the result mask is equal to one of the original shuffle masks,
3404 // or is a splat, do the replacement.
3405 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
3406 if (!newRHS)
3407 newRHS = PoisonValue::get(newLHS->getType());
3408 return new ShuffleVectorInst(newLHS, newRHS, newMask);
3409 }
3410
3411 return MadeChange ? &SVI : nullptr;
3412}
3413
3414/// Given the following de-interleaving shufflevectors and the consuming zexts:
3415/// ```
3416/// %f0 = shufflevector <8 x i32> %v, <4 x i32> <i32 0, i32 2, i32 4, i32 6>
3417/// %f1 = shufflevector <8 x i32> %v, <4 x i32> <i32 1, i32 3, i32 5, i32 7>
3418/// %z0 = zext <4 x i32> %f0 to <4 x i64>
3419/// %z1 = zext <4 x i32> %f1 to <4 x i64>
3420/// ```
3421/// We can actually bitcast the input value, `%v` first before replacing zexts
3422/// with simple arithmetics on this new bitcast:
3423/// ```
3424/// %bc = bitcast <8 x i32> %v to <4 x i64>
3425// %z0 = and <4 x i64> %bc, splat (i64 4294967295)
3426// %z1 = lshr <4 x i64> %bc, splat (i64 32)
3427/// ```
3428/// This transformation is almost always benefitial as shufflevector is more
3429/// expensive than normal arithmetics.
3432 // This pattern involves bitcast that is not compatible with big endian.
3433 if (DL.isBigEndian())
3434 return nullptr;
3435
3436 // The actual value that got de-interleaved.
3437 Value *DIV;
3438
3439 using namespace PatternMatch;
3440 Instruction *SVI = nullptr, *DI = nullptr;
3441 if (!match(
3442 &RootZExt,
3445 m_Instruction(SVI, m_Shuffle(m_Value(), m_Value()))))))
3446 return nullptr;
3447
3448 auto isDeinterleaveShuffle =
3449 [](Instruction *I) -> std::pair<Value *, unsigned> {
3450 Value *V;
3451 ArrayRef<int> ShuffleMask;
3452 unsigned Index;
3453 if (match(I, m_Shuffle(m_Value(V), m_Undef(), m_Mask(ShuffleMask))) &&
3454 isa<FixedVectorType>(V->getType())) {
3455 unsigned NumInputElements =
3456 cast<VectorType>(V->getType())->getElementCount().getFixedValue();
3458 Index) &&
3459 Index < 2 &&
3461 NumInputElements) &&
3462 ShuffleMask.size() * 2 == NumInputElements)
3463 return {V, Index};
3464 }
3465 return {nullptr, UINT_MAX};
3466 };
3467
3468 // Validate either the shufflevector or the vector.deinterleave2 and obtain
3469 // the value they're de-interleaving.
3470 if (SVI) {
3471 // We will find other shufflevectors later.
3472 DIV = isDeinterleaveShuffle(SVI).first;
3473 if (!DIV)
3474 return nullptr;
3475 } else {
3476 // We should already capture the value that got de-interleaved (i.e. DIV).
3477 assert(DI && DIV);
3478 if (!all_of(DI->users(), [](User *Usr) -> bool {
3479 auto *EV = dyn_cast<ExtractValueInst>(Usr);
3480 return EV && EV->getNumIndices() == 1;
3481 }))
3482 return nullptr;
3483 }
3484
3485 auto *InputVecTy = dyn_cast<VectorType>(DIV->getType());
3486 if (!InputVecTy)
3487 return nullptr;
3488 auto *InElementTy = dyn_cast<IntegerType>(InputVecTy->getElementType());
3489 if (!InElementTy)
3490 return nullptr;
3491 if (!InputVecTy->getElementCount().isKnownEven())
3492 return nullptr;
3493
3494 // {Field instruction, Field index}
3496 if (SVI) {
3497 for (auto *Usr : DIV->users()) {
3498 auto *FieldI = dyn_cast<Instruction>(Usr);
3499 if (!FieldI)
3500 continue;
3501 auto [V, Index] = isDeinterleaveShuffle(FieldI);
3502 if (V != DIV)
3503 continue;
3504 assert(Index < 2);
3505 // Find the earliest field extraction instruction.
3506 if (FieldI->getParent() != SVI->getParent())
3507 continue;
3508 if (FieldI != SVI && FieldI->comesBefore(SVI))
3509 SVI = FieldI;
3510 Fields.push_back({FieldI, Index});
3511 }
3512 } else {
3513 // llvm.vector.deinterleave2.
3514 for (User *Field : DI->users()) {
3515 auto *FieldI = cast<ExtractValueInst>(Field);
3516 unsigned FieldIdx = *FieldI->idx_begin();
3517 assert(FieldIdx < 2);
3518 Fields.push_back({FieldI, FieldIdx});
3519 }
3520 }
3521
3522 // {field to be replaced, field index}
3523 SmallVector<std::pair<ZExtInst *, unsigned>, 4> FieldReplacements;
3524 // We commit the transformation only if all the field users can be replaced,
3525 // otherwise the primary de-interleaving construction, regardless of
3526 // llvm.vector.deinterleave2 or shufflevectors, will still be there.
3527 for (auto [Field, FieldIdx] : Fields) {
3528 for (User *FieldUsr : Field->users()) {
3529 auto *ZExt = dyn_cast<ZExtInst>(FieldUsr);
3530 if (!ZExt)
3531 return nullptr;
3532 // Only if it's doubling the element size.
3533 if (ZExt->getDestTy() != ZExt->getSrcTy()->getExtendedType())
3534 return nullptr;
3535 FieldReplacements.push_back({ZExt, FieldIdx});
3536 }
3537 }
3538
3539 // This will insert replacement instructions before all the fields users.
3540 Builder.SetInsertPoint(DI ? DI : SVI);
3541
3542 // Double the element size but half the vector length.
3543 auto *BitcastedTy = VectorType::getExtendedElementVectorType(InputVecTy);
3544 BitcastedTy = VectorType::getHalfElementsVectorType(BitcastedTy);
3545 // Since we're going to "merge" lanes via bitcast, we need to freeze any
3546 // potential poison lanes first.
3547 Value *Freeze = Builder.CreateFreeze(DIV);
3548 Value *Bitcast = Builder.CreateBitCast(Freeze, BitcastedTy);
3549 unsigned InElementBitWidth = InElementTy->getBitWidth();
3550 auto Mask = APInt::getLowBitsSet(InElementBitWidth * 2, InElementBitWidth);
3551 Value *NewField0 = Builder.CreateAnd(Bitcast, Mask);
3552 Value *NewField1 = Builder.CreateLShr(Bitcast, InElementBitWidth);
3553
3554 for (auto [I, Idx] : FieldReplacements) {
3555 assert(Idx < 2 && "unsupported field index");
3556 replaceInstUsesWith(*I, Idx ? NewField1 : NewField0);
3557 // Make sure the old ZExt are in the worklist so that they
3558 // can be removed in the following iterations.
3560 }
3561
3562 return &RootZExt;
3563}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
Hexagon Common GEP
This file provides internal interfaces used to implement the InstCombine.
static Instruction * foldConstantInsEltIntoShuffle(InsertElementInst &InsElt)
insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex --> shufflevector X,...
static Value * evaluateInDifferentElementOrder(Value *V, ArrayRef< int > Mask, IRBuilderBase &Builder)
static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, SmallVectorImpl< int > &Mask)
If V is a shuffle of values that ONLY returns elements from either LHS or RHS, return the shuffle mas...
static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl< int > &Mask, Value *PermittedRHS, InstCombinerImpl &IC, bool &Rerun)
static APInt findDemandedEltsByAllUsers(Value *V)
Find union of elements of V demanded by all its users.
static Instruction * foldTruncInsEltPair(InsertElementInst &InsElt, bool IsBigEndian, InstCombiner::BuilderTy &Builder)
If we are inserting 2 halves of a value into adjacent elements of a vector, try to convert to a singl...
static Instruction * foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf, const SimplifyQuery &SQ)
static Instruction * foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf)
static Instruction * foldIdentityExtractShuffle(ShuffleVectorInst &Shuf)
Try to fold an extract subvector operation.
static bool findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr, APInt &UnionUsedElts)
Find elements of V demanded by UserInstr.
static Instruction * foldInsEltIntoSplat(InsertElementInst &InsElt)
Try to fold an insert element into an existing splat shuffle by changing the shuffle's mask to includ...
std::pair< Value *, Value * > ShuffleOps
We are building a shuffle to create V, which is a sequence of insertelement, extractelement pairs.
static Instruction * foldShuffleWithInsert(ShuffleVectorInst &Shuf, InstCombinerImpl &IC)
Try to replace a shuffle with an insertelement or try to replace a shuffle operand with the operand o...
static Instruction * canonicalizeInsertSplat(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
If we have an insert of a scalar to a non-zero element of an undefined vector and then shuffle that v...
static Instruction * foldTruncShuffle(ShuffleVectorInst &Shuf, bool IsBigEndian)
Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
static bool replaceExtractElements(InsertElementInst *InsElt, ExtractElementInst *ExtElt, InstCombinerImpl &IC)
If we have insertion into a vector that is wider than the vector that we are extracting from,...
static bool cheapToScalarize(Value *V, Value *EI)
Return true if the value is cheaper to scalarize than it is to leave as a vector operation.
static Value * buildNew(Instruction *I, ArrayRef< Value * > NewOps, IRBuilderBase &Builder)
Rebuild a new instruction just like 'I' but with the new operands given.
static bool canEvaluateShuffled(Value *V, ArrayRef< int > Mask, unsigned Depth=5)
Return true if we can evaluate the specified expression tree if the vector elements were shuffled in ...
static Instruction * foldSelectShuffleOfSelectShuffle(ShuffleVectorInst &Shuf)
A select shuffle of a select shuffle with a shared operand can be reduced to a single select shuffle.
static Instruction * hoistInsEltConst(InsertElementInst &InsElt2, InstCombiner::BuilderTy &Builder)
If we have an insertelement instruction feeding into another insertelement and the 2nd is inserting a...
static Instruction * foldShuffleOfUnaryOps(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
Canonicalize FP negate/abs after shuffle.
static Instruction * foldCastShuffle(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
Canonicalize casts after shuffle.
static Instruction * narrowInsElt(InsertElementInst &InsElt, InstCombiner::BuilderTy &Builder)
If both the base vector and the inserted element are extended from the same type, do the insert eleme...
static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf)
static Instruction * foldInsSequenceIntoSplat(InsertElementInst &InsElt)
Turn a chain of inserts that splats a value into an insert + shuffle: insertelt(insertelt(insertelt(i...
static Instruction * foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt)
Try to fold an extract+insert element into an existing identity shuffle by changing the shuffle's mas...
static ConstantInt * getPreferredVectorIndex(ConstantInt *IndexC)
Given a constant index for a extractelement or insertelement instruction, return it with the canonica...
static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, ArrayRef< int > Mask)
static Value * foldExtractOfStridedPointerVector(ExtractElementInst &EI, InstCombiner::BuilderTy &Builder, const DataLayout &DL)
Fold a variable extract from a vector of pointers that all point into the same object at a constant s...
static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL)
Binops may be transformed into binops with different opcodes and operands.
This file provides the interface for the instcombine pass implementation.
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
static bool isSplat(Value *V)
Return true if V is a splat of a value (which is used when multiplying a matrix with a scalar).
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
int64_t C1
int64_t C0
This file contains some templates that are useful if you are working with the STL at all.
This file implements the SmallBitVector class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG, const SDLoc &DL, const X86Subtarget &Subtarget)
If both arms of a vector select are concatenated vectors, split the select, and concatenate the resul...
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
LLVM Basic Block Representation.
Definition BasicBlock.h:61
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:254
This class represents a no-op cast from one type to another.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI CmpInst * CreateWithCopiedFlags(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Instruction *FlagsSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate, the two operands and the instructio...
OtherOps getOpcode() const
Get the opcode casted to the right type.
Definition InstrTypes.h:823
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
This instruction extracts a single (scalar) element from a VectorType value.
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
VectorType * getVectorOperandType() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setNoWrapFlags(GEPNoWrapFlags NW)
Set nowrap flags for GEP instruction.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
This instruction inserts a single (scalar) element into a VectorType value.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
VectorType * getType() const
Overload to return most specific vector type.
This instruction inserts a struct field of array element value into an aggregate value.
Instruction * foldExtractionOfVectorDeinterleave(ZExtInst &RootZExt)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
Instruction * foldSelectShuffle(ShuffleVectorInst &Shuf)
Try to fold shuffles that are the equivalent of a vector select.
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitInsertValueInst(InsertValueInst &IV)
Try to find redundant insertvalue instructions, like the following ones: %0 = insertvalue { i8,...
Instruction * visitInsertElementInst(InsertElementInst &IE)
Instruction * visitExtractElementInst(ExtractElementInst &EI)
Instruction * simplifyBinOpSplats(ShuffleVectorInst &SVI)
Instruction * foldAggregateConstructionIntoAggregateReuse(InsertValueInst &OrigIVI)
Look for chain of insertvalue's that fully define an aggregate, and trace back the values inserted,...
Instruction * visitShuffleVectorInst(ShuffleVectorInst &SVI)
SimplifyQuery SQ
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
const DataLayout & DL
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
const SimplifyQuery & getSimplifyQuery() const
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
Instruction * user_back()
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
bool isTerminator() const
iterator_range< user_iterator > users()
LLVM_ABI void setHasNoInfs(bool B)
Set or clear the no-infs flag on this instruction, which must be an operator which supports this flag...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
bool isIntDivRem() const
A wrapper class for inspecting calls to intrinsic functions.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:119
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
In order to facilitate speculative execution, many instructions do not invoke immediate undefined beh...
Definition Constants.h:1705
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
bool changesLength() const
Return true if this shuffle returns a vector with a different number of elements than its source vect...
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
static LLVM_ABI bool isSelectMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from its source vectors without lane crossings.
VectorType * getType() const
Overload to return most specific vector type.
bool increasesLength() const
Return true if this shuffle returns a vector with a greater number of elements than its source vector...
LLVM_ABI bool isIdentityWithExtract() const
Return true if this shuffle extracts the first N elements of exactly one source vector.
static LLVM_ABI bool isSingleSourceMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
bool isSelect() const
Return true if this shuffle chooses elements from its source vectors without lane crossings and all o...
static LLVM_ABI bool isDeInterleaveMaskOfFactor(ArrayRef< int > Mask, unsigned Factor, unsigned &Index)
Check if the mask is a DE-interleave mask of the given factor Factor like: <Index,...
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
LLVM_ABI void commute()
Swap the operands and adjust the mask to preserve the semantics of the instruction.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
bool all() const
Returns true if all bits are set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
@ ArrayTyID
Arrays.
Definition Type.h:76
@ StructTyID
Structures.
Definition Type.h:75
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
TypeID getTypeID() const
Return the type id for the type.
Definition Type.h:138
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
static UnaryOperator * CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:148
UnaryOps getOpcode() const
Definition InstrTypes.h:163
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
Definition Value.cpp:1117
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
User * user_back()
Definition Value.h:414
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
static VectorType * getHalfElementsVectorType(VectorType *VTy)
This static method returns a VectorType with half as many elements as the input type and the same ele...
static VectorType * getExtendedElementVectorType(VectorType *VTy)
This static method is like getInteger except that the element types are twice as wide as the elements...
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Type * getElementType() const
This class represents zero extension of integer types.
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
@ Bitcast
Perform the operation on a different, but equivalently sized type.
BinaryOpc_match< LHS, RHS, false > m_BinOp(unsigned Opcode, const LHS &L, const RHS &R)
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
auto m_Cmp()
Matches any compare instruction and ignore it.
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Constant()
Match an arbitrary Constant and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< false > m_ZeroForbidPoison()
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_Deinterleave2(const Opnd &Op)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
auto m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
auto m_UnOp()
Match an arbitrary unary operation and ignore it.
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI llvm::SmallVector< int, 16 > createUnaryMask(ArrayRef< int > Mask, unsigned NumElts)
Given a shuffle mask for a binary shuffle, create the equivalent shuffle mask assuming both operands ...
LLVM_ABI Value * simplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef< int > Mask, Type *RetTy, const SimplifyQuery &Q)
Given operands for a ShuffleVectorInst, fold the result or return null.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * simplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an InsertValueInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
LLVM_ABI Value * simplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx, const SimplifyQuery &Q)
Given operands for an InsertElement, fold the result or return null.
constexpr unsigned BitWidth
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Value * simplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &Q)
Given operands for an ExtractElementInst, fold the result or return null.
LLVM_ABI bool scaleShuffleMaskElts(unsigned NumDstElts, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Attempt to narrow/widen the Mask shuffle mask to the NumDstElts target width.
LLVM_ABI int getSplatIndex(ArrayRef< int > Mask)
If all non-negative Mask elements are the same value, return that value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
These are the ingredients in an alternate form binary operator as described below.
BinopElts(BinaryOperator::BinaryOps Opc=(BinaryOperator::BinaryOps) 0, Value *V0=nullptr, Value *V1=nullptr)
BinaryOperator::BinaryOps Opcode
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344