LLVM 19.0.0git
VectorCombine.cpp
Go to the documentation of this file.
1//===------- VectorCombine.cpp - Optimize partial vector operations -------===//
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 pass optimizes scalar/vector interactions using target cost models. The
10// transforms implemented here may not fit in traditional loop-based or SLP
11// vectorization passes.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/Loads.h"
26#include "llvm/IR/Dominators.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
33#include <numeric>
34#include <queue>
35
36#define DEBUG_TYPE "vector-combine"
38
39using namespace llvm;
40using namespace llvm::PatternMatch;
41
42STATISTIC(NumVecLoad, "Number of vector loads formed");
43STATISTIC(NumVecCmp, "Number of vector compares formed");
44STATISTIC(NumVecBO, "Number of vector binops formed");
45STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
46STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
47STATISTIC(NumScalarBO, "Number of scalar binops formed");
48STATISTIC(NumScalarCmp, "Number of scalar compares formed");
49
51 "disable-vector-combine", cl::init(false), cl::Hidden,
52 cl::desc("Disable all vector combine transforms"));
53
55 "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
56 cl::desc("Disable binop extract to shuffle transforms"));
57
59 "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
60 cl::desc("Max number of instructions to scan for vector combining."));
61
62static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
63
64namespace {
65class VectorCombine {
66public:
67 VectorCombine(Function &F, const TargetTransformInfo &TTI,
68 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC,
69 const DataLayout *DL, bool TryEarlyFoldsOnly)
70 : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC), DL(DL),
71 TryEarlyFoldsOnly(TryEarlyFoldsOnly) {}
72
73 bool run();
74
75private:
76 Function &F;
77 IRBuilder<> Builder;
79 const DominatorTree &DT;
80 AAResults &AA;
82 const DataLayout *DL;
83
84 /// If true, only perform beneficial early IR transforms. Do not introduce new
85 /// vector operations.
86 bool TryEarlyFoldsOnly;
87
88 InstructionWorklist Worklist;
89
90 // TODO: Direct calls from the top-level "run" loop use a plain "Instruction"
91 // parameter. That should be updated to specific sub-classes because the
92 // run loop was changed to dispatch on opcode.
93 bool vectorizeLoadInsert(Instruction &I);
94 bool widenSubvectorLoad(Instruction &I);
95 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
97 unsigned PreferredExtractIndex) const;
98 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
99 const Instruction &I,
100 ExtractElementInst *&ConvertToShuffle,
101 unsigned PreferredExtractIndex);
102 void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
103 Instruction &I);
104 void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
105 Instruction &I);
106 bool foldExtractExtract(Instruction &I);
107 bool foldInsExtFNeg(Instruction &I);
108 bool foldBitcastShuffle(Instruction &I);
109 bool scalarizeBinopOrCmp(Instruction &I);
110 bool scalarizeVPIntrinsic(Instruction &I);
111 bool foldExtractedCmps(Instruction &I);
112 bool foldSingleElementStore(Instruction &I);
113 bool scalarizeLoadExtract(Instruction &I);
114 bool foldShuffleOfBinops(Instruction &I);
115 bool foldShuffleOfCastops(Instruction &I);
116 bool foldShuffleOfShuffles(Instruction &I);
117 bool foldShuffleToIdentity(Instruction &I);
118 bool foldShuffleFromReductions(Instruction &I);
119 bool foldTruncFromReductions(Instruction &I);
120 bool foldSelectShuffle(Instruction &I, bool FromReduction = false);
121
122 void replaceValue(Value &Old, Value &New) {
123 Old.replaceAllUsesWith(&New);
124 if (auto *NewI = dyn_cast<Instruction>(&New)) {
125 New.takeName(&Old);
126 Worklist.pushUsersToWorkList(*NewI);
127 Worklist.pushValue(NewI);
128 }
129 Worklist.pushValue(&Old);
130 }
131
133 for (Value *Op : I.operands())
134 Worklist.pushValue(Op);
135 Worklist.remove(&I);
136 I.eraseFromParent();
137 }
138};
139} // namespace
140
141/// Return the source operand of a potentially bitcasted value. If there is no
142/// bitcast, return the input value itself.
144 while (auto *BitCast = dyn_cast<BitCastInst>(V))
145 V = BitCast->getOperand(0);
146 return V;
147}
148
149static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI) {
150 // Do not widen load if atomic/volatile or under asan/hwasan/memtag/tsan.
151 // The widened load may load data from dirty regions or create data races
152 // non-existent in the source.
153 if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
154 Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
156 return false;
157
158 // We are potentially transforming byte-sized (8-bit) memory accesses, so make
159 // sure we have all of our type-based constraints in place for this target.
160 Type *ScalarTy = Load->getType()->getScalarType();
161 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
162 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
163 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
164 ScalarSize % 8 != 0)
165 return false;
166
167 return true;
168}
169
170bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
171 // Match insert into fixed vector of scalar value.
172 // TODO: Handle non-zero insert index.
173 Value *Scalar;
174 if (!match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
175 !Scalar->hasOneUse())
176 return false;
177
178 // Optionally match an extract from another vector.
179 Value *X;
180 bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
181 if (!HasExtract)
182 X = Scalar;
183
184 auto *Load = dyn_cast<LoadInst>(X);
185 if (!canWidenLoad(Load, TTI))
186 return false;
187
188 Type *ScalarTy = Scalar->getType();
189 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
190 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
191
192 // Check safety of replacing the scalar load with a larger vector load.
193 // We use minimal alignment (maximum flexibility) because we only care about
194 // the dereferenceable region. When calculating cost and creating a new op,
195 // we may use a larger value based on alignment attributes.
196 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
197 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
198
199 unsigned MinVecNumElts = MinVectorSize / ScalarSize;
200 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
201 unsigned OffsetEltIndex = 0;
202 Align Alignment = Load->getAlign();
203 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), *DL, Load, &AC,
204 &DT)) {
205 // It is not safe to load directly from the pointer, but we can still peek
206 // through gep offsets and check if it safe to load from a base address with
207 // updated alignment. If it is, we can shuffle the element(s) into place
208 // after loading.
209 unsigned OffsetBitWidth = DL->getIndexTypeSizeInBits(SrcPtr->getType());
210 APInt Offset(OffsetBitWidth, 0);
212
213 // We want to shuffle the result down from a high element of a vector, so
214 // the offset must be positive.
215 if (Offset.isNegative())
216 return false;
217
218 // The offset must be a multiple of the scalar element to shuffle cleanly
219 // in the element's size.
220 uint64_t ScalarSizeInBytes = ScalarSize / 8;
221 if (Offset.urem(ScalarSizeInBytes) != 0)
222 return false;
223
224 // If we load MinVecNumElts, will our target element still be loaded?
225 OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
226 if (OffsetEltIndex >= MinVecNumElts)
227 return false;
228
229 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), *DL, Load, &AC,
230 &DT))
231 return false;
232
233 // Update alignment with offset value. Note that the offset could be negated
234 // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
235 // negation does not change the result of the alignment calculation.
236 Alignment = commonAlignment(Alignment, Offset.getZExtValue());
237 }
238
239 // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
240 // Use the greater of the alignment on the load or its source pointer.
241 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
242 Type *LoadTy = Load->getType();
243 unsigned AS = Load->getPointerAddressSpace();
244 InstructionCost OldCost =
245 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
246 APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
248 OldCost +=
249 TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
250 /* Insert */ true, HasExtract, CostKind);
251
252 // New pattern: load VecPtr
253 InstructionCost NewCost =
254 TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
255 // Optionally, we are shuffling the loaded vector element(s) into place.
256 // For the mask set everything but element 0 to undef to prevent poison from
257 // propagating from the extra loaded memory. This will also optionally
258 // shrink/grow the vector from the loaded size to the output size.
259 // We assume this operation has no cost in codegen if there was no offset.
260 // Note that we could use freeze to avoid poison problems, but then we might
261 // still need a shuffle to change the vector size.
262 auto *Ty = cast<FixedVectorType>(I.getType());
263 unsigned OutputNumElts = Ty->getNumElements();
265 assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
266 Mask[0] = OffsetEltIndex;
267 if (OffsetEltIndex)
268 NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
269
270 // We can aggressively convert to the vector form because the backend can
271 // invert this transform if it does not result in a performance win.
272 if (OldCost < NewCost || !NewCost.isValid())
273 return false;
274
275 // It is safe and potentially profitable to load a vector directly:
276 // inselt undef, load Scalar, 0 --> load VecPtr
277 IRBuilder<> Builder(Load);
278 Value *CastedPtr =
279 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
280 Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
281 VecLd = Builder.CreateShuffleVector(VecLd, Mask);
282
283 replaceValue(I, *VecLd);
284 ++NumVecLoad;
285 return true;
286}
287
288/// If we are loading a vector and then inserting it into a larger vector with
289/// undefined elements, try to load the larger vector and eliminate the insert.
290/// This removes a shuffle in IR and may allow combining of other loaded values.
291bool VectorCombine::widenSubvectorLoad(Instruction &I) {
292 // Match subvector insert of fixed vector.
293 auto *Shuf = cast<ShuffleVectorInst>(&I);
294 if (!Shuf->isIdentityWithPadding())
295 return false;
296
297 // Allow a non-canonical shuffle mask that is choosing elements from op1.
298 unsigned NumOpElts =
299 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
300 unsigned OpIndex = any_of(Shuf->getShuffleMask(), [&NumOpElts](int M) {
301 return M >= (int)(NumOpElts);
302 });
303
304 auto *Load = dyn_cast<LoadInst>(Shuf->getOperand(OpIndex));
305 if (!canWidenLoad(Load, TTI))
306 return false;
307
308 // We use minimal alignment (maximum flexibility) because we only care about
309 // the dereferenceable region. When calculating cost and creating a new op,
310 // we may use a larger value based on alignment attributes.
311 auto *Ty = cast<FixedVectorType>(I.getType());
312 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
313 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
314 Align Alignment = Load->getAlign();
315 if (!isSafeToLoadUnconditionally(SrcPtr, Ty, Align(1), *DL, Load, &AC, &DT))
316 return false;
317
318 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
319 Type *LoadTy = Load->getType();
320 unsigned AS = Load->getPointerAddressSpace();
321
322 // Original pattern: insert_subvector (load PtrOp)
323 // This conservatively assumes that the cost of a subvector insert into an
324 // undef value is 0. We could add that cost if the cost model accurately
325 // reflects the real cost of that operation.
326 InstructionCost OldCost =
327 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
328
329 // New pattern: load PtrOp
330 InstructionCost NewCost =
331 TTI.getMemoryOpCost(Instruction::Load, Ty, Alignment, AS);
332
333 // We can aggressively convert to the vector form because the backend can
334 // invert this transform if it does not result in a performance win.
335 if (OldCost < NewCost || !NewCost.isValid())
336 return false;
337
338 IRBuilder<> Builder(Load);
339 Value *CastedPtr =
340 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
341 Value *VecLd = Builder.CreateAlignedLoad(Ty, CastedPtr, Alignment);
342 replaceValue(I, *VecLd);
343 ++NumVecLoad;
344 return true;
345}
346
347/// Determine which, if any, of the inputs should be replaced by a shuffle
348/// followed by extract from a different index.
349ExtractElementInst *VectorCombine::getShuffleExtract(
351 unsigned PreferredExtractIndex = InvalidIndex) const {
352 auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
353 auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
354 assert(Index0C && Index1C && "Expected constant extract indexes");
355
356 unsigned Index0 = Index0C->getZExtValue();
357 unsigned Index1 = Index1C->getZExtValue();
358
359 // If the extract indexes are identical, no shuffle is needed.
360 if (Index0 == Index1)
361 return nullptr;
362
363 Type *VecTy = Ext0->getVectorOperand()->getType();
365 assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
366 InstructionCost Cost0 =
367 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
368 InstructionCost Cost1 =
369 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
370
371 // If both costs are invalid no shuffle is needed
372 if (!Cost0.isValid() && !Cost1.isValid())
373 return nullptr;
374
375 // We are extracting from 2 different indexes, so one operand must be shuffled
376 // before performing a vector operation and/or extract. The more expensive
377 // extract will be replaced by a shuffle.
378 if (Cost0 > Cost1)
379 return Ext0;
380 if (Cost1 > Cost0)
381 return Ext1;
382
383 // If the costs are equal and there is a preferred extract index, shuffle the
384 // opposite operand.
385 if (PreferredExtractIndex == Index0)
386 return Ext1;
387 if (PreferredExtractIndex == Index1)
388 return Ext0;
389
390 // Otherwise, replace the extract with the higher index.
391 return Index0 > Index1 ? Ext0 : Ext1;
392}
393
394/// Compare the relative costs of 2 extracts followed by scalar operation vs.
395/// vector operation(s) followed by extract. Return true if the existing
396/// instructions are cheaper than a vector alternative. Otherwise, return false
397/// and if one of the extracts should be transformed to a shufflevector, set
398/// \p ConvertToShuffle to that extract instruction.
399bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
400 ExtractElementInst *Ext1,
401 const Instruction &I,
402 ExtractElementInst *&ConvertToShuffle,
403 unsigned PreferredExtractIndex) {
404 auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getOperand(1));
405 auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getOperand(1));
406 assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes");
407
408 unsigned Opcode = I.getOpcode();
409 Type *ScalarTy = Ext0->getType();
410 auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
411 InstructionCost ScalarOpCost, VectorOpCost;
412
413 // Get cost estimates for scalar and vector versions of the operation.
414 bool IsBinOp = Instruction::isBinaryOp(Opcode);
415 if (IsBinOp) {
416 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
417 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
418 } else {
419 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
420 "Expected a compare");
421 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
422 ScalarOpCost = TTI.getCmpSelInstrCost(
423 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
424 VectorOpCost = TTI.getCmpSelInstrCost(
425 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
426 }
427
428 // Get cost estimates for the extract elements. These costs will factor into
429 // both sequences.
430 unsigned Ext0Index = Ext0IndexC->getZExtValue();
431 unsigned Ext1Index = Ext1IndexC->getZExtValue();
433
434 InstructionCost Extract0Cost =
435 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Ext0Index);
436 InstructionCost Extract1Cost =
437 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Ext1Index);
438
439 // A more expensive extract will always be replaced by a splat shuffle.
440 // For example, if Ext0 is more expensive:
441 // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
442 // extelt (opcode (splat V0, Ext0), V1), Ext1
443 // TODO: Evaluate whether that always results in lowest cost. Alternatively,
444 // check the cost of creating a broadcast shuffle and shuffling both
445 // operands to element 0.
446 InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
447
448 // Extra uses of the extracts mean that we include those costs in the
449 // vector total because those instructions will not be eliminated.
450 InstructionCost OldCost, NewCost;
451 if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
452 // Handle a special case. If the 2 extracts are identical, adjust the
453 // formulas to account for that. The extra use charge allows for either the
454 // CSE'd pattern or an unoptimized form with identical values:
455 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
456 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
457 : !Ext0->hasOneUse() || !Ext1->hasOneUse();
458 OldCost = CheapExtractCost + ScalarOpCost;
459 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
460 } else {
461 // Handle the general case. Each extract is actually a different value:
462 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
463 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
464 NewCost = VectorOpCost + CheapExtractCost +
465 !Ext0->hasOneUse() * Extract0Cost +
466 !Ext1->hasOneUse() * Extract1Cost;
467 }
468
469 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
470 if (ConvertToShuffle) {
471 if (IsBinOp && DisableBinopExtractShuffle)
472 return true;
473
474 // If we are extracting from 2 different indexes, then one operand must be
475 // shuffled before performing the vector operation. The shuffle mask is
476 // poison except for 1 lane that is being translated to the remaining
477 // extraction lane. Therefore, it is a splat shuffle. Ex:
478 // ShufMask = { poison, poison, 0, poison }
479 // TODO: The cost model has an option for a "broadcast" shuffle
480 // (splat-from-element-0), but no option for a more general splat.
481 NewCost +=
483 }
484
485 // Aggressively form a vector op if the cost is equal because the transform
486 // may enable further optimization.
487 // Codegen can reverse this transform (scalarize) if it was not profitable.
488 return OldCost < NewCost;
489}
490
491/// Create a shuffle that translates (shifts) 1 element from the input vector
492/// to a new element location.
493static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
494 unsigned NewIndex, IRBuilder<> &Builder) {
495 // The shuffle mask is poison except for 1 lane that is being translated
496 // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
497 // ShufMask = { 2, poison, poison, poison }
498 auto *VecTy = cast<FixedVectorType>(Vec->getType());
499 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
500 ShufMask[NewIndex] = OldIndex;
501 return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
502}
503
504/// Given an extract element instruction with constant index operand, shuffle
505/// the source vector (shift the scalar element) to a NewIndex for extraction.
506/// Return null if the input can be constant folded, so that we are not creating
507/// unnecessary instructions.
509 unsigned NewIndex,
510 IRBuilder<> &Builder) {
511 // Shufflevectors can only be created for fixed-width vectors.
512 if (!isa<FixedVectorType>(ExtElt->getOperand(0)->getType()))
513 return nullptr;
514
515 // If the extract can be constant-folded, this code is unsimplified. Defer
516 // to other passes to handle that.
517 Value *X = ExtElt->getVectorOperand();
518 Value *C = ExtElt->getIndexOperand();
519 assert(isa<ConstantInt>(C) && "Expected a constant index operand");
520 if (isa<Constant>(X))
521 return nullptr;
522
523 Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
524 NewIndex, Builder);
525 return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
526}
527
528/// Try to reduce extract element costs by converting scalar compares to vector
529/// compares followed by extract.
530/// cmp (ext0 V0, C), (ext1 V1, C)
531void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
533 assert(isa<CmpInst>(&I) && "Expected a compare");
534 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
535 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
536 "Expected matching constant extract indexes");
537
538 // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
539 ++NumVecCmp;
540 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
541 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
542 Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
543 Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
544 replaceValue(I, *NewExt);
545}
546
547/// Try to reduce extract element costs by converting scalar binops to vector
548/// binops followed by extract.
549/// bo (ext0 V0, C), (ext1 V1, C)
550void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
552 assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
553 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
554 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
555 "Expected matching constant extract indexes");
556
557 // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
558 ++NumVecBO;
559 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
560 Value *VecBO =
561 Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
562
563 // All IR flags are safe to back-propagate because any potential poison
564 // created in unused vector elements is discarded by the extract.
565 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
566 VecBOInst->copyIRFlags(&I);
567
568 Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
569 replaceValue(I, *NewExt);
570}
571
572/// Match an instruction with extracted vector operands.
573bool VectorCombine::foldExtractExtract(Instruction &I) {
574 // It is not safe to transform things like div, urem, etc. because we may
575 // create undefined behavior when executing those on unknown vector elements.
577 return false;
578
579 Instruction *I0, *I1;
581 if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
583 return false;
584
585 Value *V0, *V1;
586 uint64_t C0, C1;
587 if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
588 !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
589 V0->getType() != V1->getType())
590 return false;
591
592 // If the scalar value 'I' is going to be re-inserted into a vector, then try
593 // to create an extract to that same element. The extract/insert can be
594 // reduced to a "select shuffle".
595 // TODO: If we add a larger pattern match that starts from an insert, this
596 // probably becomes unnecessary.
597 auto *Ext0 = cast<ExtractElementInst>(I0);
598 auto *Ext1 = cast<ExtractElementInst>(I1);
599 uint64_t InsertIndex = InvalidIndex;
600 if (I.hasOneUse())
601 match(I.user_back(),
602 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
603
604 ExtractElementInst *ExtractToChange;
605 if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
606 return false;
607
608 if (ExtractToChange) {
609 unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
610 ExtractElementInst *NewExtract =
611 translateExtract(ExtractToChange, CheapExtractIdx, Builder);
612 if (!NewExtract)
613 return false;
614 if (ExtractToChange == Ext0)
615 Ext0 = NewExtract;
616 else
617 Ext1 = NewExtract;
618 }
619
620 if (Pred != CmpInst::BAD_ICMP_PREDICATE)
621 foldExtExtCmp(Ext0, Ext1, I);
622 else
623 foldExtExtBinop(Ext0, Ext1, I);
624
625 Worklist.push(Ext0);
626 Worklist.push(Ext1);
627 return true;
628}
629
630/// Try to replace an extract + scalar fneg + insert with a vector fneg +
631/// shuffle.
632bool VectorCombine::foldInsExtFNeg(Instruction &I) {
633 // Match an insert (op (extract)) pattern.
634 Value *DestVec;
636 Instruction *FNeg;
637 if (!match(&I, m_InsertElt(m_Value(DestVec), m_OneUse(m_Instruction(FNeg)),
639 return false;
640
641 // Note: This handles the canonical fneg instruction and "fsub -0.0, X".
642 Value *SrcVec;
643 Instruction *Extract;
644 if (!match(FNeg, m_FNeg(m_CombineAnd(
645 m_Instruction(Extract),
647 return false;
648
649 // TODO: We could handle this with a length-changing shuffle.
650 auto *VecTy = cast<FixedVectorType>(I.getType());
651 if (SrcVec->getType() != VecTy)
652 return false;
653
654 // Ignore bogus insert/extract index.
655 unsigned NumElts = VecTy->getNumElements();
656 if (Index >= NumElts)
657 return false;
658
659 // We are inserting the negated element into the same lane that we extracted
660 // from. This is equivalent to a select-shuffle that chooses all but the
661 // negated element from the destination vector.
662 SmallVector<int> Mask(NumElts);
663 std::iota(Mask.begin(), Mask.end(), 0);
664 Mask[Index] = Index + NumElts;
665
666 Type *ScalarTy = VecTy->getScalarType();
668 InstructionCost OldCost =
669 TTI.getArithmeticInstrCost(Instruction::FNeg, ScalarTy) +
671
672 // If the extract has one use, it will be eliminated, so count it in the
673 // original cost. If it has more than one use, ignore the cost because it will
674 // be the same before/after.
675 if (Extract->hasOneUse())
676 OldCost += TTI.getVectorInstrCost(*Extract, VecTy, CostKind, Index);
677
678 InstructionCost NewCost =
679 TTI.getArithmeticInstrCost(Instruction::FNeg, VecTy) +
681
682 if (NewCost > OldCost)
683 return false;
684
685 // insertelt DestVec, (fneg (extractelt SrcVec, Index)), Index -->
686 // shuffle DestVec, (fneg SrcVec), Mask
687 Value *VecFNeg = Builder.CreateFNegFMF(SrcVec, FNeg);
688 Value *Shuf = Builder.CreateShuffleVector(DestVec, VecFNeg, Mask);
689 replaceValue(I, *Shuf);
690 return true;
691}
692
693/// If this is a bitcast of a shuffle, try to bitcast the source vector to the
694/// destination type followed by shuffle. This can enable further transforms by
695/// moving bitcasts or shuffles together.
696bool VectorCombine::foldBitcastShuffle(Instruction &I) {
697 Value *V0, *V1;
699 if (!match(&I, m_BitCast(m_OneUse(
700 m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(Mask))))))
701 return false;
702
703 // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
704 // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
705 // mask for scalable type is a splat or not.
706 // 2) Disallow non-vector casts.
707 // TODO: We could allow any shuffle.
708 auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
709 auto *SrcTy = dyn_cast<FixedVectorType>(V0->getType());
710 if (!DestTy || !SrcTy)
711 return false;
712
713 unsigned DestEltSize = DestTy->getScalarSizeInBits();
714 unsigned SrcEltSize = SrcTy->getScalarSizeInBits();
715 if (SrcTy->getPrimitiveSizeInBits() % DestEltSize != 0)
716 return false;
717
718 bool IsUnary = isa<UndefValue>(V1);
719
720 // For binary shuffles, only fold bitcast(shuffle(X,Y))
721 // if it won't increase the number of bitcasts.
722 if (!IsUnary) {
723 auto *BCTy0 = dyn_cast<FixedVectorType>(peekThroughBitcasts(V0)->getType());
724 auto *BCTy1 = dyn_cast<FixedVectorType>(peekThroughBitcasts(V1)->getType());
725 if (!(BCTy0 && BCTy0->getElementType() == DestTy->getElementType()) &&
726 !(BCTy1 && BCTy1->getElementType() == DestTy->getElementType()))
727 return false;
728 }
729
730 SmallVector<int, 16> NewMask;
731 if (DestEltSize <= SrcEltSize) {
732 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
733 // always be expanded to the equivalent form choosing narrower elements.
734 assert(SrcEltSize % DestEltSize == 0 && "Unexpected shuffle mask");
735 unsigned ScaleFactor = SrcEltSize / DestEltSize;
736 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
737 } else {
738 // The bitcast is from narrow elements to wide elements. The shuffle mask
739 // must choose consecutive elements to allow casting first.
740 assert(DestEltSize % SrcEltSize == 0 && "Unexpected shuffle mask");
741 unsigned ScaleFactor = DestEltSize / SrcEltSize;
742 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
743 return false;
744 }
745
746 // Bitcast the shuffle src - keep its original width but using the destination
747 // scalar type.
748 unsigned NumSrcElts = SrcTy->getPrimitiveSizeInBits() / DestEltSize;
749 auto *NewShuffleTy =
750 FixedVectorType::get(DestTy->getScalarType(), NumSrcElts);
751 auto *OldShuffleTy =
752 FixedVectorType::get(SrcTy->getScalarType(), Mask.size());
753 unsigned NumOps = IsUnary ? 1 : 2;
754
755 // The new shuffle must not cost more than the old shuffle.
761
762 InstructionCost DestCost =
763 TTI.getShuffleCost(SK, NewShuffleTy, NewMask, CK) +
764 (NumOps * TTI.getCastInstrCost(Instruction::BitCast, NewShuffleTy, SrcTy,
765 TargetTransformInfo::CastContextHint::None,
766 CK));
767 InstructionCost SrcCost =
768 TTI.getShuffleCost(SK, SrcTy, Mask, CK) +
769 TTI.getCastInstrCost(Instruction::BitCast, DestTy, OldShuffleTy,
770 TargetTransformInfo::CastContextHint::None, CK);
771 if (DestCost > SrcCost || !DestCost.isValid())
772 return false;
773
774 // bitcast (shuf V0, V1, MaskC) --> shuf (bitcast V0), (bitcast V1), MaskC'
775 ++NumShufOfBitcast;
776 Value *CastV0 = Builder.CreateBitCast(peekThroughBitcasts(V0), NewShuffleTy);
777 Value *CastV1 = Builder.CreateBitCast(peekThroughBitcasts(V1), NewShuffleTy);
778 Value *Shuf = Builder.CreateShuffleVector(CastV0, CastV1, NewMask);
779 replaceValue(I, *Shuf);
780 return true;
781}
782
783/// VP Intrinsics whose vector operands are both splat values may be simplified
784/// into the scalar version of the operation and the result splatted. This
785/// can lead to scalarization down the line.
786bool VectorCombine::scalarizeVPIntrinsic(Instruction &I) {
787 if (!isa<VPIntrinsic>(I))
788 return false;
789 VPIntrinsic &VPI = cast<VPIntrinsic>(I);
790 Value *Op0 = VPI.getArgOperand(0);
791 Value *Op1 = VPI.getArgOperand(1);
792
793 if (!isSplatValue(Op0) || !isSplatValue(Op1))
794 return false;
795
796 // Check getSplatValue early in this function, to avoid doing unnecessary
797 // work.
798 Value *ScalarOp0 = getSplatValue(Op0);
799 Value *ScalarOp1 = getSplatValue(Op1);
800 if (!ScalarOp0 || !ScalarOp1)
801 return false;
802
803 // For the binary VP intrinsics supported here, the result on disabled lanes
804 // is a poison value. For now, only do this simplification if all lanes
805 // are active.
806 // TODO: Relax the condition that all lanes are active by using insertelement
807 // on inactive lanes.
808 auto IsAllTrueMask = [](Value *MaskVal) {
809 if (Value *SplattedVal = getSplatValue(MaskVal))
810 if (auto *ConstValue = dyn_cast<Constant>(SplattedVal))
811 return ConstValue->isAllOnesValue();
812 return false;
813 };
814 if (!IsAllTrueMask(VPI.getArgOperand(2)))
815 return false;
816
817 // Check to make sure we support scalarization of the intrinsic
818 Intrinsic::ID IntrID = VPI.getIntrinsicID();
819 if (!VPBinOpIntrinsic::isVPBinOp(IntrID))
820 return false;
821
822 // Calculate cost of splatting both operands into vectors and the vector
823 // intrinsic
824 VectorType *VecTy = cast<VectorType>(VPI.getType());
827 if (auto *FVTy = dyn_cast<FixedVectorType>(VecTy))
828 Mask.resize(FVTy->getNumElements(), 0);
829 InstructionCost SplatCost =
830 TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind, 0) +
832
833 // Calculate the cost of the VP Intrinsic
835 for (Value *V : VPI.args())
836 Args.push_back(V->getType());
837 IntrinsicCostAttributes Attrs(IntrID, VecTy, Args);
838 InstructionCost VectorOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind);
839 InstructionCost OldCost = 2 * SplatCost + VectorOpCost;
840
841 // Determine scalar opcode
842 std::optional<unsigned> FunctionalOpcode =
844 std::optional<Intrinsic::ID> ScalarIntrID = std::nullopt;
845 if (!FunctionalOpcode) {
846 ScalarIntrID = VPI.getFunctionalIntrinsicID();
847 if (!ScalarIntrID)
848 return false;
849 }
850
851 // Calculate cost of scalarizing
852 InstructionCost ScalarOpCost = 0;
853 if (ScalarIntrID) {
854 IntrinsicCostAttributes Attrs(*ScalarIntrID, VecTy->getScalarType(), Args);
855 ScalarOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind);
856 } else {
857 ScalarOpCost =
858 TTI.getArithmeticInstrCost(*FunctionalOpcode, VecTy->getScalarType());
859 }
860
861 // The existing splats may be kept around if other instructions use them.
862 InstructionCost CostToKeepSplats =
863 (SplatCost * !Op0->hasOneUse()) + (SplatCost * !Op1->hasOneUse());
864 InstructionCost NewCost = ScalarOpCost + SplatCost + CostToKeepSplats;
865
866 LLVM_DEBUG(dbgs() << "Found a VP Intrinsic to scalarize: " << VPI
867 << "\n");
868 LLVM_DEBUG(dbgs() << "Cost of Intrinsic: " << OldCost
869 << ", Cost of scalarizing:" << NewCost << "\n");
870
871 // We want to scalarize unless the vector variant actually has lower cost.
872 if (OldCost < NewCost || !NewCost.isValid())
873 return false;
874
875 // Scalarize the intrinsic
876 ElementCount EC = cast<VectorType>(Op0->getType())->getElementCount();
877 Value *EVL = VPI.getArgOperand(3);
878
879 // If the VP op might introduce UB or poison, we can scalarize it provided
880 // that we know the EVL > 0: If the EVL is zero, then the original VP op
881 // becomes a no-op and thus won't be UB, so make sure we don't introduce UB by
882 // scalarizing it.
883 bool SafeToSpeculate;
884 if (ScalarIntrID)
885 SafeToSpeculate = Intrinsic::getAttributes(I.getContext(), *ScalarIntrID)
886 .hasFnAttr(Attribute::AttrKind::Speculatable);
887 else
889 *FunctionalOpcode, &VPI, nullptr, &AC, &DT);
890 if (!SafeToSpeculate &&
891 !isKnownNonZero(EVL, SimplifyQuery(*DL, &DT, &AC, &VPI)))
892 return false;
893
894 Value *ScalarVal =
895 ScalarIntrID
896 ? Builder.CreateIntrinsic(VecTy->getScalarType(), *ScalarIntrID,
897 {ScalarOp0, ScalarOp1})
898 : Builder.CreateBinOp((Instruction::BinaryOps)(*FunctionalOpcode),
899 ScalarOp0, ScalarOp1);
900
901 replaceValue(VPI, *Builder.CreateVectorSplat(EC, ScalarVal));
902 return true;
903}
904
905/// Match a vector binop or compare instruction with at least one inserted
906/// scalar operand and convert to scalar binop/cmp followed by insertelement.
907bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
909 Value *Ins0, *Ins1;
910 if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
911 !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
912 return false;
913
914 // Do not convert the vector condition of a vector select into a scalar
915 // condition. That may cause problems for codegen because of differences in
916 // boolean formats and register-file transfers.
917 // TODO: Can we account for that in the cost model?
918 bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
919 if (IsCmp)
920 for (User *U : I.users())
921 if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
922 return false;
923
924 // Match against one or both scalar values being inserted into constant
925 // vectors:
926 // vec_op VecC0, (inselt VecC1, V1, Index)
927 // vec_op (inselt VecC0, V0, Index), VecC1
928 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
929 // TODO: Deal with mismatched index constants and variable indexes?
930 Constant *VecC0 = nullptr, *VecC1 = nullptr;
931 Value *V0 = nullptr, *V1 = nullptr;
932 uint64_t Index0 = 0, Index1 = 0;
933 if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
934 m_ConstantInt(Index0))) &&
935 !match(Ins0, m_Constant(VecC0)))
936 return false;
937 if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
938 m_ConstantInt(Index1))) &&
939 !match(Ins1, m_Constant(VecC1)))
940 return false;
941
942 bool IsConst0 = !V0;
943 bool IsConst1 = !V1;
944 if (IsConst0 && IsConst1)
945 return false;
946 if (!IsConst0 && !IsConst1 && Index0 != Index1)
947 return false;
948
949 // Bail for single insertion if it is a load.
950 // TODO: Handle this once getVectorInstrCost can cost for load/stores.
951 auto *I0 = dyn_cast_or_null<Instruction>(V0);
952 auto *I1 = dyn_cast_or_null<Instruction>(V1);
953 if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
954 (IsConst1 && I0 && I0->mayReadFromMemory()))
955 return false;
956
957 uint64_t Index = IsConst0 ? Index1 : Index0;
958 Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
959 Type *VecTy = I.getType();
960 assert(VecTy->isVectorTy() &&
961 (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
962 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
963 ScalarTy->isPointerTy()) &&
964 "Unexpected types for insert element into binop or cmp");
965
966 unsigned Opcode = I.getOpcode();
967 InstructionCost ScalarOpCost, VectorOpCost;
968 if (IsCmp) {
969 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
970 ScalarOpCost = TTI.getCmpSelInstrCost(
971 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
972 VectorOpCost = TTI.getCmpSelInstrCost(
973 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
974 } else {
975 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
976 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
977 }
978
979 // Get cost estimate for the insert element. This cost will factor into
980 // both sequences.
983 Instruction::InsertElement, VecTy, CostKind, Index);
984 InstructionCost OldCost =
985 (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
986 InstructionCost NewCost = ScalarOpCost + InsertCost +
987 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
988 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
989
990 // We want to scalarize unless the vector variant actually has lower cost.
991 if (OldCost < NewCost || !NewCost.isValid())
992 return false;
993
994 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
995 // inselt NewVecC, (scalar_op V0, V1), Index
996 if (IsCmp)
997 ++NumScalarCmp;
998 else
999 ++NumScalarBO;
1000
1001 // For constant cases, extract the scalar element, this should constant fold.
1002 if (IsConst0)
1003 V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
1004 if (IsConst1)
1005 V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
1006
1007 Value *Scalar =
1008 IsCmp ? Builder.CreateCmp(Pred, V0, V1)
1009 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
1010
1011 Scalar->setName(I.getName() + ".scalar");
1012
1013 // All IR flags are safe to back-propagate. There is no potential for extra
1014 // poison to be created by the scalar instruction.
1015 if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
1016 ScalarInst->copyIRFlags(&I);
1017
1018 // Fold the vector constants in the original vectors into a new base vector.
1019 Value *NewVecC =
1020 IsCmp ? Builder.CreateCmp(Pred, VecC0, VecC1)
1021 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, VecC0, VecC1);
1022 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
1023 replaceValue(I, *Insert);
1024 return true;
1025}
1026
1027/// Try to combine a scalar binop + 2 scalar compares of extracted elements of
1028/// a vector into vector operations followed by extract. Note: The SLP pass
1029/// may miss this pattern because of implementation problems.
1030bool VectorCombine::foldExtractedCmps(Instruction &I) {
1031 // We are looking for a scalar binop of booleans.
1032 // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
1033 if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
1034 return false;
1035
1036 // The compare predicates should match, and each compare should have a
1037 // constant operand.
1038 // TODO: Relax the one-use constraints.
1039 Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
1040 Instruction *I0, *I1;
1041 Constant *C0, *C1;
1042 CmpInst::Predicate P0, P1;
1043 if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
1044 !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
1045 P0 != P1)
1046 return false;
1047
1048 // The compare operands must be extracts of the same vector with constant
1049 // extract indexes.
1050 // TODO: Relax the one-use constraints.
1051 Value *X;
1052 uint64_t Index0, Index1;
1053 if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
1055 return false;
1056
1057 auto *Ext0 = cast<ExtractElementInst>(I0);
1058 auto *Ext1 = cast<ExtractElementInst>(I1);
1059 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
1060 if (!ConvertToShuf)
1061 return false;
1062
1063 // The original scalar pattern is:
1064 // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
1065 CmpInst::Predicate Pred = P0;
1066 unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
1067 : Instruction::ICmp;
1068 auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
1069 if (!VecTy)
1070 return false;
1071
1073 InstructionCost OldCost =
1074 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
1075 OldCost += TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
1076 OldCost +=
1077 TTI.getCmpSelInstrCost(CmpOpcode, I0->getType(),
1078 CmpInst::makeCmpResultType(I0->getType()), Pred) *
1079 2;
1080 OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
1081
1082 // The proposed vector pattern is:
1083 // vcmp = cmp Pred X, VecC
1084 // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
1085 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
1086 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
1087 auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
1089 CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred);
1090 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
1091 ShufMask[CheapIndex] = ExpensiveIndex;
1093 ShufMask);
1094 NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
1095 NewCost += TTI.getVectorInstrCost(*Ext0, CmpTy, CostKind, CheapIndex);
1096
1097 // Aggressively form vector ops if the cost is equal because the transform
1098 // may enable further optimization.
1099 // Codegen can reverse this transform (scalarize) if it was not profitable.
1100 if (OldCost < NewCost || !NewCost.isValid())
1101 return false;
1102
1103 // Create a vector constant from the 2 scalar constants.
1104 SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
1105 PoisonValue::get(VecTy->getElementType()));
1106 CmpC[Index0] = C0;
1107 CmpC[Index1] = C1;
1108 Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
1109
1110 Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
1111 Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
1112 VCmp, Shuf);
1113 Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
1114 replaceValue(I, *NewExt);
1115 ++NumVecCmpBO;
1116 return true;
1117}
1118
1119// Check if memory loc modified between two instrs in the same BB
1122 const MemoryLocation &Loc, AAResults &AA) {
1123 unsigned NumScanned = 0;
1124 return std::any_of(Begin, End, [&](const Instruction &Instr) {
1125 return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
1126 ++NumScanned > MaxInstrsToScan;
1127 });
1128}
1129
1130namespace {
1131/// Helper class to indicate whether a vector index can be safely scalarized and
1132/// if a freeze needs to be inserted.
1133class ScalarizationResult {
1134 enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
1135
1136 StatusTy Status;
1137 Value *ToFreeze;
1138
1139 ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
1140 : Status(Status), ToFreeze(ToFreeze) {}
1141
1142public:
1143 ScalarizationResult(const ScalarizationResult &Other) = default;
1144 ~ScalarizationResult() {
1145 assert(!ToFreeze && "freeze() not called with ToFreeze being set");
1146 }
1147
1148 static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
1149 static ScalarizationResult safe() { return {StatusTy::Safe}; }
1150 static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
1151 return {StatusTy::SafeWithFreeze, ToFreeze};
1152 }
1153
1154 /// Returns true if the index can be scalarize without requiring a freeze.
1155 bool isSafe() const { return Status == StatusTy::Safe; }
1156 /// Returns true if the index cannot be scalarized.
1157 bool isUnsafe() const { return Status == StatusTy::Unsafe; }
1158 /// Returns true if the index can be scalarize, but requires inserting a
1159 /// freeze.
1160 bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
1161
1162 /// Reset the state of Unsafe and clear ToFreze if set.
1163 void discard() {
1164 ToFreeze = nullptr;
1165 Status = StatusTy::Unsafe;
1166 }
1167
1168 /// Freeze the ToFreeze and update the use in \p User to use it.
1169 void freeze(IRBuilder<> &Builder, Instruction &UserI) {
1170 assert(isSafeWithFreeze() &&
1171 "should only be used when freezing is required");
1172 assert(is_contained(ToFreeze->users(), &UserI) &&
1173 "UserI must be a user of ToFreeze");
1174 IRBuilder<>::InsertPointGuard Guard(Builder);
1175 Builder.SetInsertPoint(cast<Instruction>(&UserI));
1176 Value *Frozen =
1177 Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
1178 for (Use &U : make_early_inc_range((UserI.operands())))
1179 if (U.get() == ToFreeze)
1180 U.set(Frozen);
1181
1182 ToFreeze = nullptr;
1183 }
1184};
1185} // namespace
1186
1187/// Check if it is legal to scalarize a memory access to \p VecTy at index \p
1188/// Idx. \p Idx must access a valid vector element.
1189static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx,
1190 Instruction *CtxI,
1191 AssumptionCache &AC,
1192 const DominatorTree &DT) {
1193 // We do checks for both fixed vector types and scalable vector types.
1194 // This is the number of elements of fixed vector types,
1195 // or the minimum number of elements of scalable vector types.
1196 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1197
1198 if (auto *C = dyn_cast<ConstantInt>(Idx)) {
1199 if (C->getValue().ult(NumElements))
1200 return ScalarizationResult::safe();
1201 return ScalarizationResult::unsafe();
1202 }
1203
1204 unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
1205 APInt Zero(IntWidth, 0);
1206 APInt MaxElts(IntWidth, NumElements);
1207 ConstantRange ValidIndices(Zero, MaxElts);
1208 ConstantRange IdxRange(IntWidth, true);
1209
1210 if (isGuaranteedNotToBePoison(Idx, &AC)) {
1211 if (ValidIndices.contains(computeConstantRange(Idx, /* ForSigned */ false,
1212 true, &AC, CtxI, &DT)))
1213 return ScalarizationResult::safe();
1214 return ScalarizationResult::unsafe();
1215 }
1216
1217 // If the index may be poison, check if we can insert a freeze before the
1218 // range of the index is restricted.
1219 Value *IdxBase;
1220 ConstantInt *CI;
1221 if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
1222 IdxRange = IdxRange.binaryAnd(CI->getValue());
1223 } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
1224 IdxRange = IdxRange.urem(CI->getValue());
1225 }
1226
1227 if (ValidIndices.contains(IdxRange))
1228 return ScalarizationResult::safeWithFreeze(IdxBase);
1229 return ScalarizationResult::unsafe();
1230}
1231
1232/// The memory operation on a vector of \p ScalarType had alignment of
1233/// \p VectorAlignment. Compute the maximal, but conservatively correct,
1234/// alignment that will be valid for the memory operation on a single scalar
1235/// element of the same type with index \p Idx.
1237 Type *ScalarType, Value *Idx,
1238 const DataLayout &DL) {
1239 if (auto *C = dyn_cast<ConstantInt>(Idx))
1240 return commonAlignment(VectorAlignment,
1241 C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
1242 return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
1243}
1244
1245// Combine patterns like:
1246// %0 = load <4 x i32>, <4 x i32>* %a
1247// %1 = insertelement <4 x i32> %0, i32 %b, i32 1
1248// store <4 x i32> %1, <4 x i32>* %a
1249// to:
1250// %0 = bitcast <4 x i32>* %a to i32*
1251// %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
1252// store i32 %b, i32* %1
1253bool VectorCombine::foldSingleElementStore(Instruction &I) {
1254 auto *SI = cast<StoreInst>(&I);
1255 if (!SI->isSimple() || !isa<VectorType>(SI->getValueOperand()->getType()))
1256 return false;
1257
1258 // TODO: Combine more complicated patterns (multiple insert) by referencing
1259 // TargetTransformInfo.
1261 Value *NewElement;
1262 Value *Idx;
1263 if (!match(SI->getValueOperand(),
1264 m_InsertElt(m_Instruction(Source), m_Value(NewElement),
1265 m_Value(Idx))))
1266 return false;
1267
1268 if (auto *Load = dyn_cast<LoadInst>(Source)) {
1269 auto VecTy = cast<VectorType>(SI->getValueOperand()->getType());
1270 Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
1271 // Don't optimize for atomic/volatile load or store. Ensure memory is not
1272 // modified between, vector type matches store size, and index is inbounds.
1273 if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
1274 !DL->typeSizeEqualsStoreSize(Load->getType()->getScalarType()) ||
1275 SrcAddr != SI->getPointerOperand()->stripPointerCasts())
1276 return false;
1277
1278 auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT);
1279 if (ScalarizableIdx.isUnsafe() ||
1280 isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
1281 MemoryLocation::get(SI), AA))
1282 return false;
1283
1284 if (ScalarizableIdx.isSafeWithFreeze())
1285 ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
1286 Value *GEP = Builder.CreateInBoundsGEP(
1287 SI->getValueOperand()->getType(), SI->getPointerOperand(),
1288 {ConstantInt::get(Idx->getType(), 0), Idx});
1289 StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
1290 NSI->copyMetadata(*SI);
1291 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
1292 std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx,
1293 *DL);
1294 NSI->setAlignment(ScalarOpAlignment);
1295 replaceValue(I, *NSI);
1297 return true;
1298 }
1299
1300 return false;
1301}
1302
1303/// Try to scalarize vector loads feeding extractelement instructions.
1304bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
1305 Value *Ptr;
1306 if (!match(&I, m_Load(m_Value(Ptr))))
1307 return false;
1308
1309 auto *VecTy = cast<VectorType>(I.getType());
1310 auto *LI = cast<LoadInst>(&I);
1311 if (LI->isVolatile() || !DL->typeSizeEqualsStoreSize(VecTy->getScalarType()))
1312 return false;
1313
1314 InstructionCost OriginalCost =
1315 TTI.getMemoryOpCost(Instruction::Load, VecTy, LI->getAlign(),
1316 LI->getPointerAddressSpace());
1317 InstructionCost ScalarizedCost = 0;
1318
1319 Instruction *LastCheckedInst = LI;
1320 unsigned NumInstChecked = 0;
1322 auto FailureGuard = make_scope_exit([&]() {
1323 // If the transform is aborted, discard the ScalarizationResults.
1324 for (auto &Pair : NeedFreeze)
1325 Pair.second.discard();
1326 });
1327
1328 // Check if all users of the load are extracts with no memory modifications
1329 // between the load and the extract. Compute the cost of both the original
1330 // code and the scalarized version.
1331 for (User *U : LI->users()) {
1332 auto *UI = dyn_cast<ExtractElementInst>(U);
1333 if (!UI || UI->getParent() != LI->getParent())
1334 return false;
1335
1336 // Check if any instruction between the load and the extract may modify
1337 // memory.
1338 if (LastCheckedInst->comesBefore(UI)) {
1339 for (Instruction &I :
1340 make_range(std::next(LI->getIterator()), UI->getIterator())) {
1341 // Bail out if we reached the check limit or the instruction may write
1342 // to memory.
1343 if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
1344 return false;
1345 NumInstChecked++;
1346 }
1347 LastCheckedInst = UI;
1348 }
1349
1350 auto ScalarIdx = canScalarizeAccess(VecTy, UI->getOperand(1), &I, AC, DT);
1351 if (ScalarIdx.isUnsafe())
1352 return false;
1353 if (ScalarIdx.isSafeWithFreeze()) {
1354 NeedFreeze.try_emplace(UI, ScalarIdx);
1355 ScalarIdx.discard();
1356 }
1357
1358 auto *Index = dyn_cast<ConstantInt>(UI->getOperand(1));
1360 OriginalCost +=
1361 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
1362 Index ? Index->getZExtValue() : -1);
1363 ScalarizedCost +=
1364 TTI.getMemoryOpCost(Instruction::Load, VecTy->getElementType(),
1365 Align(1), LI->getPointerAddressSpace());
1366 ScalarizedCost += TTI.getAddressComputationCost(VecTy->getElementType());
1367 }
1368
1369 if (ScalarizedCost >= OriginalCost)
1370 return false;
1371
1372 // Replace extracts with narrow scalar loads.
1373 for (User *U : LI->users()) {
1374 auto *EI = cast<ExtractElementInst>(U);
1375 Value *Idx = EI->getOperand(1);
1376
1377 // Insert 'freeze' for poison indexes.
1378 auto It = NeedFreeze.find(EI);
1379 if (It != NeedFreeze.end())
1380 It->second.freeze(Builder, *cast<Instruction>(Idx));
1381
1382 Builder.SetInsertPoint(EI);
1383 Value *GEP =
1384 Builder.CreateInBoundsGEP(VecTy, Ptr, {Builder.getInt32(0), Idx});
1385 auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
1386 VecTy->getElementType(), GEP, EI->getName() + ".scalar"));
1387
1388 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
1389 LI->getAlign(), VecTy->getElementType(), Idx, *DL);
1390 NewLoad->setAlignment(ScalarOpAlignment);
1391
1392 replaceValue(*EI, *NewLoad);
1393 }
1394
1395 FailureGuard.release();
1396 return true;
1397}
1398
1399/// Try to convert "shuffle (binop), (binop)" into "binop (shuffle), (shuffle)".
1400bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
1401 BinaryOperator *B0, *B1;
1402 ArrayRef<int> OldMask;
1403 if (!match(&I, m_Shuffle(m_OneUse(m_BinOp(B0)), m_OneUse(m_BinOp(B1)),
1404 m_Mask(OldMask))))
1405 return false;
1406
1407 // Don't introduce poison into div/rem.
1408 if (any_of(OldMask, [](int M) { return M == PoisonMaskElem; }) &&
1409 B0->isIntDivRem())
1410 return false;
1411
1412 // TODO: Add support for addlike etc.
1413 Instruction::BinaryOps Opcode = B0->getOpcode();
1414 if (Opcode != B1->getOpcode())
1415 return false;
1416
1417 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
1418 auto *BinOpTy = dyn_cast<FixedVectorType>(B0->getType());
1419 if (!ShuffleDstTy || !BinOpTy)
1420 return false;
1421
1422 unsigned NumSrcElts = BinOpTy->getNumElements();
1423
1424 // If we have something like "add X, Y" and "add Z, X", swap ops to match.
1425 Value *X = B0->getOperand(0), *Y = B0->getOperand(1);
1426 Value *Z = B1->getOperand(0), *W = B1->getOperand(1);
1427 if (BinaryOperator::isCommutative(Opcode) && X != Z && Y != W &&
1428 (X == W || Y == Z))
1429 std::swap(X, Y);
1430
1431 auto ConvertToUnary = [NumSrcElts](int &M) {
1432 if (M >= (int)NumSrcElts)
1433 M -= NumSrcElts;
1434 };
1435
1436 SmallVector<int> NewMask0(OldMask.begin(), OldMask.end());
1438 if (X == Z) {
1439 llvm::for_each(NewMask0, ConvertToUnary);
1441 Z = PoisonValue::get(BinOpTy);
1442 }
1443
1444 SmallVector<int> NewMask1(OldMask.begin(), OldMask.end());
1446 if (Y == W) {
1447 llvm::for_each(NewMask1, ConvertToUnary);
1449 W = PoisonValue::get(BinOpTy);
1450 }
1451
1452 // Try to replace a binop with a shuffle if the shuffle is not costly.
1454
1455 InstructionCost OldCost =
1456 TTI.getArithmeticInstrCost(B0->getOpcode(), BinOpTy, CostKind) +
1457 TTI.getArithmeticInstrCost(B1->getOpcode(), BinOpTy, CostKind) +
1459 OldMask, CostKind, 0, nullptr, {B0, B1}, &I);
1460
1461 InstructionCost NewCost =
1462 TTI.getShuffleCost(SK0, BinOpTy, NewMask0, CostKind, 0, nullptr, {X, Z}) +
1463 TTI.getShuffleCost(SK1, BinOpTy, NewMask1, CostKind, 0, nullptr, {Y, W}) +
1464 TTI.getArithmeticInstrCost(Opcode, ShuffleDstTy, CostKind);
1465
1466 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two binops: " << I
1467 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1468 << "\n");
1469 if (NewCost >= OldCost)
1470 return false;
1471
1472 Value *Shuf0 = Builder.CreateShuffleVector(X, Z, NewMask0);
1473 Value *Shuf1 = Builder.CreateShuffleVector(Y, W, NewMask1);
1474 Value *NewBO = Builder.CreateBinOp(Opcode, Shuf0, Shuf1);
1475
1476 // Intersect flags from the old binops.
1477 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
1478 NewInst->copyIRFlags(B0);
1479 NewInst->andIRFlags(B1);
1480 }
1481
1482 Worklist.pushValue(Shuf0);
1483 Worklist.pushValue(Shuf1);
1484 replaceValue(I, *NewBO);
1485 return true;
1486}
1487
1488/// Try to convert "shuffle (castop), (castop)" with a shared castop operand
1489/// into "castop (shuffle)".
1490bool VectorCombine::foldShuffleOfCastops(Instruction &I) {
1491 Value *V0, *V1;
1492 ArrayRef<int> OldMask;
1493 if (!match(&I, m_Shuffle(m_OneUse(m_Value(V0)), m_OneUse(m_Value(V1)),
1494 m_Mask(OldMask))))
1495 return false;
1496
1497 auto *C0 = dyn_cast<CastInst>(V0);
1498 auto *C1 = dyn_cast<CastInst>(V1);
1499 if (!C0 || !C1)
1500 return false;
1501
1502 Instruction::CastOps Opcode = C0->getOpcode();
1503 if (C0->getSrcTy() != C1->getSrcTy())
1504 return false;
1505
1506 // Handle shuffle(zext_nneg(x), sext(y)) -> sext(shuffle(x,y)) folds.
1507 if (Opcode != C1->getOpcode()) {
1508 if (match(C0, m_SExtLike(m_Value())) && match(C1, m_SExtLike(m_Value())))
1509 Opcode = Instruction::SExt;
1510 else
1511 return false;
1512 }
1513
1514 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
1515 auto *CastDstTy = dyn_cast<FixedVectorType>(C0->getDestTy());
1516 auto *CastSrcTy = dyn_cast<FixedVectorType>(C0->getSrcTy());
1517 if (!ShuffleDstTy || !CastDstTy || !CastSrcTy)
1518 return false;
1519
1520 unsigned NumSrcElts = CastSrcTy->getNumElements();
1521 unsigned NumDstElts = CastDstTy->getNumElements();
1522 assert((NumDstElts == NumSrcElts || Opcode == Instruction::BitCast) &&
1523 "Only bitcasts expected to alter src/dst element counts");
1524
1525 // Check for bitcasting of unscalable vector types.
1526 // e.g. <32 x i40> -> <40 x i32>
1527 if (NumDstElts != NumSrcElts && (NumSrcElts % NumDstElts) != 0 &&
1528 (NumDstElts % NumSrcElts) != 0)
1529 return false;
1530
1531 SmallVector<int, 16> NewMask;
1532 if (NumSrcElts >= NumDstElts) {
1533 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
1534 // always be expanded to the equivalent form choosing narrower elements.
1535 assert(NumSrcElts % NumDstElts == 0 && "Unexpected shuffle mask");
1536 unsigned ScaleFactor = NumSrcElts / NumDstElts;
1537 narrowShuffleMaskElts(ScaleFactor, OldMask, NewMask);
1538 } else {
1539 // The bitcast is from narrow elements to wide elements. The shuffle mask
1540 // must choose consecutive elements to allow casting first.
1541 assert(NumDstElts % NumSrcElts == 0 && "Unexpected shuffle mask");
1542 unsigned ScaleFactor = NumDstElts / NumSrcElts;
1543 if (!widenShuffleMaskElts(ScaleFactor, OldMask, NewMask))
1544 return false;
1545 }
1546
1547 auto *NewShuffleDstTy =
1548 FixedVectorType::get(CastSrcTy->getScalarType(), NewMask.size());
1549
1550 // Try to replace a castop with a shuffle if the shuffle is not costly.
1552
1553 InstructionCost OldCost =
1554 TTI.getCastInstrCost(C0->getOpcode(), CastDstTy, CastSrcTy,
1556 TTI.getCastInstrCost(C1->getOpcode(), CastDstTy, CastSrcTy,
1558 OldCost +=
1560 OldMask, CostKind, 0, nullptr, std::nullopt, &I);
1561
1563 TargetTransformInfo::SK_PermuteTwoSrc, CastSrcTy, NewMask, CostKind);
1564 NewCost += TTI.getCastInstrCost(Opcode, ShuffleDstTy, NewShuffleDstTy,
1566
1567 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two casts: " << I
1568 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1569 << "\n");
1570 if (NewCost > OldCost)
1571 return false;
1572
1573 Value *Shuf = Builder.CreateShuffleVector(C0->getOperand(0),
1574 C1->getOperand(0), NewMask);
1575 Value *Cast = Builder.CreateCast(Opcode, Shuf, ShuffleDstTy);
1576
1577 // Intersect flags from the old casts.
1578 if (auto *NewInst = dyn_cast<Instruction>(Cast)) {
1579 NewInst->copyIRFlags(C0);
1580 NewInst->andIRFlags(C1);
1581 }
1582
1583 Worklist.pushValue(Shuf);
1584 replaceValue(I, *Cast);
1585 return true;
1586}
1587
1588/// Try to convert "shuffle (shuffle x, undef), (shuffle y, undef)"
1589/// into "shuffle x, y".
1590bool VectorCombine::foldShuffleOfShuffles(Instruction &I) {
1591 Value *V0, *V1;
1592 UndefValue *U0, *U1;
1593 ArrayRef<int> OuterMask, InnerMask0, InnerMask1;
1595 m_Mask(InnerMask0))),
1597 m_Mask(InnerMask1))),
1598 m_Mask(OuterMask))))
1599 return false;
1600
1601 auto *ShufI0 = dyn_cast<Instruction>(I.getOperand(0));
1602 auto *ShufI1 = dyn_cast<Instruction>(I.getOperand(1));
1603 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
1604 auto *ShuffleSrcTy = dyn_cast<FixedVectorType>(V0->getType());
1605 auto *ShuffleImmTy = dyn_cast<FixedVectorType>(I.getOperand(0)->getType());
1606 if (!ShuffleDstTy || !ShuffleSrcTy || !ShuffleImmTy ||
1607 V0->getType() != V1->getType())
1608 return false;
1609
1610 unsigned NumSrcElts = ShuffleSrcTy->getNumElements();
1611 unsigned NumImmElts = ShuffleImmTy->getNumElements();
1612
1613 // Bail if either inner masks reference a RHS undef arg.
1614 if ((!isa<PoisonValue>(U0) &&
1615 any_of(InnerMask0, [&](int M) { return M >= (int)NumSrcElts; })) ||
1616 (!isa<PoisonValue>(U1) &&
1617 any_of(InnerMask1, [&](int M) { return M >= (int)NumSrcElts; })))
1618 return false;
1619
1620 // Merge shuffles - replace index to the RHS poison arg with PoisonMaskElem,
1621 SmallVector<int, 16> NewMask(OuterMask.begin(), OuterMask.end());
1622 for (int &M : NewMask) {
1623 if (0 <= M && M < (int)NumImmElts) {
1624 M = (InnerMask0[M] >= (int)NumSrcElts) ? PoisonMaskElem : InnerMask0[M];
1625 } else if (M >= (int)NumImmElts) {
1626 if (InnerMask1[M - NumImmElts] >= (int)NumSrcElts)
1627 M = PoisonMaskElem;
1628 else
1629 M = InnerMask1[M - NumImmElts] + (V0 == V1 ? 0 : NumSrcElts);
1630 }
1631 }
1632
1633 // Have we folded to an Identity shuffle?
1634 if (ShuffleVectorInst::isIdentityMask(NewMask, NumSrcElts)) {
1635 replaceValue(I, *V0);
1636 return true;
1637 }
1638
1639 // Try to merge the shuffles if the new shuffle is not costly.
1641
1642 InstructionCost OldCost =
1644 InnerMask0, CostKind, 0, nullptr, {V0, U0}, ShufI0) +
1646 InnerMask1, CostKind, 0, nullptr, {V1, U1}, ShufI1) +
1648 OuterMask, CostKind, 0, nullptr, {ShufI0, ShufI1}, &I);
1649
1650 InstructionCost NewCost =
1652 NewMask, CostKind, 0, nullptr, {V0, V1});
1653
1654 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two shuffles: " << I
1655 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1656 << "\n");
1657 if (NewCost > OldCost)
1658 return false;
1659
1660 // Clear unused sources to poison.
1661 if (none_of(NewMask, [&](int M) { return 0 <= M && M < (int)NumSrcElts; }))
1662 V0 = PoisonValue::get(ShuffleSrcTy);
1663 if (none_of(NewMask, [&](int M) { return (int)NumSrcElts <= M; }))
1664 V1 = PoisonValue::get(ShuffleSrcTy);
1665
1666 Value *Shuf = Builder.CreateShuffleVector(V0, V1, NewMask);
1667 replaceValue(I, *Shuf);
1668 return true;
1669}
1670
1671// Starting from a shuffle, look up through operands tracking the shuffled index
1672// of each lane. If we can simplify away the shuffles to identities then
1673// do so.
1674bool VectorCombine::foldShuffleToIdentity(Instruction &I) {
1675 auto *Ty = dyn_cast<FixedVectorType>(I.getType());
1676 if (!Ty || !isa<Instruction>(I.getOperand(0)) ||
1677 !isa<Instruction>(I.getOperand(1)))
1678 return false;
1679
1680 using InstLane = std::pair<Value *, int>;
1681
1682 auto LookThroughShuffles = [](Value *V, int Lane) -> InstLane {
1683 while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
1684 unsigned NumElts =
1685 cast<FixedVectorType>(SV->getOperand(0)->getType())->getNumElements();
1686 int M = SV->getMaskValue(Lane);
1687 if (M < 0)
1688 return {nullptr, PoisonMaskElem};
1689 else if (M < (int)NumElts) {
1690 V = SV->getOperand(0);
1691 Lane = M;
1692 } else {
1693 V = SV->getOperand(1);
1694 Lane = M - NumElts;
1695 }
1696 }
1697 return InstLane{V, Lane};
1698 };
1699
1700 auto GenerateInstLaneVectorFromOperand =
1701 [&LookThroughShuffles](ArrayRef<InstLane> Item, int Op) {
1703 for (InstLane V : Item) {
1704 NItem.emplace_back(
1705 !V.first
1706 ? InstLane{nullptr, PoisonMaskElem}
1707 : LookThroughShuffles(
1708 cast<Instruction>(V.first)->getOperand(Op), V.second));
1709 }
1710 return NItem;
1711 };
1712
1713 SmallVector<InstLane> Start(Ty->getNumElements());
1714 for (unsigned M = 0, E = Ty->getNumElements(); M < E; ++M)
1715 Start[M] = LookThroughShuffles(&I, M);
1716
1718 Worklist.push_back(Start);
1719 SmallPtrSet<Value *, 4> IdentityLeafs, SplatLeafs;
1720 unsigned NumVisited = 0;
1721
1722 while (!Worklist.empty()) {
1723 SmallVector<InstLane> Item = Worklist.pop_back_val();
1724 if (++NumVisited > MaxInstrsToScan)
1725 return false;
1726
1727 // If we found an undef first lane then bail out to keep things simple.
1728 if (!Item[0].first)
1729 return false;
1730
1731 // Look for an identity value.
1732 if (Item[0].second == 0 && Item[0].first->getType() == Ty &&
1733 all_of(drop_begin(enumerate(Item)), [&](const auto &E) {
1734 return !E.value().first || (E.value().first == Item[0].first &&
1735 E.value().second == (int)E.index());
1736 })) {
1737 IdentityLeafs.insert(Item[0].first);
1738 continue;
1739 }
1740 // Look for a splat value.
1741 if (all_of(drop_begin(Item), [&](InstLane &IL) {
1742 return !IL.first ||
1743 (IL.first == Item[0].first && IL.second == Item[0].second);
1744 })) {
1745 SplatLeafs.insert(Item[0].first);
1746 continue;
1747 }
1748
1749 // We need each element to be the same type of value, and check that each
1750 // element has a single use.
1751 if (!all_of(drop_begin(Item), [&](InstLane IL) {
1752 if (!IL.first)
1753 return true;
1754 if (auto *I = dyn_cast<Instruction>(IL.first); I && !I->hasOneUse())
1755 return false;
1756 if (IL.first->getValueID() != Item[0].first->getValueID())
1757 return false;
1758 if (isa<CallInst>(IL.first) && !isa<IntrinsicInst>(IL.first))
1759 return false;
1760 auto *II = dyn_cast<IntrinsicInst>(IL.first);
1761 return !II ||
1762 (isa<IntrinsicInst>(Item[0].first) &&
1763 II->getIntrinsicID() ==
1764 cast<IntrinsicInst>(Item[0].first)->getIntrinsicID());
1765 }))
1766 return false;
1767
1768 // Check the operator is one that we support. We exclude div/rem in case
1769 // they hit UB from poison lanes.
1770 if (isa<BinaryOperator>(Item[0].first) &&
1771 !cast<BinaryOperator>(Item[0].first)->isIntDivRem()) {
1772 Worklist.push_back(GenerateInstLaneVectorFromOperand(Item, 0));
1773 Worklist.push_back(GenerateInstLaneVectorFromOperand(Item, 1));
1774 } else if (isa<UnaryOperator>(Item[0].first)) {
1775 Worklist.push_back(GenerateInstLaneVectorFromOperand(Item, 0));
1776 } else {
1777 return false;
1778 }
1779 }
1780
1781 // If we got this far, we know the shuffles are superfluous and can be
1782 // removed. Scan through again and generate the new tree of instructions.
1783 std::function<Value *(ArrayRef<InstLane>)> Generate =
1784 [&](ArrayRef<InstLane> Item) -> Value * {
1785 if (IdentityLeafs.contains(Item[0].first) &&
1786 all_of(drop_begin(enumerate(Item)), [&](const auto &E) {
1787 return !E.value().first || (E.value().first == Item[0].first &&
1788 E.value().second == (int)E.index());
1789 })) {
1790 return Item[0].first;
1791 }
1792 if (SplatLeafs.contains(Item[0].first)) {
1793 if (auto ILI = dyn_cast<Instruction>(Item[0].first))
1794 Builder.SetInsertPoint(*ILI->getInsertionPointAfterDef());
1795 else if (isa<Argument>(Item[0].first))
1796 Builder.SetInsertPointPastAllocas(I.getParent()->getParent());
1797 SmallVector<int, 16> Mask(Ty->getNumElements(), Item[0].second);
1798 return Builder.CreateShuffleVector(Item[0].first, Mask);
1799 }
1800
1801 auto *I = cast<Instruction>(Item[0].first);
1802 SmallVector<Value *> Ops(I->getNumOperands());
1803 for (unsigned Idx = 0, E = I->getNumOperands(); Idx < E; Idx++)
1804 Ops[Idx] = Generate(GenerateInstLaneVectorFromOperand(Item, Idx));
1805 Builder.SetInsertPoint(I);
1806 if (auto BI = dyn_cast<BinaryOperator>(I))
1807 return Builder.CreateBinOp((Instruction::BinaryOps)BI->getOpcode(),
1808 Ops[0], Ops[1]);
1809 assert(isa<UnaryInstruction>(I) &&
1810 "Unexpected instruction type in Generate");
1811 return Builder.CreateUnOp((Instruction::UnaryOps)I->getOpcode(), Ops[0]);
1812 };
1813
1814 Value *V = Generate(Start);
1815 replaceValue(I, *V);
1816 return true;
1817}
1818
1819/// Given a commutative reduction, the order of the input lanes does not alter
1820/// the results. We can use this to remove certain shuffles feeding the
1821/// reduction, removing the need to shuffle at all.
1822bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
1823 auto *II = dyn_cast<IntrinsicInst>(&I);
1824 if (!II)
1825 return false;
1826 switch (II->getIntrinsicID()) {
1827 case Intrinsic::vector_reduce_add:
1828 case Intrinsic::vector_reduce_mul:
1829 case Intrinsic::vector_reduce_and:
1830 case Intrinsic::vector_reduce_or:
1831 case Intrinsic::vector_reduce_xor:
1832 case Intrinsic::vector_reduce_smin:
1833 case Intrinsic::vector_reduce_smax:
1834 case Intrinsic::vector_reduce_umin:
1835 case Intrinsic::vector_reduce_umax:
1836 break;
1837 default:
1838 return false;
1839 }
1840
1841 // Find all the inputs when looking through operations that do not alter the
1842 // lane order (binops, for example). Currently we look for a single shuffle,
1843 // and can ignore splat values.
1844 std::queue<Value *> Worklist;
1846 ShuffleVectorInst *Shuffle = nullptr;
1847 if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
1848 Worklist.push(Op);
1849
1850 while (!Worklist.empty()) {
1851 Value *CV = Worklist.front();
1852 Worklist.pop();
1853 if (Visited.contains(CV))
1854 continue;
1855
1856 // Splats don't change the order, so can be safely ignored.
1857 if (isSplatValue(CV))
1858 continue;
1859
1860 Visited.insert(CV);
1861
1862 if (auto *CI = dyn_cast<Instruction>(CV)) {
1863 if (CI->isBinaryOp()) {
1864 for (auto *Op : CI->operand_values())
1865 Worklist.push(Op);
1866 continue;
1867 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
1868 if (Shuffle && Shuffle != SV)
1869 return false;
1870 Shuffle = SV;
1871 continue;
1872 }
1873 }
1874
1875 // Anything else is currently an unknown node.
1876 return false;
1877 }
1878
1879 if (!Shuffle)
1880 return false;
1881
1882 // Check all uses of the binary ops and shuffles are also included in the
1883 // lane-invariant operations (Visited should be the list of lanewise
1884 // instructions, including the shuffle that we found).
1885 for (auto *V : Visited)
1886 for (auto *U : V->users())
1887 if (!Visited.contains(U) && U != &I)
1888 return false;
1889
1891 dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
1892 if (!VecType)
1893 return false;
1894 FixedVectorType *ShuffleInputType =
1895 dyn_cast<FixedVectorType>(Shuffle->getOperand(0)->getType());
1896 if (!ShuffleInputType)
1897 return false;
1898 unsigned NumInputElts = ShuffleInputType->getNumElements();
1899
1900 // Find the mask from sorting the lanes into order. This is most likely to
1901 // become a identity or concat mask. Undef elements are pushed to the end.
1902 SmallVector<int> ConcatMask;
1903 Shuffle->getShuffleMask(ConcatMask);
1904 sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
1905 // In the case of a truncating shuffle it's possible for the mask
1906 // to have an index greater than the size of the resulting vector.
1907 // This requires special handling.
1908 bool IsTruncatingShuffle = VecType->getNumElements() < NumInputElts;
1909 bool UsesSecondVec =
1910 any_of(ConcatMask, [&](int M) { return M >= (int)NumInputElts; });
1911
1912 FixedVectorType *VecTyForCost =
1913 (UsesSecondVec && !IsTruncatingShuffle) ? VecType : ShuffleInputType;
1916 VecTyForCost, Shuffle->getShuffleMask());
1919 VecTyForCost, ConcatMask);
1920
1921 LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
1922 << "\n");
1923 LLVM_DEBUG(dbgs() << " OldCost: " << OldCost << " vs NewCost: " << NewCost
1924 << "\n");
1925 if (NewCost < OldCost) {
1926 Builder.SetInsertPoint(Shuffle);
1927 Value *NewShuffle = Builder.CreateShuffleVector(
1928 Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
1929 LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
1930 replaceValue(*Shuffle, *NewShuffle);
1931 }
1932
1933 // See if we can re-use foldSelectShuffle, getting it to reduce the size of
1934 // the shuffle into a nicer order, as it can ignore the order of the shuffles.
1935 return foldSelectShuffle(*Shuffle, true);
1936}
1937
1938/// Determine if its more efficient to fold:
1939/// reduce(trunc(x)) -> trunc(reduce(x)).
1940bool VectorCombine::foldTruncFromReductions(Instruction &I) {
1941 auto *II = dyn_cast<IntrinsicInst>(&I);
1942 if (!II)
1943 return false;
1944
1945 Intrinsic::ID IID = II->getIntrinsicID();
1946 switch (IID) {
1947 case Intrinsic::vector_reduce_add:
1948 case Intrinsic::vector_reduce_mul:
1949 case Intrinsic::vector_reduce_and:
1950 case Intrinsic::vector_reduce_or:
1951 case Intrinsic::vector_reduce_xor:
1952 break;
1953 default:
1954 return false;
1955 }
1956
1957 unsigned ReductionOpc = getArithmeticReductionInstruction(IID);
1958 Value *ReductionSrc = I.getOperand(0);
1959
1960 Value *TruncSrc;
1961 if (!match(ReductionSrc, m_OneUse(m_Trunc(m_Value(TruncSrc)))))
1962 return false;
1963
1964 auto *Trunc = cast<CastInst>(ReductionSrc);
1965 auto *TruncSrcTy = cast<VectorType>(TruncSrc->getType());
1966 auto *ReductionSrcTy = cast<VectorType>(ReductionSrc->getType());
1967 Type *ResultTy = I.getType();
1968
1970 InstructionCost OldCost =
1971 TTI.getCastInstrCost(Instruction::Trunc, ReductionSrcTy, TruncSrcTy,
1973 TTI.getArithmeticReductionCost(ReductionOpc, ReductionSrcTy, std::nullopt,
1974 CostKind);
1975 InstructionCost NewCost =
1976 TTI.getArithmeticReductionCost(ReductionOpc, TruncSrcTy, std::nullopt,
1977 CostKind) +
1978 TTI.getCastInstrCost(Instruction::Trunc, ResultTy,
1979 ReductionSrcTy->getScalarType(),
1981
1982 if (OldCost <= NewCost || !NewCost.isValid())
1983 return false;
1984
1985 Value *NewReduction = Builder.CreateIntrinsic(
1986 TruncSrcTy->getScalarType(), II->getIntrinsicID(), {TruncSrc});
1987 Value *NewTruncation = Builder.CreateTrunc(NewReduction, ResultTy);
1988 replaceValue(I, *NewTruncation);
1989 return true;
1990}
1991
1992/// This method looks for groups of shuffles acting on binops, of the form:
1993/// %x = shuffle ...
1994/// %y = shuffle ...
1995/// %a = binop %x, %y
1996/// %b = binop %x, %y
1997/// shuffle %a, %b, selectmask
1998/// We may, especially if the shuffle is wider than legal, be able to convert
1999/// the shuffle to a form where only parts of a and b need to be computed. On
2000/// architectures with no obvious "select" shuffle, this can reduce the total
2001/// number of operations if the target reports them as cheaper.
2002bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) {
2003 auto *SVI = cast<ShuffleVectorInst>(&I);
2004 auto *VT = cast<FixedVectorType>(I.getType());
2005 auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0));
2006 auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1));
2007 if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
2008 VT != Op0->getType())
2009 return false;
2010
2011 auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0));
2012 auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1));
2013 auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0));
2014 auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1));
2015 SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
2016 auto checkSVNonOpUses = [&](Instruction *I) {
2017 if (!I || I->getOperand(0)->getType() != VT)
2018 return true;
2019 return any_of(I->users(), [&](User *U) {
2020 return U != Op0 && U != Op1 &&
2021 !(isa<ShuffleVectorInst>(U) &&
2022 (InputShuffles.contains(cast<Instruction>(U)) ||
2023 isInstructionTriviallyDead(cast<Instruction>(U))));
2024 });
2025 };
2026 if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
2027 checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
2028 return false;
2029
2030 // Collect all the uses that are shuffles that we can transform together. We
2031 // may not have a single shuffle, but a group that can all be transformed
2032 // together profitably.
2034 auto collectShuffles = [&](Instruction *I) {
2035 for (auto *U : I->users()) {
2036 auto *SV = dyn_cast<ShuffleVectorInst>(U);
2037 if (!SV || SV->getType() != VT)
2038 return false;
2039 if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) ||
2040 (SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1))
2041 return false;
2042 if (!llvm::is_contained(Shuffles, SV))
2043 Shuffles.push_back(SV);
2044 }
2045 return true;
2046 };
2047 if (!collectShuffles(Op0) || !collectShuffles(Op1))
2048 return false;
2049 // From a reduction, we need to be processing a single shuffle, otherwise the
2050 // other uses will not be lane-invariant.
2051 if (FromReduction && Shuffles.size() > 1)
2052 return false;
2053
2054 // Add any shuffle uses for the shuffles we have found, to include them in our
2055 // cost calculations.
2056 if (!FromReduction) {
2057 for (ShuffleVectorInst *SV : Shuffles) {
2058 for (auto *U : SV->users()) {
2059 ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U);
2060 if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT)
2061 Shuffles.push_back(SSV);
2062 }
2063 }
2064 }
2065
2066 // For each of the output shuffles, we try to sort all the first vector
2067 // elements to the beginning, followed by the second array elements at the
2068 // end. If the binops are legalized to smaller vectors, this may reduce total
2069 // number of binops. We compute the ReconstructMask mask needed to convert
2070 // back to the original lane order.
2072 SmallVector<SmallVector<int>> OrigReconstructMasks;
2073 int MaxV1Elt = 0, MaxV2Elt = 0;
2074 unsigned NumElts = VT->getNumElements();
2075 for (ShuffleVectorInst *SVN : Shuffles) {
2077 SVN->getShuffleMask(Mask);
2078
2079 // Check the operands are the same as the original, or reversed (in which
2080 // case we need to commute the mask).
2081 Value *SVOp0 = SVN->getOperand(0);
2082 Value *SVOp1 = SVN->getOperand(1);
2083 if (isa<UndefValue>(SVOp1)) {
2084 auto *SSV = cast<ShuffleVectorInst>(SVOp0);
2085 SVOp0 = SSV->getOperand(0);
2086 SVOp1 = SSV->getOperand(1);
2087 for (unsigned I = 0, E = Mask.size(); I != E; I++) {
2088 if (Mask[I] >= static_cast<int>(SSV->getShuffleMask().size()))
2089 return false;
2090 Mask[I] = Mask[I] < 0 ? Mask[I] : SSV->getMaskValue(Mask[I]);
2091 }
2092 }
2093 if (SVOp0 == Op1 && SVOp1 == Op0) {
2094 std::swap(SVOp0, SVOp1);
2096 }
2097 if (SVOp0 != Op0 || SVOp1 != Op1)
2098 return false;
2099
2100 // Calculate the reconstruction mask for this shuffle, as the mask needed to
2101 // take the packed values from Op0/Op1 and reconstructing to the original
2102 // order.
2103 SmallVector<int> ReconstructMask;
2104 for (unsigned I = 0; I < Mask.size(); I++) {
2105 if (Mask[I] < 0) {
2106 ReconstructMask.push_back(-1);
2107 } else if (Mask[I] < static_cast<int>(NumElts)) {
2108 MaxV1Elt = std::max(MaxV1Elt, Mask[I]);
2109 auto It = find_if(V1, [&](const std::pair<int, int> &A) {
2110 return Mask[I] == A.first;
2111 });
2112 if (It != V1.end())
2113 ReconstructMask.push_back(It - V1.begin());
2114 else {
2115 ReconstructMask.push_back(V1.size());
2116 V1.emplace_back(Mask[I], V1.size());
2117 }
2118 } else {
2119 MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts);
2120 auto It = find_if(V2, [&](const std::pair<int, int> &A) {
2121 return Mask[I] - static_cast<int>(NumElts) == A.first;
2122 });
2123 if (It != V2.end())
2124 ReconstructMask.push_back(NumElts + It - V2.begin());
2125 else {
2126 ReconstructMask.push_back(NumElts + V2.size());
2127 V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size());
2128 }
2129 }
2130 }
2131
2132 // For reductions, we know that the lane ordering out doesn't alter the
2133 // result. In-order can help simplify the shuffle away.
2134 if (FromReduction)
2135 sort(ReconstructMask);
2136 OrigReconstructMasks.push_back(std::move(ReconstructMask));
2137 }
2138
2139 // If the Maximum element used from V1 and V2 are not larger than the new
2140 // vectors, the vectors are already packes and performing the optimization
2141 // again will likely not help any further. This also prevents us from getting
2142 // stuck in a cycle in case the costs do not also rule it out.
2143 if (V1.empty() || V2.empty() ||
2144 (MaxV1Elt == static_cast<int>(V1.size()) - 1 &&
2145 MaxV2Elt == static_cast<int>(V2.size()) - 1))
2146 return false;
2147
2148 // GetBaseMaskValue takes one of the inputs, which may either be a shuffle, a
2149 // shuffle of another shuffle, or not a shuffle (that is treated like a
2150 // identity shuffle).
2151 auto GetBaseMaskValue = [&](Instruction *I, int M) {
2152 auto *SV = dyn_cast<ShuffleVectorInst>(I);
2153 if (!SV)
2154 return M;
2155 if (isa<UndefValue>(SV->getOperand(1)))
2156 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
2157 if (InputShuffles.contains(SSV))
2158 return SSV->getMaskValue(SV->getMaskValue(M));
2159 return SV->getMaskValue(M);
2160 };
2161
2162 // Attempt to sort the inputs my ascending mask values to make simpler input
2163 // shuffles and push complex shuffles down to the uses. We sort on the first
2164 // of the two input shuffle orders, to try and get at least one input into a
2165 // nice order.
2166 auto SortBase = [&](Instruction *A, std::pair<int, int> X,
2167 std::pair<int, int> Y) {
2168 int MXA = GetBaseMaskValue(A, X.first);
2169 int MYA = GetBaseMaskValue(A, Y.first);
2170 return MXA < MYA;
2171 };
2172 stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) {
2173 return SortBase(SVI0A, A, B);
2174 });
2175 stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) {
2176 return SortBase(SVI1A, A, B);
2177 });
2178 // Calculate our ReconstructMasks from the OrigReconstructMasks and the
2179 // modified order of the input shuffles.
2180 SmallVector<SmallVector<int>> ReconstructMasks;
2181 for (const auto &Mask : OrigReconstructMasks) {
2182 SmallVector<int> ReconstructMask;
2183 for (int M : Mask) {
2184 auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) {
2185 auto It = find_if(V, [M](auto A) { return A.second == M; });
2186 assert(It != V.end() && "Expected all entries in Mask");
2187 return std::distance(V.begin(), It);
2188 };
2189 if (M < 0)
2190 ReconstructMask.push_back(-1);
2191 else if (M < static_cast<int>(NumElts)) {
2192 ReconstructMask.push_back(FindIndex(V1, M));
2193 } else {
2194 ReconstructMask.push_back(NumElts + FindIndex(V2, M));
2195 }
2196 }
2197 ReconstructMasks.push_back(std::move(ReconstructMask));
2198 }
2199
2200 // Calculate the masks needed for the new input shuffles, which get padded
2201 // with undef
2202 SmallVector<int> V1A, V1B, V2A, V2B;
2203 for (unsigned I = 0; I < V1.size(); I++) {
2204 V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first));
2205 V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first));
2206 }
2207 for (unsigned I = 0; I < V2.size(); I++) {
2208 V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first));
2209 V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first));
2210 }
2211 while (V1A.size() < NumElts) {
2214 }
2215 while (V2A.size() < NumElts) {
2218 }
2219
2220 auto AddShuffleCost = [&](InstructionCost C, Instruction *I) {
2221 auto *SV = dyn_cast<ShuffleVectorInst>(I);
2222 if (!SV)
2223 return C;
2224 return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1))
2227 VT, SV->getShuffleMask());
2228 };
2229 auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) {
2230 return C + TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, Mask);
2231 };
2232
2233 // Get the costs of the shuffles + binops before and after with the new
2234 // shuffle masks.
2235 InstructionCost CostBefore =
2236 TTI.getArithmeticInstrCost(Op0->getOpcode(), VT) +
2237 TTI.getArithmeticInstrCost(Op1->getOpcode(), VT);
2238 CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
2239 InstructionCost(0), AddShuffleCost);
2240 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
2241 InstructionCost(0), AddShuffleCost);
2242
2243 // The new binops will be unused for lanes past the used shuffle lengths.
2244 // These types attempt to get the correct cost for that from the target.
2245 FixedVectorType *Op0SmallVT =
2246 FixedVectorType::get(VT->getScalarType(), V1.size());
2247 FixedVectorType *Op1SmallVT =
2248 FixedVectorType::get(VT->getScalarType(), V2.size());
2249 InstructionCost CostAfter =
2250 TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT) +
2251 TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT);
2252 CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
2253 InstructionCost(0), AddShuffleMaskCost);
2254 std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
2255 CostAfter +=
2256 std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
2257 InstructionCost(0), AddShuffleMaskCost);
2258
2259 LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n");
2260 LLVM_DEBUG(dbgs() << " CostBefore: " << CostBefore
2261 << " vs CostAfter: " << CostAfter << "\n");
2262 if (CostBefore <= CostAfter)
2263 return false;
2264
2265 // The cost model has passed, create the new instructions.
2266 auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * {
2267 auto *SV = dyn_cast<ShuffleVectorInst>(I);
2268 if (!SV)
2269 return I;
2270 if (isa<UndefValue>(SV->getOperand(1)))
2271 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
2272 if (InputShuffles.contains(SSV))
2273 return SSV->getOperand(Op);
2274 return SV->getOperand(Op);
2275 };
2276 Builder.SetInsertPoint(*SVI0A->getInsertionPointAfterDef());
2277 Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0),
2278 GetShuffleOperand(SVI0A, 1), V1A);
2279 Builder.SetInsertPoint(*SVI0B->getInsertionPointAfterDef());
2280 Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0),
2281 GetShuffleOperand(SVI0B, 1), V1B);
2282 Builder.SetInsertPoint(*SVI1A->getInsertionPointAfterDef());
2283 Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0),
2284 GetShuffleOperand(SVI1A, 1), V2A);
2285 Builder.SetInsertPoint(*SVI1B->getInsertionPointAfterDef());
2286 Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0),
2287 GetShuffleOperand(SVI1B, 1), V2B);
2288 Builder.SetInsertPoint(Op0);
2289 Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(),
2290 NSV0A, NSV0B);
2291 if (auto *I = dyn_cast<Instruction>(NOp0))
2292 I->copyIRFlags(Op0, true);
2293 Builder.SetInsertPoint(Op1);
2294 Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(),
2295 NSV1A, NSV1B);
2296 if (auto *I = dyn_cast<Instruction>(NOp1))
2297 I->copyIRFlags(Op1, true);
2298
2299 for (int S = 0, E = ReconstructMasks.size(); S != E; S++) {
2300 Builder.SetInsertPoint(Shuffles[S]);
2301 Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]);
2302 replaceValue(*Shuffles[S], *NSV);
2303 }
2304
2305 Worklist.pushValue(NSV0A);
2306 Worklist.pushValue(NSV0B);
2307 Worklist.pushValue(NSV1A);
2308 Worklist.pushValue(NSV1B);
2309 for (auto *S : Shuffles)
2310 Worklist.add(S);
2311 return true;
2312}
2313
2314/// This is the entry point for all transforms. Pass manager differences are
2315/// handled in the callers of this function.
2316bool VectorCombine::run() {
2318 return false;
2319
2320 // Don't attempt vectorization if the target does not support vectors.
2321 if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
2322 return false;
2323
2324 bool MadeChange = false;
2325 auto FoldInst = [this, &MadeChange](Instruction &I) {
2326 Builder.SetInsertPoint(&I);
2327 bool IsFixedVectorType = isa<FixedVectorType>(I.getType());
2328 auto Opcode = I.getOpcode();
2329
2330 // These folds should be beneficial regardless of when this pass is run
2331 // in the optimization pipeline.
2332 // The type checking is for run-time efficiency. We can avoid wasting time
2333 // dispatching to folding functions if there's no chance of matching.
2334 if (IsFixedVectorType) {
2335 switch (Opcode) {
2336 case Instruction::InsertElement:
2337 MadeChange |= vectorizeLoadInsert(I);
2338 break;
2339 case Instruction::ShuffleVector:
2340 MadeChange |= widenSubvectorLoad(I);
2341 break;
2342 default:
2343 break;
2344 }
2345 }
2346
2347 // This transform works with scalable and fixed vectors
2348 // TODO: Identify and allow other scalable transforms
2349 if (isa<VectorType>(I.getType())) {
2350 MadeChange |= scalarizeBinopOrCmp(I);
2351 MadeChange |= scalarizeLoadExtract(I);
2352 MadeChange |= scalarizeVPIntrinsic(I);
2353 }
2354
2355 if (Opcode == Instruction::Store)
2356 MadeChange |= foldSingleElementStore(I);
2357
2358 // If this is an early pipeline invocation of this pass, we are done.
2359 if (TryEarlyFoldsOnly)
2360 return;
2361
2362 // Otherwise, try folds that improve codegen but may interfere with
2363 // early IR canonicalizations.
2364 // The type checking is for run-time efficiency. We can avoid wasting time
2365 // dispatching to folding functions if there's no chance of matching.
2366 if (IsFixedVectorType) {
2367 switch (Opcode) {
2368 case Instruction::InsertElement:
2369 MadeChange |= foldInsExtFNeg(I);
2370 break;
2371 case Instruction::ShuffleVector:
2372 MadeChange |= foldShuffleOfBinops(I);
2373 MadeChange |= foldShuffleOfCastops(I);
2374 MadeChange |= foldShuffleOfShuffles(I);
2375 MadeChange |= foldSelectShuffle(I);
2376 MadeChange |= foldShuffleToIdentity(I);
2377 break;
2378 case Instruction::BitCast:
2379 MadeChange |= foldBitcastShuffle(I);
2380 break;
2381 }
2382 } else {
2383 switch (Opcode) {
2384 case Instruction::Call:
2385 MadeChange |= foldShuffleFromReductions(I);
2386 MadeChange |= foldTruncFromReductions(I);
2387 break;
2388 case Instruction::ICmp:
2389 case Instruction::FCmp:
2390 MadeChange |= foldExtractExtract(I);
2391 break;
2392 default:
2393 if (Instruction::isBinaryOp(Opcode)) {
2394 MadeChange |= foldExtractExtract(I);
2395 MadeChange |= foldExtractedCmps(I);
2396 }
2397 break;
2398 }
2399 }
2400 };
2401
2402 for (BasicBlock &BB : F) {
2403 // Ignore unreachable basic blocks.
2404 if (!DT.isReachableFromEntry(&BB))
2405 continue;
2406 // Use early increment range so that we can erase instructions in loop.
2407 for (Instruction &I : make_early_inc_range(BB)) {
2408 if (I.isDebugOrPseudoInst())
2409 continue;
2410 FoldInst(I);
2411 }
2412 }
2413
2414 while (!Worklist.isEmpty()) {
2415 Instruction *I = Worklist.removeOne();
2416 if (!I)
2417 continue;
2418
2421 continue;
2422 }
2423
2424 FoldInst(*I);
2425 }
2426
2427 return MadeChange;
2428}
2429
2432 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
2436 const DataLayout *DL = &F.getParent()->getDataLayout();
2437 VectorCombine Combiner(F, TTI, DT, AA, AC, DL, TryEarlyFoldsOnly);
2438 if (!Combiner.run())
2439 return PreservedAnalyses::all();
2442 return PA;
2443}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static cl::opt< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1291
bool End
Definition: ELF_riscv.cpp:480
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Definition: LICM.cpp:1497
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
if(VerifyEach)
FunctionAnalysisManager FAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned OpIndex
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
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:167
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
This pass exposes codegen information to IR-level passes.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
static Value * createShiftShuffle(Value *Vec, unsigned OldIndex, unsigned NewIndex, IRBuilder<> &Builder)
Create a shuffle that translates (shifts) 1 element from the input vector to a new element location.
static Value * peekThroughBitcasts(Value *V)
Return the source operand of a potentially bitcasted value.
static Align computeAlignmentAfterScalarization(Align VectorAlignment, Type *ScalarType, Value *Idx, const DataLayout &DL)
The memory operation on a vector of ScalarType had alignment of VectorAlignment.
static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx, Instruction *CtxI, AssumptionCache &AC, const DominatorTree &DT)
Check if it is legal to scalarize a memory access to VecTy at index Idx.
static cl::opt< bool > DisableVectorCombine("disable-vector-combine", cl::init(false), cl::Hidden, cl::desc("Disable all vector combine transforms"))
static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI)
static const unsigned InvalidIndex
static cl::opt< unsigned > MaxInstrsToScan("vector-combine-max-scan-instrs", cl::init(30), cl::Hidden, cl::desc("Max number of instructions to scan for vector combining."))
static cl::opt< bool > DisableBinopExtractShuffle("disable-binop-extract-shuffle", cl::init(false), cl::Hidden, cl::desc("Disable binop extract to shuffle transforms"))
static bool isMemModifiedBetween(BasicBlock::iterator Begin, BasicBlock::iterator End, const MemoryLocation &Loc, AAResults &AA)
static ExtractElementInst * translateExtract(ExtractElementInst *ExtElt, unsigned NewIndex, IRBuilder<> &Builder)
Given an extract element instruction with constant index operand, shuffle the source vector (shift th...
A manager for alias analyses.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
Class for arbitrary precision integers.
Definition: APInt.h:76
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:217
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
iterator begin() const
Definition: ArrayRef.h:153
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if the attribute exists for the function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
BinaryOps getOpcode() const
Definition: InstrTypes.h:513
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:70
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1687
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1678
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:1362
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:993
bool isFPPredicate() const
Definition: InstrTypes.h:1122
Combiner implementation.
Definition: Combiner.h:34
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2452
This is the shared class of boolean and integer constants.
Definition: Constants.h:80
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:145
This class represents a range of values.
Definition: ConstantRange.h:47
ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1398
This is an important base class in LLVM.
Definition: Constant.h:41
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Definition: DenseMap.h:235
iterator end()
Definition: DenseMap.h:84
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
This instruction extracts a single (scalar) element from a VectorType value.
Class to represent fixed width SIMD vectors.
Definition: DerivedTypes.h:539
unsigned getNumElements() const
Definition: DerivedTypes.h:582
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:692
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2472
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2460
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1807
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Definition: IRBuilder.cpp:1212
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:932
Value * CreateFNegFMF(Value *V, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1740
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2535
void SetInsertPointPastAllocas(Function *F)
This specifies that created instructions should inserted at the beginning end of the specified functi...
Definition: IRBuilder.h:214
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1876
Value * CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2182
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:491
Value * CreateUnOp(Instruction::UnaryOps Opc, Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1753
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:486
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2366
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2127
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1790
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2494
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1803
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2007
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:569
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1666
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2161
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
InstructionWorklist - This is the worklist management logic for InstCombine and other simplification ...
void pushUsersToWorkList(Instruction &I)
When an instruction is simplified, add all users of the instruction to the work lists because they mi...
void push(Instruction *I)
Push the instruction onto the worklist stack.
void remove(Instruction *I)
Remove I from the worklist if it exists.
bool isBinaryOp() const
Definition: Instruction.h:257
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
bool isIntDivRem() const
Definition: Instruction.h:258
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:54
An instruction for reading from memory.
Definition: Instructions.h:184
Representation for a specific memory location.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1827
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:144
This instruction constructs a fixed permutation of two input vectors.
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
VectorType * getType() const
Overload to return most specific vector type.
static void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
static 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 ...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:366
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
void setAlignment(Align Align)
Definition: Instructions.h:373
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE=nullptr, const SCEV *Ptr=nullptr) const
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of vector reduction intrinsics.
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args=std::nullopt, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
unsigned getMinVectorRegisterBitWidth() const
unsigned getNumberOfRegisters(unsigned ClassID) const
InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp, ArrayRef< int > Mask=std::nullopt, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args=std::nullopt, const Instruction *CxtI=nullptr) const
InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind) const
Estimate the overhead of scalarizing an instruction.
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, Value *Op0=nullptr, Value *Op1=nullptr) const
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_Select
Selects elements from the corresponding lane of either source operand.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ None
The cast is not used with a load/store of any kind.
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:255
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
'undef' values are things that do not have specified contents.
Definition: Constants.h:1348
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
op_range operands()
Definition: User.h:242
Value * getOperand(unsigned i) const
Definition: User.h:169
static bool isVPBinOp(Intrinsic::ID ID)
This is the common base class for vector predication intrinsics.
std::optional< unsigned > getFunctionalIntrinsicID() const
std::optional< unsigned > getFunctionalOpcode() const
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition: Value.h:736
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition: Value.cpp:926
bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition: Value.cpp:149
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
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.
Definition: BitmaskEnum.h:121
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
AttributeList getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:165
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:966
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:810
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:869
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:168
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Definition: PatternMatch.h:245
CastOperator_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:593
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
class_match< UndefValue > m_UndefValue()
Match an arbitrary UndefValue constant.
Definition: PatternMatch.h:155
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
Definition: PatternMatch.h:105
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
match_combine_or< CastInst_match< OpTy, SExtInst >, NNegZExt_match< OpTy > > m_SExtLike(const OpTy &Op)
Match either "sext" or "zext nneg".
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
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.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
@ Offset
Definition: DWP.cpp:456
void stable_sort(R &&Range)
Definition: STLExtras.h:1995
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1715
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:1722
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are are tuples (A,...
Definition: STLExtras.h:2406
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
Definition: LoopUtils.cpp:921
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656
bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
bool widenShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Try to transform a shuffle mask by replacing elements with the scaled index for an equivalent mask of...
Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
ConstantRange computeConstantRange(const Value *V, bool ForSigned, bool UseInstrInfo=true, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition: Local.cpp:400
bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1736
bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
void narrowShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Replace each shuffle mask index with the scaled sequential indices for an equivalent mask of narrowed...
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:212
bool isSafeToLoadUnconditionally(Value *V, Align Alignment, APInt &Size, const DataLayout &DL, Instruction *ScanFrom=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if we know that executing a load from this value cannot trap.
Definition: Loads.cpp:352
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39